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_in_direction);
302 },
303 )
304 .detach();
305
306 cx.on_action(move |_: &workspace::NewFile, cx| {
307 let app_state = workspace::AppState::global(cx);
308 if let Some(app_state) = app_state.upgrade() {
309 workspace::open_new(app_state, cx, |workspace, cx| {
310 Editor::new_file(workspace, &Default::default(), cx)
311 })
312 .detach();
313 }
314 });
315 cx.on_action(move |_: &workspace::NewWindow, cx| {
316 let app_state = workspace::AppState::global(cx);
317 if let Some(app_state) = app_state.upgrade() {
318 workspace::open_new(app_state, cx, |workspace, cx| {
319 Editor::new_file(workspace, &Default::default(), cx)
320 })
321 .detach();
322 }
323 });
324}
325
326pub struct SearchWithinRange;
327
328trait InvalidationRegion {
329 fn ranges(&self) -> &[Range<Anchor>];
330}
331
332#[derive(Clone, Debug, PartialEq)]
333pub enum SelectPhase {
334 Begin {
335 position: DisplayPoint,
336 add: bool,
337 click_count: usize,
338 },
339 BeginColumnar {
340 position: DisplayPoint,
341 reset: bool,
342 goal_column: u32,
343 },
344 Extend {
345 position: DisplayPoint,
346 click_count: usize,
347 },
348 Update {
349 position: DisplayPoint,
350 goal_column: u32,
351 scroll_delta: gpui::Point<f32>,
352 },
353 End,
354}
355
356#[derive(Clone, Debug)]
357pub enum SelectMode {
358 Character,
359 Word(Range<Anchor>),
360 Line(Range<Anchor>),
361 All,
362}
363
364#[derive(Copy, Clone, PartialEq, Eq, Debug)]
365pub enum EditorMode {
366 SingleLine { auto_width: bool },
367 AutoHeight { max_lines: usize },
368 Full,
369}
370
371#[derive(Clone, Debug)]
372pub enum SoftWrap {
373 None,
374 PreferLine,
375 EditorWidth,
376 Column(u32),
377}
378
379#[derive(Clone)]
380pub struct EditorStyle {
381 pub background: Hsla,
382 pub local_player: PlayerColor,
383 pub text: TextStyle,
384 pub scrollbar_width: Pixels,
385 pub syntax: Arc<SyntaxTheme>,
386 pub status: StatusColors,
387 pub inlay_hints_style: HighlightStyle,
388 pub suggestions_style: HighlightStyle,
389 pub unnecessary_code_fade: f32,
390}
391
392impl Default for EditorStyle {
393 fn default() -> Self {
394 Self {
395 background: Hsla::default(),
396 local_player: PlayerColor::default(),
397 text: TextStyle::default(),
398 scrollbar_width: Pixels::default(),
399 syntax: Default::default(),
400 // HACK: Status colors don't have a real default.
401 // We should look into removing the status colors from the editor
402 // style and retrieve them directly from the theme.
403 status: StatusColors::dark(),
404 inlay_hints_style: HighlightStyle::default(),
405 suggestions_style: HighlightStyle::default(),
406 unnecessary_code_fade: Default::default(),
407 }
408 }
409}
410
411type CompletionId = usize;
412
413#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
414struct EditorActionId(usize);
415
416impl EditorActionId {
417 pub fn post_inc(&mut self) -> Self {
418 let answer = self.0;
419
420 *self = Self(answer + 1);
421
422 Self(answer)
423 }
424}
425
426// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
427// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
428
429type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
430type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
431
432#[derive(Default)]
433struct ScrollbarMarkerState {
434 scrollbar_size: Size<Pixels>,
435 dirty: bool,
436 markers: Arc<[PaintQuad]>,
437 pending_refresh: Option<Task<Result<()>>>,
438}
439
440impl ScrollbarMarkerState {
441 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
442 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
443 }
444}
445
446#[derive(Clone, Debug)]
447struct RunnableTasks {
448 templates: Vec<(TaskSourceKind, TaskTemplate)>,
449 offset: MultiBufferOffset,
450 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
451 column: u32,
452 // Values of all named captures, including those starting with '_'
453 extra_variables: HashMap<String, String>,
454 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
455 context_range: Range<BufferOffset>,
456}
457
458#[derive(Clone)]
459struct ResolvedTasks {
460 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
461 position: Anchor,
462}
463#[derive(Copy, Clone, Debug)]
464struct MultiBufferOffset(usize);
465#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
466struct BufferOffset(usize);
467
468// Addons allow storing per-editor state in other crates (e.g. Vim)
469pub trait Addon: 'static {
470 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
471
472 fn to_any(&self) -> &dyn std::any::Any;
473}
474
475/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
476///
477/// See the [module level documentation](self) for more information.
478pub struct Editor {
479 focus_handle: FocusHandle,
480 last_focused_descendant: Option<WeakFocusHandle>,
481 /// The text buffer being edited
482 buffer: Model<MultiBuffer>,
483 /// Map of how text in the buffer should be displayed.
484 /// Handles soft wraps, folds, fake inlay text insertions, etc.
485 pub display_map: Model<DisplayMap>,
486 pub selections: SelectionsCollection,
487 pub scroll_manager: ScrollManager,
488 /// When inline assist editors are linked, they all render cursors because
489 /// typing enters text into each of them, even the ones that aren't focused.
490 pub(crate) show_cursor_when_unfocused: bool,
491 columnar_selection_tail: Option<Anchor>,
492 add_selections_state: Option<AddSelectionsState>,
493 select_next_state: Option<SelectNextState>,
494 select_prev_state: Option<SelectNextState>,
495 selection_history: SelectionHistory,
496 autoclose_regions: Vec<AutocloseRegion>,
497 snippet_stack: InvalidationStack<SnippetState>,
498 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
499 ime_transaction: Option<TransactionId>,
500 active_diagnostics: Option<ActiveDiagnosticGroup>,
501 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
502 project: Option<Model<Project>>,
503 completion_provider: Option<Box<dyn CompletionProvider>>,
504 collaboration_hub: Option<Box<dyn CollaborationHub>>,
505 blink_manager: Model<BlinkManager>,
506 show_cursor_names: bool,
507 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
508 pub show_local_selections: bool,
509 mode: EditorMode,
510 show_breadcrumbs: bool,
511 show_gutter: bool,
512 show_line_numbers: Option<bool>,
513 show_git_diff_gutter: Option<bool>,
514 show_code_actions: Option<bool>,
515 show_runnables: Option<bool>,
516 show_wrap_guides: Option<bool>,
517 show_indent_guides: Option<bool>,
518 placeholder_text: Option<Arc<str>>,
519 highlight_order: usize,
520 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
521 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
522 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
523 scrollbar_marker_state: ScrollbarMarkerState,
524 active_indent_guides_state: ActiveIndentGuidesState,
525 nav_history: Option<ItemNavHistory>,
526 context_menu: RwLock<Option<ContextMenu>>,
527 mouse_context_menu: Option<MouseContextMenu>,
528 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
529 signature_help_state: SignatureHelpState,
530 auto_signature_help: Option<bool>,
531 find_all_references_task_sources: Vec<Anchor>,
532 next_completion_id: CompletionId,
533 completion_documentation_pre_resolve_debounce: DebouncedDelay,
534 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
535 code_actions_task: Option<Task<()>>,
536 document_highlights_task: Option<Task<()>>,
537 linked_editing_range_task: Option<Task<Option<()>>>,
538 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
539 pending_rename: Option<RenameState>,
540 searchable: bool,
541 cursor_shape: CursorShape,
542 current_line_highlight: Option<CurrentLineHighlight>,
543 collapse_matches: bool,
544 autoindent_mode: Option<AutoindentMode>,
545 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
546 input_enabled: bool,
547 use_modal_editing: bool,
548 read_only: bool,
549 leader_peer_id: Option<PeerId>,
550 remote_id: Option<ViewId>,
551 hover_state: HoverState,
552 gutter_hovered: bool,
553 hovered_link_state: Option<HoveredLinkState>,
554 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
555 active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
556 show_inline_completions: bool,
557 inlay_hint_cache: InlayHintCache,
558 expanded_hunks: ExpandedHunks,
559 next_inlay_id: usize,
560 _subscriptions: Vec<Subscription>,
561 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
562 gutter_dimensions: GutterDimensions,
563 style: Option<EditorStyle>,
564 next_editor_action_id: EditorActionId,
565 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
566 use_autoclose: bool,
567 use_auto_surround: bool,
568 auto_replace_emoji_shortcode: bool,
569 show_git_blame_gutter: bool,
570 show_git_blame_inline: bool,
571 show_git_blame_inline_delay_task: Option<Task<()>>,
572 git_blame_inline_enabled: bool,
573 serialize_dirty_buffers: bool,
574 show_selection_menu: Option<bool>,
575 blame: Option<Model<GitBlame>>,
576 blame_subscription: Option<Subscription>,
577 custom_context_menu: Option<
578 Box<
579 dyn 'static
580 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
581 >,
582 >,
583 last_bounds: Option<Bounds<Pixels>>,
584 expect_bounds_change: Option<Bounds<Pixels>>,
585 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
586 tasks_update_task: Option<Task<()>>,
587 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
588 file_header_size: u32,
589 breadcrumb_header: Option<String>,
590 focused_block: Option<FocusedBlock>,
591 next_scroll_position: NextScrollCursorCenterTopBottom,
592 addons: HashMap<TypeId, Box<dyn Addon>>,
593 _scroll_cursor_center_top_bottom_task: Task<()>,
594}
595
596#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
597enum NextScrollCursorCenterTopBottom {
598 #[default]
599 Center,
600 Top,
601 Bottom,
602}
603
604impl NextScrollCursorCenterTopBottom {
605 fn next(&self) -> Self {
606 match self {
607 Self::Center => Self::Top,
608 Self::Top => Self::Bottom,
609 Self::Bottom => Self::Center,
610 }
611 }
612}
613
614#[derive(Clone)]
615pub struct EditorSnapshot {
616 pub mode: EditorMode,
617 show_gutter: bool,
618 show_line_numbers: Option<bool>,
619 show_git_diff_gutter: Option<bool>,
620 show_code_actions: Option<bool>,
621 show_runnables: Option<bool>,
622 render_git_blame_gutter: bool,
623 pub display_snapshot: DisplaySnapshot,
624 pub placeholder_text: Option<Arc<str>>,
625 is_focused: bool,
626 scroll_anchor: ScrollAnchor,
627 ongoing_scroll: OngoingScroll,
628 current_line_highlight: CurrentLineHighlight,
629 gutter_hovered: bool,
630}
631
632const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
633
634#[derive(Default, Debug, Clone, Copy)]
635pub struct GutterDimensions {
636 pub left_padding: Pixels,
637 pub right_padding: Pixels,
638 pub width: Pixels,
639 pub margin: Pixels,
640 pub git_blame_entries_width: Option<Pixels>,
641}
642
643impl GutterDimensions {
644 /// The full width of the space taken up by the gutter.
645 pub fn full_width(&self) -> Pixels {
646 self.margin + self.width
647 }
648
649 /// The width of the space reserved for the fold indicators,
650 /// use alongside 'justify_end' and `gutter_width` to
651 /// right align content with the line numbers
652 pub fn fold_area_width(&self) -> Pixels {
653 self.margin + self.right_padding
654 }
655}
656
657#[derive(Debug)]
658pub struct RemoteSelection {
659 pub replica_id: ReplicaId,
660 pub selection: Selection<Anchor>,
661 pub cursor_shape: CursorShape,
662 pub peer_id: PeerId,
663 pub line_mode: bool,
664 pub participant_index: Option<ParticipantIndex>,
665 pub user_name: Option<SharedString>,
666}
667
668#[derive(Clone, Debug)]
669struct SelectionHistoryEntry {
670 selections: Arc<[Selection<Anchor>]>,
671 select_next_state: Option<SelectNextState>,
672 select_prev_state: Option<SelectNextState>,
673 add_selections_state: Option<AddSelectionsState>,
674}
675
676enum SelectionHistoryMode {
677 Normal,
678 Undoing,
679 Redoing,
680}
681
682#[derive(Clone, PartialEq, Eq, Hash)]
683struct HoveredCursor {
684 replica_id: u16,
685 selection_id: usize,
686}
687
688impl Default for SelectionHistoryMode {
689 fn default() -> Self {
690 Self::Normal
691 }
692}
693
694#[derive(Default)]
695struct SelectionHistory {
696 #[allow(clippy::type_complexity)]
697 selections_by_transaction:
698 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
699 mode: SelectionHistoryMode,
700 undo_stack: VecDeque<SelectionHistoryEntry>,
701 redo_stack: VecDeque<SelectionHistoryEntry>,
702}
703
704impl SelectionHistory {
705 fn insert_transaction(
706 &mut self,
707 transaction_id: TransactionId,
708 selections: Arc<[Selection<Anchor>]>,
709 ) {
710 self.selections_by_transaction
711 .insert(transaction_id, (selections, None));
712 }
713
714 #[allow(clippy::type_complexity)]
715 fn transaction(
716 &self,
717 transaction_id: TransactionId,
718 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
719 self.selections_by_transaction.get(&transaction_id)
720 }
721
722 #[allow(clippy::type_complexity)]
723 fn transaction_mut(
724 &mut self,
725 transaction_id: TransactionId,
726 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
727 self.selections_by_transaction.get_mut(&transaction_id)
728 }
729
730 fn push(&mut self, entry: SelectionHistoryEntry) {
731 if !entry.selections.is_empty() {
732 match self.mode {
733 SelectionHistoryMode::Normal => {
734 self.push_undo(entry);
735 self.redo_stack.clear();
736 }
737 SelectionHistoryMode::Undoing => self.push_redo(entry),
738 SelectionHistoryMode::Redoing => self.push_undo(entry),
739 }
740 }
741 }
742
743 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
744 if self
745 .undo_stack
746 .back()
747 .map_or(true, |e| e.selections != entry.selections)
748 {
749 self.undo_stack.push_back(entry);
750 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
751 self.undo_stack.pop_front();
752 }
753 }
754 }
755
756 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
757 if self
758 .redo_stack
759 .back()
760 .map_or(true, |e| e.selections != entry.selections)
761 {
762 self.redo_stack.push_back(entry);
763 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
764 self.redo_stack.pop_front();
765 }
766 }
767 }
768}
769
770struct RowHighlight {
771 index: usize,
772 range: RangeInclusive<Anchor>,
773 color: Option<Hsla>,
774 should_autoscroll: bool,
775}
776
777#[derive(Clone, Debug)]
778struct AddSelectionsState {
779 above: bool,
780 stack: Vec<usize>,
781}
782
783#[derive(Clone)]
784struct SelectNextState {
785 query: AhoCorasick,
786 wordwise: bool,
787 done: bool,
788}
789
790impl std::fmt::Debug for SelectNextState {
791 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
792 f.debug_struct(std::any::type_name::<Self>())
793 .field("wordwise", &self.wordwise)
794 .field("done", &self.done)
795 .finish()
796 }
797}
798
799#[derive(Debug)]
800struct AutocloseRegion {
801 selection_id: usize,
802 range: Range<Anchor>,
803 pair: BracketPair,
804}
805
806#[derive(Debug)]
807struct SnippetState {
808 ranges: Vec<Vec<Range<Anchor>>>,
809 active_index: usize,
810}
811
812#[doc(hidden)]
813pub struct RenameState {
814 pub range: Range<Anchor>,
815 pub old_name: Arc<str>,
816 pub editor: View<Editor>,
817 block_id: CustomBlockId,
818}
819
820struct InvalidationStack<T>(Vec<T>);
821
822struct RegisteredInlineCompletionProvider {
823 provider: Arc<dyn InlineCompletionProviderHandle>,
824 _subscription: Subscription,
825}
826
827enum ContextMenu {
828 Completions(CompletionsMenu),
829 CodeActions(CodeActionsMenu),
830}
831
832impl ContextMenu {
833 fn select_first(
834 &mut self,
835 project: Option<&Model<Project>>,
836 cx: &mut ViewContext<Editor>,
837 ) -> bool {
838 if self.visible() {
839 match self {
840 ContextMenu::Completions(menu) => menu.select_first(project, cx),
841 ContextMenu::CodeActions(menu) => menu.select_first(cx),
842 }
843 true
844 } else {
845 false
846 }
847 }
848
849 fn select_prev(
850 &mut self,
851 project: Option<&Model<Project>>,
852 cx: &mut ViewContext<Editor>,
853 ) -> bool {
854 if self.visible() {
855 match self {
856 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
857 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
858 }
859 true
860 } else {
861 false
862 }
863 }
864
865 fn select_next(
866 &mut self,
867 project: Option<&Model<Project>>,
868 cx: &mut ViewContext<Editor>,
869 ) -> bool {
870 if self.visible() {
871 match self {
872 ContextMenu::Completions(menu) => menu.select_next(project, cx),
873 ContextMenu::CodeActions(menu) => menu.select_next(cx),
874 }
875 true
876 } else {
877 false
878 }
879 }
880
881 fn select_last(
882 &mut self,
883 project: Option<&Model<Project>>,
884 cx: &mut ViewContext<Editor>,
885 ) -> bool {
886 if self.visible() {
887 match self {
888 ContextMenu::Completions(menu) => menu.select_last(project, cx),
889 ContextMenu::CodeActions(menu) => menu.select_last(cx),
890 }
891 true
892 } else {
893 false
894 }
895 }
896
897 fn visible(&self) -> bool {
898 match self {
899 ContextMenu::Completions(menu) => menu.visible(),
900 ContextMenu::CodeActions(menu) => menu.visible(),
901 }
902 }
903
904 fn render(
905 &self,
906 cursor_position: DisplayPoint,
907 style: &EditorStyle,
908 max_height: Pixels,
909 workspace: Option<WeakView<Workspace>>,
910 cx: &mut ViewContext<Editor>,
911 ) -> (ContextMenuOrigin, AnyElement) {
912 match self {
913 ContextMenu::Completions(menu) => (
914 ContextMenuOrigin::EditorPoint(cursor_position),
915 menu.render(style, max_height, workspace, cx),
916 ),
917 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
918 }
919 }
920}
921
922enum ContextMenuOrigin {
923 EditorPoint(DisplayPoint),
924 GutterIndicator(DisplayRow),
925}
926
927#[derive(Clone)]
928struct CompletionsMenu {
929 id: CompletionId,
930 sort_completions: bool,
931 initial_position: Anchor,
932 buffer: Model<Buffer>,
933 completions: Arc<RwLock<Box<[Completion]>>>,
934 match_candidates: Arc<[StringMatchCandidate]>,
935 matches: Arc<[StringMatch]>,
936 selected_item: usize,
937 scroll_handle: UniformListScrollHandle,
938 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
939}
940
941impl CompletionsMenu {
942 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
943 self.selected_item = 0;
944 self.scroll_handle.scroll_to_item(self.selected_item);
945 self.attempt_resolve_selected_completion_documentation(project, cx);
946 cx.notify();
947 }
948
949 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
950 if self.selected_item > 0 {
951 self.selected_item -= 1;
952 } else {
953 self.selected_item = self.matches.len() - 1;
954 }
955 self.scroll_handle.scroll_to_item(self.selected_item);
956 self.attempt_resolve_selected_completion_documentation(project, cx);
957 cx.notify();
958 }
959
960 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
961 if self.selected_item + 1 < self.matches.len() {
962 self.selected_item += 1;
963 } else {
964 self.selected_item = 0;
965 }
966 self.scroll_handle.scroll_to_item(self.selected_item);
967 self.attempt_resolve_selected_completion_documentation(project, cx);
968 cx.notify();
969 }
970
971 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
972 self.selected_item = self.matches.len() - 1;
973 self.scroll_handle.scroll_to_item(self.selected_item);
974 self.attempt_resolve_selected_completion_documentation(project, cx);
975 cx.notify();
976 }
977
978 fn pre_resolve_completion_documentation(
979 buffer: Model<Buffer>,
980 completions: Arc<RwLock<Box<[Completion]>>>,
981 matches: Arc<[StringMatch]>,
982 editor: &Editor,
983 cx: &mut ViewContext<Editor>,
984 ) -> Task<()> {
985 let settings = EditorSettings::get_global(cx);
986 if !settings.show_completion_documentation {
987 return Task::ready(());
988 }
989
990 let Some(provider) = editor.completion_provider.as_ref() else {
991 return Task::ready(());
992 };
993
994 let resolve_task = provider.resolve_completions(
995 buffer,
996 matches.iter().map(|m| m.candidate_id).collect(),
997 completions.clone(),
998 cx,
999 );
1000
1001 return cx.spawn(move |this, mut cx| async move {
1002 if let Some(true) = resolve_task.await.log_err() {
1003 this.update(&mut cx, |_, cx| cx.notify()).ok();
1004 }
1005 });
1006 }
1007
1008 fn attempt_resolve_selected_completion_documentation(
1009 &mut self,
1010 project: Option<&Model<Project>>,
1011 cx: &mut ViewContext<Editor>,
1012 ) {
1013 let settings = EditorSettings::get_global(cx);
1014 if !settings.show_completion_documentation {
1015 return;
1016 }
1017
1018 let completion_index = self.matches[self.selected_item].candidate_id;
1019 let Some(project) = project else {
1020 return;
1021 };
1022
1023 let resolve_task = project.update(cx, |project, cx| {
1024 project.resolve_completions(
1025 self.buffer.clone(),
1026 vec![completion_index],
1027 self.completions.clone(),
1028 cx,
1029 )
1030 });
1031
1032 let delay_ms =
1033 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1034 let delay = Duration::from_millis(delay_ms);
1035
1036 self.selected_completion_documentation_resolve_debounce
1037 .lock()
1038 .fire_new(delay, cx, |_, cx| {
1039 cx.spawn(move |this, mut cx| async move {
1040 if let Some(true) = resolve_task.await.log_err() {
1041 this.update(&mut cx, |_, cx| cx.notify()).ok();
1042 }
1043 })
1044 });
1045 }
1046
1047 fn visible(&self) -> bool {
1048 !self.matches.is_empty()
1049 }
1050
1051 fn render(
1052 &self,
1053 style: &EditorStyle,
1054 max_height: Pixels,
1055 workspace: Option<WeakView<Workspace>>,
1056 cx: &mut ViewContext<Editor>,
1057 ) -> AnyElement {
1058 let settings = EditorSettings::get_global(cx);
1059 let show_completion_documentation = settings.show_completion_documentation;
1060
1061 let widest_completion_ix = self
1062 .matches
1063 .iter()
1064 .enumerate()
1065 .max_by_key(|(_, mat)| {
1066 let completions = self.completions.read();
1067 let completion = &completions[mat.candidate_id];
1068 let documentation = &completion.documentation;
1069
1070 let mut len = completion.label.text.chars().count();
1071 if let Some(Documentation::SingleLine(text)) = documentation {
1072 if show_completion_documentation {
1073 len += text.chars().count();
1074 }
1075 }
1076
1077 len
1078 })
1079 .map(|(ix, _)| ix);
1080
1081 let completions = self.completions.clone();
1082 let matches = self.matches.clone();
1083 let selected_item = self.selected_item;
1084 let style = style.clone();
1085
1086 let multiline_docs = if show_completion_documentation {
1087 let mat = &self.matches[selected_item];
1088 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1089 Some(Documentation::MultiLinePlainText(text)) => {
1090 Some(div().child(SharedString::from(text.clone())))
1091 }
1092 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1093 Some(div().child(render_parsed_markdown(
1094 "completions_markdown",
1095 parsed,
1096 &style,
1097 workspace,
1098 cx,
1099 )))
1100 }
1101 _ => None,
1102 };
1103 multiline_docs.map(|div| {
1104 div.id("multiline_docs")
1105 .max_h(max_height)
1106 .flex_1()
1107 .px_1p5()
1108 .py_1()
1109 .min_w(px(260.))
1110 .max_w(px(640.))
1111 .w(px(500.))
1112 .overflow_y_scroll()
1113 .occlude()
1114 })
1115 } else {
1116 None
1117 };
1118
1119 let list = uniform_list(
1120 cx.view().clone(),
1121 "completions",
1122 matches.len(),
1123 move |_editor, range, cx| {
1124 let start_ix = range.start;
1125 let completions_guard = completions.read();
1126
1127 matches[range]
1128 .iter()
1129 .enumerate()
1130 .map(|(ix, mat)| {
1131 let item_ix = start_ix + ix;
1132 let candidate_id = mat.candidate_id;
1133 let completion = &completions_guard[candidate_id];
1134
1135 let documentation = if show_completion_documentation {
1136 &completion.documentation
1137 } else {
1138 &None
1139 };
1140
1141 let highlights = gpui::combine_highlights(
1142 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1143 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1144 |(range, mut highlight)| {
1145 // Ignore font weight for syntax highlighting, as we'll use it
1146 // for fuzzy matches.
1147 highlight.font_weight = None;
1148
1149 if completion.lsp_completion.deprecated.unwrap_or(false) {
1150 highlight.strikethrough = Some(StrikethroughStyle {
1151 thickness: 1.0.into(),
1152 ..Default::default()
1153 });
1154 highlight.color = Some(cx.theme().colors().text_muted);
1155 }
1156
1157 (range, highlight)
1158 },
1159 ),
1160 );
1161 let completion_label = StyledText::new(completion.label.text.clone())
1162 .with_highlights(&style.text, highlights);
1163 let documentation_label =
1164 if let Some(Documentation::SingleLine(text)) = documentation {
1165 if text.trim().is_empty() {
1166 None
1167 } else {
1168 Some(
1169 Label::new(text.clone())
1170 .ml_4()
1171 .size(LabelSize::Small)
1172 .color(Color::Muted),
1173 )
1174 }
1175 } else {
1176 None
1177 };
1178
1179 div().min_w(px(220.)).max_w(px(540.)).child(
1180 ListItem::new(mat.candidate_id)
1181 .inset(true)
1182 .selected(item_ix == selected_item)
1183 .on_click(cx.listener(move |editor, _event, cx| {
1184 cx.stop_propagation();
1185 if let Some(task) = editor.confirm_completion(
1186 &ConfirmCompletion {
1187 item_ix: Some(item_ix),
1188 },
1189 cx,
1190 ) {
1191 task.detach_and_log_err(cx)
1192 }
1193 }))
1194 .child(h_flex().overflow_hidden().child(completion_label))
1195 .end_slot::<Label>(documentation_label),
1196 )
1197 })
1198 .collect()
1199 },
1200 )
1201 .occlude()
1202 .max_h(max_height)
1203 .track_scroll(self.scroll_handle.clone())
1204 .with_width_from_item(widest_completion_ix)
1205 .with_sizing_behavior(ListSizingBehavior::Infer);
1206
1207 Popover::new()
1208 .child(list)
1209 .when_some(multiline_docs, |popover, multiline_docs| {
1210 popover.aside(multiline_docs)
1211 })
1212 .into_any_element()
1213 }
1214
1215 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1216 let mut matches = if let Some(query) = query {
1217 fuzzy::match_strings(
1218 &self.match_candidates,
1219 query,
1220 query.chars().any(|c| c.is_uppercase()),
1221 100,
1222 &Default::default(),
1223 executor,
1224 )
1225 .await
1226 } else {
1227 self.match_candidates
1228 .iter()
1229 .enumerate()
1230 .map(|(candidate_id, candidate)| StringMatch {
1231 candidate_id,
1232 score: Default::default(),
1233 positions: Default::default(),
1234 string: candidate.string.clone(),
1235 })
1236 .collect()
1237 };
1238
1239 // Remove all candidates where the query's start does not match the start of any word in the candidate
1240 if let Some(query) = query {
1241 if let Some(query_start) = query.chars().next() {
1242 matches.retain(|string_match| {
1243 split_words(&string_match.string).any(|word| {
1244 // Check that the first codepoint of the word as lowercase matches the first
1245 // codepoint of the query as lowercase
1246 word.chars()
1247 .flat_map(|codepoint| codepoint.to_lowercase())
1248 .zip(query_start.to_lowercase())
1249 .all(|(word_cp, query_cp)| word_cp == query_cp)
1250 })
1251 });
1252 }
1253 }
1254
1255 let completions = self.completions.read();
1256 if self.sort_completions {
1257 matches.sort_unstable_by_key(|mat| {
1258 // We do want to strike a balance here between what the language server tells us
1259 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1260 // `Creat` and there is a local variable called `CreateComponent`).
1261 // So what we do is: we bucket all matches into two buckets
1262 // - Strong matches
1263 // - Weak matches
1264 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1265 // and the Weak matches are the rest.
1266 //
1267 // For the strong matches, we sort by the language-servers score first and for the weak
1268 // matches, we prefer our fuzzy finder first.
1269 //
1270 // The thinking behind that: it's useless to take the sort_text the language-server gives
1271 // us into account when it's obviously a bad match.
1272
1273 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1274 enum MatchScore<'a> {
1275 Strong {
1276 sort_text: Option<&'a str>,
1277 score: Reverse<OrderedFloat<f64>>,
1278 sort_key: (usize, &'a str),
1279 },
1280 Weak {
1281 score: Reverse<OrderedFloat<f64>>,
1282 sort_text: Option<&'a str>,
1283 sort_key: (usize, &'a str),
1284 },
1285 }
1286
1287 let completion = &completions[mat.candidate_id];
1288 let sort_key = completion.sort_key();
1289 let sort_text = completion.lsp_completion.sort_text.as_deref();
1290 let score = Reverse(OrderedFloat(mat.score));
1291
1292 if mat.score >= 0.2 {
1293 MatchScore::Strong {
1294 sort_text,
1295 score,
1296 sort_key,
1297 }
1298 } else {
1299 MatchScore::Weak {
1300 score,
1301 sort_text,
1302 sort_key,
1303 }
1304 }
1305 });
1306 }
1307
1308 for mat in &mut matches {
1309 let completion = &completions[mat.candidate_id];
1310 mat.string.clone_from(&completion.label.text);
1311 for position in &mut mat.positions {
1312 *position += completion.label.filter_range.start;
1313 }
1314 }
1315 drop(completions);
1316
1317 self.matches = matches.into();
1318 self.selected_item = 0;
1319 }
1320}
1321
1322#[derive(Clone)]
1323struct CodeActionContents {
1324 tasks: Option<Arc<ResolvedTasks>>,
1325 actions: Option<Arc<[CodeAction]>>,
1326}
1327
1328impl CodeActionContents {
1329 fn len(&self) -> usize {
1330 match (&self.tasks, &self.actions) {
1331 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1332 (Some(tasks), None) => tasks.templates.len(),
1333 (None, Some(actions)) => actions.len(),
1334 (None, None) => 0,
1335 }
1336 }
1337
1338 fn is_empty(&self) -> bool {
1339 match (&self.tasks, &self.actions) {
1340 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1341 (Some(tasks), None) => tasks.templates.is_empty(),
1342 (None, Some(actions)) => actions.is_empty(),
1343 (None, None) => true,
1344 }
1345 }
1346
1347 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1348 self.tasks
1349 .iter()
1350 .flat_map(|tasks| {
1351 tasks
1352 .templates
1353 .iter()
1354 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1355 })
1356 .chain(self.actions.iter().flat_map(|actions| {
1357 actions
1358 .iter()
1359 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1360 }))
1361 }
1362 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1363 match (&self.tasks, &self.actions) {
1364 (Some(tasks), Some(actions)) => {
1365 if index < tasks.templates.len() {
1366 tasks
1367 .templates
1368 .get(index)
1369 .cloned()
1370 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1371 } else {
1372 actions
1373 .get(index - tasks.templates.len())
1374 .cloned()
1375 .map(CodeActionsItem::CodeAction)
1376 }
1377 }
1378 (Some(tasks), None) => tasks
1379 .templates
1380 .get(index)
1381 .cloned()
1382 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1383 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1384 (None, None) => None,
1385 }
1386 }
1387}
1388
1389#[allow(clippy::large_enum_variant)]
1390#[derive(Clone)]
1391enum CodeActionsItem {
1392 Task(TaskSourceKind, ResolvedTask),
1393 CodeAction(CodeAction),
1394}
1395
1396impl CodeActionsItem {
1397 fn as_task(&self) -> Option<&ResolvedTask> {
1398 let Self::Task(_, task) = self else {
1399 return None;
1400 };
1401 Some(task)
1402 }
1403 fn as_code_action(&self) -> Option<&CodeAction> {
1404 let Self::CodeAction(action) = self else {
1405 return None;
1406 };
1407 Some(action)
1408 }
1409 fn label(&self) -> String {
1410 match self {
1411 Self::CodeAction(action) => action.lsp_action.title.clone(),
1412 Self::Task(_, task) => task.resolved_label.clone(),
1413 }
1414 }
1415}
1416
1417struct CodeActionsMenu {
1418 actions: CodeActionContents,
1419 buffer: Model<Buffer>,
1420 selected_item: usize,
1421 scroll_handle: UniformListScrollHandle,
1422 deployed_from_indicator: Option<DisplayRow>,
1423}
1424
1425impl CodeActionsMenu {
1426 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1427 self.selected_item = 0;
1428 self.scroll_handle.scroll_to_item(self.selected_item);
1429 cx.notify()
1430 }
1431
1432 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1433 if self.selected_item > 0 {
1434 self.selected_item -= 1;
1435 } else {
1436 self.selected_item = self.actions.len() - 1;
1437 }
1438 self.scroll_handle.scroll_to_item(self.selected_item);
1439 cx.notify();
1440 }
1441
1442 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1443 if self.selected_item + 1 < self.actions.len() {
1444 self.selected_item += 1;
1445 } else {
1446 self.selected_item = 0;
1447 }
1448 self.scroll_handle.scroll_to_item(self.selected_item);
1449 cx.notify();
1450 }
1451
1452 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1453 self.selected_item = self.actions.len() - 1;
1454 self.scroll_handle.scroll_to_item(self.selected_item);
1455 cx.notify()
1456 }
1457
1458 fn visible(&self) -> bool {
1459 !self.actions.is_empty()
1460 }
1461
1462 fn render(
1463 &self,
1464 cursor_position: DisplayPoint,
1465 _style: &EditorStyle,
1466 max_height: Pixels,
1467 cx: &mut ViewContext<Editor>,
1468 ) -> (ContextMenuOrigin, AnyElement) {
1469 let actions = self.actions.clone();
1470 let selected_item = self.selected_item;
1471 let element = uniform_list(
1472 cx.view().clone(),
1473 "code_actions_menu",
1474 self.actions.len(),
1475 move |_this, range, cx| {
1476 actions
1477 .iter()
1478 .skip(range.start)
1479 .take(range.end - range.start)
1480 .enumerate()
1481 .map(|(ix, action)| {
1482 let item_ix = range.start + ix;
1483 let selected = selected_item == item_ix;
1484 let colors = cx.theme().colors();
1485 div()
1486 .px_2()
1487 .text_color(colors.text)
1488 .when(selected, |style| {
1489 style
1490 .bg(colors.element_active)
1491 .text_color(colors.text_accent)
1492 })
1493 .hover(|style| {
1494 style
1495 .bg(colors.element_hover)
1496 .text_color(colors.text_accent)
1497 })
1498 .whitespace_nowrap()
1499 .when_some(action.as_code_action(), |this, action| {
1500 this.on_mouse_down(
1501 MouseButton::Left,
1502 cx.listener(move |editor, _, cx| {
1503 cx.stop_propagation();
1504 if let Some(task) = editor.confirm_code_action(
1505 &ConfirmCodeAction {
1506 item_ix: Some(item_ix),
1507 },
1508 cx,
1509 ) {
1510 task.detach_and_log_err(cx)
1511 }
1512 }),
1513 )
1514 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1515 .child(SharedString::from(action.lsp_action.title.clone()))
1516 })
1517 .when_some(action.as_task(), |this, task| {
1518 this.on_mouse_down(
1519 MouseButton::Left,
1520 cx.listener(move |editor, _, cx| {
1521 cx.stop_propagation();
1522 if let Some(task) = editor.confirm_code_action(
1523 &ConfirmCodeAction {
1524 item_ix: Some(item_ix),
1525 },
1526 cx,
1527 ) {
1528 task.detach_and_log_err(cx)
1529 }
1530 }),
1531 )
1532 .child(SharedString::from(task.resolved_label.clone()))
1533 })
1534 })
1535 .collect()
1536 },
1537 )
1538 .elevation_1(cx)
1539 .px_2()
1540 .py_1()
1541 .max_h(max_height)
1542 .occlude()
1543 .track_scroll(self.scroll_handle.clone())
1544 .with_width_from_item(
1545 self.actions
1546 .iter()
1547 .enumerate()
1548 .max_by_key(|(_, action)| match action {
1549 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1550 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1551 })
1552 .map(|(ix, _)| ix),
1553 )
1554 .with_sizing_behavior(ListSizingBehavior::Infer)
1555 .into_any_element();
1556
1557 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1558 ContextMenuOrigin::GutterIndicator(row)
1559 } else {
1560 ContextMenuOrigin::EditorPoint(cursor_position)
1561 };
1562
1563 (cursor_position, element)
1564 }
1565}
1566
1567#[derive(Debug)]
1568struct ActiveDiagnosticGroup {
1569 primary_range: Range<Anchor>,
1570 primary_message: String,
1571 group_id: usize,
1572 blocks: HashMap<CustomBlockId, Diagnostic>,
1573 is_valid: bool,
1574}
1575
1576#[derive(Serialize, Deserialize, Clone, Debug)]
1577pub struct ClipboardSelection {
1578 pub len: usize,
1579 pub is_entire_line: bool,
1580 pub first_line_indent: u32,
1581}
1582
1583#[derive(Debug)]
1584pub(crate) struct NavigationData {
1585 cursor_anchor: Anchor,
1586 cursor_position: Point,
1587 scroll_anchor: ScrollAnchor,
1588 scroll_top_row: u32,
1589}
1590
1591#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1592enum GotoDefinitionKind {
1593 Symbol,
1594 Declaration,
1595 Type,
1596 Implementation,
1597}
1598
1599#[derive(Debug, Clone)]
1600enum InlayHintRefreshReason {
1601 Toggle(bool),
1602 SettingsChange(InlayHintSettings),
1603 NewLinesShown,
1604 BufferEdited(HashSet<Arc<Language>>),
1605 RefreshRequested,
1606 ExcerptsRemoved(Vec<ExcerptId>),
1607}
1608
1609impl InlayHintRefreshReason {
1610 fn description(&self) -> &'static str {
1611 match self {
1612 Self::Toggle(_) => "toggle",
1613 Self::SettingsChange(_) => "settings change",
1614 Self::NewLinesShown => "new lines shown",
1615 Self::BufferEdited(_) => "buffer edited",
1616 Self::RefreshRequested => "refresh requested",
1617 Self::ExcerptsRemoved(_) => "excerpts removed",
1618 }
1619 }
1620}
1621
1622pub(crate) struct FocusedBlock {
1623 id: BlockId,
1624 focus_handle: WeakFocusHandle,
1625}
1626
1627impl Editor {
1628 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1629 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1630 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1631 Self::new(
1632 EditorMode::SingleLine { auto_width: false },
1633 buffer,
1634 None,
1635 false,
1636 cx,
1637 )
1638 }
1639
1640 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1641 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1642 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1643 Self::new(EditorMode::Full, buffer, None, false, cx)
1644 }
1645
1646 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1647 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1648 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1649 Self::new(
1650 EditorMode::SingleLine { auto_width: true },
1651 buffer,
1652 None,
1653 false,
1654 cx,
1655 )
1656 }
1657
1658 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1659 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1660 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1661 Self::new(
1662 EditorMode::AutoHeight { max_lines },
1663 buffer,
1664 None,
1665 false,
1666 cx,
1667 )
1668 }
1669
1670 pub fn for_buffer(
1671 buffer: Model<Buffer>,
1672 project: Option<Model<Project>>,
1673 cx: &mut ViewContext<Self>,
1674 ) -> Self {
1675 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1676 Self::new(EditorMode::Full, buffer, project, false, cx)
1677 }
1678
1679 pub fn for_multibuffer(
1680 buffer: Model<MultiBuffer>,
1681 project: Option<Model<Project>>,
1682 show_excerpt_controls: bool,
1683 cx: &mut ViewContext<Self>,
1684 ) -> Self {
1685 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1686 }
1687
1688 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1689 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1690 let mut clone = Self::new(
1691 self.mode,
1692 self.buffer.clone(),
1693 self.project.clone(),
1694 show_excerpt_controls,
1695 cx,
1696 );
1697 self.display_map.update(cx, |display_map, cx| {
1698 let snapshot = display_map.snapshot(cx);
1699 clone.display_map.update(cx, |display_map, cx| {
1700 display_map.set_state(&snapshot, cx);
1701 });
1702 });
1703 clone.selections.clone_state(&self.selections);
1704 clone.scroll_manager.clone_state(&self.scroll_manager);
1705 clone.searchable = self.searchable;
1706 clone
1707 }
1708
1709 pub fn new(
1710 mode: EditorMode,
1711 buffer: Model<MultiBuffer>,
1712 project: Option<Model<Project>>,
1713 show_excerpt_controls: bool,
1714 cx: &mut ViewContext<Self>,
1715 ) -> Self {
1716 let style = cx.text_style();
1717 let font_size = style.font_size.to_pixels(cx.rem_size());
1718 let editor = cx.view().downgrade();
1719 let fold_placeholder = FoldPlaceholder {
1720 constrain_width: true,
1721 render: Arc::new(move |fold_id, fold_range, cx| {
1722 let editor = editor.clone();
1723 div()
1724 .id(fold_id)
1725 .bg(cx.theme().colors().ghost_element_background)
1726 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1727 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1728 .rounded_sm()
1729 .size_full()
1730 .cursor_pointer()
1731 .child("⋯")
1732 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1733 .on_click(move |_, cx| {
1734 editor
1735 .update(cx, |editor, cx| {
1736 editor.unfold_ranges(
1737 [fold_range.start..fold_range.end],
1738 true,
1739 false,
1740 cx,
1741 );
1742 cx.stop_propagation();
1743 })
1744 .ok();
1745 })
1746 .into_any()
1747 }),
1748 merge_adjacent: true,
1749 };
1750 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1751 let display_map = cx.new_model(|cx| {
1752 DisplayMap::new(
1753 buffer.clone(),
1754 style.font(),
1755 font_size,
1756 None,
1757 show_excerpt_controls,
1758 file_header_size,
1759 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1760 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1761 fold_placeholder,
1762 cx,
1763 )
1764 });
1765
1766 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1767
1768 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1769
1770 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1771 .then(|| language_settings::SoftWrap::PreferLine);
1772
1773 let mut project_subscriptions = Vec::new();
1774 if mode == EditorMode::Full {
1775 if let Some(project) = project.as_ref() {
1776 if buffer.read(cx).is_singleton() {
1777 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1778 cx.emit(EditorEvent::TitleChanged);
1779 }));
1780 }
1781 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1782 if let project::Event::RefreshInlayHints = event {
1783 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1784 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1785 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1786 let focus_handle = editor.focus_handle(cx);
1787 if focus_handle.is_focused(cx) {
1788 let snapshot = buffer.read(cx).snapshot();
1789 for (range, snippet) in snippet_edits {
1790 let editor_range =
1791 language::range_from_lsp(*range).to_offset(&snapshot);
1792 editor
1793 .insert_snippet(&[editor_range], snippet.clone(), cx)
1794 .ok();
1795 }
1796 }
1797 }
1798 }
1799 }));
1800 let task_inventory = project.read(cx).task_inventory().clone();
1801 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1802 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1803 }));
1804 }
1805 }
1806
1807 let inlay_hint_settings = inlay_hint_settings(
1808 selections.newest_anchor().head(),
1809 &buffer.read(cx).snapshot(cx),
1810 cx,
1811 );
1812 let focus_handle = cx.focus_handle();
1813 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1814 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1815 .detach();
1816 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1817 .detach();
1818 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1819
1820 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1821 Some(false)
1822 } else {
1823 None
1824 };
1825
1826 let mut this = Self {
1827 focus_handle,
1828 show_cursor_when_unfocused: false,
1829 last_focused_descendant: None,
1830 buffer: buffer.clone(),
1831 display_map: display_map.clone(),
1832 selections,
1833 scroll_manager: ScrollManager::new(cx),
1834 columnar_selection_tail: None,
1835 add_selections_state: None,
1836 select_next_state: None,
1837 select_prev_state: None,
1838 selection_history: Default::default(),
1839 autoclose_regions: Default::default(),
1840 snippet_stack: Default::default(),
1841 select_larger_syntax_node_stack: Vec::new(),
1842 ime_transaction: Default::default(),
1843 active_diagnostics: None,
1844 soft_wrap_mode_override,
1845 completion_provider: project.clone().map(|project| Box::new(project) as _),
1846 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1847 project,
1848 blink_manager: blink_manager.clone(),
1849 show_local_selections: true,
1850 mode,
1851 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1852 show_gutter: mode == EditorMode::Full,
1853 show_line_numbers: None,
1854 show_git_diff_gutter: None,
1855 show_code_actions: None,
1856 show_runnables: None,
1857 show_wrap_guides: None,
1858 show_indent_guides,
1859 placeholder_text: None,
1860 highlight_order: 0,
1861 highlighted_rows: HashMap::default(),
1862 background_highlights: Default::default(),
1863 gutter_highlights: TreeMap::default(),
1864 scrollbar_marker_state: ScrollbarMarkerState::default(),
1865 active_indent_guides_state: ActiveIndentGuidesState::default(),
1866 nav_history: None,
1867 context_menu: RwLock::new(None),
1868 mouse_context_menu: None,
1869 completion_tasks: Default::default(),
1870 signature_help_state: SignatureHelpState::default(),
1871 auto_signature_help: None,
1872 find_all_references_task_sources: Vec::new(),
1873 next_completion_id: 0,
1874 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1875 next_inlay_id: 0,
1876 available_code_actions: Default::default(),
1877 code_actions_task: Default::default(),
1878 document_highlights_task: Default::default(),
1879 linked_editing_range_task: Default::default(),
1880 pending_rename: Default::default(),
1881 searchable: true,
1882 cursor_shape: Default::default(),
1883 current_line_highlight: None,
1884 autoindent_mode: Some(AutoindentMode::EachLine),
1885 collapse_matches: false,
1886 workspace: None,
1887 input_enabled: true,
1888 use_modal_editing: mode == EditorMode::Full,
1889 read_only: false,
1890 use_autoclose: true,
1891 use_auto_surround: true,
1892 auto_replace_emoji_shortcode: false,
1893 leader_peer_id: None,
1894 remote_id: None,
1895 hover_state: Default::default(),
1896 hovered_link_state: Default::default(),
1897 inline_completion_provider: None,
1898 active_inline_completion: None,
1899 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1900 expanded_hunks: ExpandedHunks::default(),
1901 gutter_hovered: false,
1902 pixel_position_of_newest_cursor: None,
1903 last_bounds: None,
1904 expect_bounds_change: None,
1905 gutter_dimensions: GutterDimensions::default(),
1906 style: None,
1907 show_cursor_names: false,
1908 hovered_cursors: Default::default(),
1909 next_editor_action_id: EditorActionId::default(),
1910 editor_actions: Rc::default(),
1911 show_inline_completions: mode == EditorMode::Full,
1912 custom_context_menu: None,
1913 show_git_blame_gutter: false,
1914 show_git_blame_inline: false,
1915 show_selection_menu: None,
1916 show_git_blame_inline_delay_task: None,
1917 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1918 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1919 .session
1920 .restore_unsaved_buffers,
1921 blame: None,
1922 blame_subscription: None,
1923 file_header_size,
1924 tasks: Default::default(),
1925 _subscriptions: vec![
1926 cx.observe(&buffer, Self::on_buffer_changed),
1927 cx.subscribe(&buffer, Self::on_buffer_event),
1928 cx.observe(&display_map, Self::on_display_map_changed),
1929 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1930 cx.observe_global::<SettingsStore>(Self::settings_changed),
1931 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1932 cx.observe_window_activation(|editor, cx| {
1933 let active = cx.is_window_active();
1934 editor.blink_manager.update(cx, |blink_manager, cx| {
1935 if active {
1936 blink_manager.enable(cx);
1937 } else {
1938 blink_manager.disable(cx);
1939 }
1940 });
1941 }),
1942 ],
1943 tasks_update_task: None,
1944 linked_edit_ranges: Default::default(),
1945 previous_search_ranges: None,
1946 breadcrumb_header: None,
1947 focused_block: None,
1948 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1949 addons: HashMap::default(),
1950 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1951 };
1952 this.tasks_update_task = Some(this.refresh_runnables(cx));
1953 this._subscriptions.extend(project_subscriptions);
1954
1955 this.end_selection(cx);
1956 this.scroll_manager.show_scrollbar(cx);
1957
1958 if mode == EditorMode::Full {
1959 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1960 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1961
1962 if this.git_blame_inline_enabled {
1963 this.git_blame_inline_enabled = true;
1964 this.start_git_blame_inline(false, cx);
1965 }
1966 }
1967
1968 this.report_editor_event("open", None, cx);
1969 this
1970 }
1971
1972 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1973 self.mouse_context_menu
1974 .as_ref()
1975 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1976 }
1977
1978 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1979 let mut key_context = KeyContext::new_with_defaults();
1980 key_context.add("Editor");
1981 let mode = match self.mode {
1982 EditorMode::SingleLine { .. } => "single_line",
1983 EditorMode::AutoHeight { .. } => "auto_height",
1984 EditorMode::Full => "full",
1985 };
1986
1987 if EditorSettings::jupyter_enabled(cx) {
1988 key_context.add("jupyter");
1989 }
1990
1991 key_context.set("mode", mode);
1992 if self.pending_rename.is_some() {
1993 key_context.add("renaming");
1994 }
1995 if self.context_menu_visible() {
1996 match self.context_menu.read().as_ref() {
1997 Some(ContextMenu::Completions(_)) => {
1998 key_context.add("menu");
1999 key_context.add("showing_completions")
2000 }
2001 Some(ContextMenu::CodeActions(_)) => {
2002 key_context.add("menu");
2003 key_context.add("showing_code_actions")
2004 }
2005 None => {}
2006 }
2007 }
2008
2009 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2010 if !self.focus_handle(cx).contains_focused(cx)
2011 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2012 {
2013 for addon in self.addons.values() {
2014 addon.extend_key_context(&mut key_context, cx)
2015 }
2016 }
2017
2018 if let Some(extension) = self
2019 .buffer
2020 .read(cx)
2021 .as_singleton()
2022 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2023 {
2024 key_context.set("extension", extension.to_string());
2025 }
2026
2027 if self.has_active_inline_completion(cx) {
2028 key_context.add("copilot_suggestion");
2029 key_context.add("inline_completion");
2030 }
2031
2032 key_context
2033 }
2034
2035 pub fn new_file(
2036 workspace: &mut Workspace,
2037 _: &workspace::NewFile,
2038 cx: &mut ViewContext<Workspace>,
2039 ) {
2040 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2041 "Failed to create buffer",
2042 cx,
2043 |e, _| match e.error_code() {
2044 ErrorCode::RemoteUpgradeRequired => Some(format!(
2045 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2046 e.error_tag("required").unwrap_or("the latest version")
2047 )),
2048 _ => None,
2049 },
2050 );
2051 }
2052
2053 pub fn new_in_workspace(
2054 workspace: &mut Workspace,
2055 cx: &mut ViewContext<Workspace>,
2056 ) -> Task<Result<View<Editor>>> {
2057 let project = workspace.project().clone();
2058 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2059
2060 cx.spawn(|workspace, mut cx| async move {
2061 let buffer = create.await?;
2062 workspace.update(&mut cx, |workspace, cx| {
2063 let editor =
2064 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2065 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2066 editor
2067 })
2068 })
2069 }
2070
2071 pub fn new_file_in_direction(
2072 workspace: &mut Workspace,
2073 action: &workspace::NewFileInDirection,
2074 cx: &mut ViewContext<Workspace>,
2075 ) {
2076 let project = workspace.project().clone();
2077 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2078 let direction = action.0;
2079
2080 cx.spawn(|workspace, mut cx| async move {
2081 let buffer = create.await?;
2082 workspace.update(&mut cx, move |workspace, cx| {
2083 workspace.split_item(
2084 direction,
2085 Box::new(
2086 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2087 ),
2088 cx,
2089 )
2090 })?;
2091 anyhow::Ok(())
2092 })
2093 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2094 ErrorCode::RemoteUpgradeRequired => Some(format!(
2095 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2096 e.error_tag("required").unwrap_or("the latest version")
2097 )),
2098 _ => None,
2099 });
2100 }
2101
2102 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2103 self.buffer.read(cx).replica_id()
2104 }
2105
2106 pub fn leader_peer_id(&self) -> Option<PeerId> {
2107 self.leader_peer_id
2108 }
2109
2110 pub fn buffer(&self) -> &Model<MultiBuffer> {
2111 &self.buffer
2112 }
2113
2114 pub fn workspace(&self) -> Option<View<Workspace>> {
2115 self.workspace.as_ref()?.0.upgrade()
2116 }
2117
2118 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2119 self.buffer().read(cx).title(cx)
2120 }
2121
2122 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2123 EditorSnapshot {
2124 mode: self.mode,
2125 show_gutter: self.show_gutter,
2126 show_line_numbers: self.show_line_numbers,
2127 show_git_diff_gutter: self.show_git_diff_gutter,
2128 show_code_actions: self.show_code_actions,
2129 show_runnables: self.show_runnables,
2130 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2131 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2132 scroll_anchor: self.scroll_manager.anchor(),
2133 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2134 placeholder_text: self.placeholder_text.clone(),
2135 is_focused: self.focus_handle.is_focused(cx),
2136 current_line_highlight: self
2137 .current_line_highlight
2138 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2139 gutter_hovered: self.gutter_hovered,
2140 }
2141 }
2142
2143 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2144 self.buffer.read(cx).language_at(point, cx)
2145 }
2146
2147 pub fn file_at<T: ToOffset>(
2148 &self,
2149 point: T,
2150 cx: &AppContext,
2151 ) -> Option<Arc<dyn language::File>> {
2152 self.buffer.read(cx).read(cx).file_at(point).cloned()
2153 }
2154
2155 pub fn active_excerpt(
2156 &self,
2157 cx: &AppContext,
2158 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2159 self.buffer
2160 .read(cx)
2161 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2162 }
2163
2164 pub fn mode(&self) -> EditorMode {
2165 self.mode
2166 }
2167
2168 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2169 self.collaboration_hub.as_deref()
2170 }
2171
2172 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2173 self.collaboration_hub = Some(hub);
2174 }
2175
2176 pub fn set_custom_context_menu(
2177 &mut self,
2178 f: impl 'static
2179 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2180 ) {
2181 self.custom_context_menu = Some(Box::new(f))
2182 }
2183
2184 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2185 self.completion_provider = Some(provider);
2186 }
2187
2188 pub fn set_inline_completion_provider<T>(
2189 &mut self,
2190 provider: Option<Model<T>>,
2191 cx: &mut ViewContext<Self>,
2192 ) where
2193 T: InlineCompletionProvider,
2194 {
2195 self.inline_completion_provider =
2196 provider.map(|provider| RegisteredInlineCompletionProvider {
2197 _subscription: cx.observe(&provider, |this, _, cx| {
2198 if this.focus_handle.is_focused(cx) {
2199 this.update_visible_inline_completion(cx);
2200 }
2201 }),
2202 provider: Arc::new(provider),
2203 });
2204 self.refresh_inline_completion(false, false, cx);
2205 }
2206
2207 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2208 self.placeholder_text.as_deref()
2209 }
2210
2211 pub fn set_placeholder_text(
2212 &mut self,
2213 placeholder_text: impl Into<Arc<str>>,
2214 cx: &mut ViewContext<Self>,
2215 ) {
2216 let placeholder_text = Some(placeholder_text.into());
2217 if self.placeholder_text != placeholder_text {
2218 self.placeholder_text = placeholder_text;
2219 cx.notify();
2220 }
2221 }
2222
2223 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2224 self.cursor_shape = cursor_shape;
2225
2226 // Disrupt blink for immediate user feedback that the cursor shape has changed
2227 self.blink_manager.update(cx, BlinkManager::show_cursor);
2228
2229 cx.notify();
2230 }
2231
2232 pub fn set_current_line_highlight(
2233 &mut self,
2234 current_line_highlight: Option<CurrentLineHighlight>,
2235 ) {
2236 self.current_line_highlight = current_line_highlight;
2237 }
2238
2239 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2240 self.collapse_matches = collapse_matches;
2241 }
2242
2243 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2244 if self.collapse_matches {
2245 return range.start..range.start;
2246 }
2247 range.clone()
2248 }
2249
2250 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2251 if self.display_map.read(cx).clip_at_line_ends != clip {
2252 self.display_map
2253 .update(cx, |map, _| map.clip_at_line_ends = clip);
2254 }
2255 }
2256
2257 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2258 self.input_enabled = input_enabled;
2259 }
2260
2261 pub fn set_autoindent(&mut self, autoindent: bool) {
2262 if autoindent {
2263 self.autoindent_mode = Some(AutoindentMode::EachLine);
2264 } else {
2265 self.autoindent_mode = None;
2266 }
2267 }
2268
2269 pub fn read_only(&self, cx: &AppContext) -> bool {
2270 self.read_only || self.buffer.read(cx).read_only()
2271 }
2272
2273 pub fn set_read_only(&mut self, read_only: bool) {
2274 self.read_only = read_only;
2275 }
2276
2277 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2278 self.use_autoclose = autoclose;
2279 }
2280
2281 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2282 self.use_auto_surround = auto_surround;
2283 }
2284
2285 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2286 self.auto_replace_emoji_shortcode = auto_replace;
2287 }
2288
2289 pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
2290 self.show_inline_completions = show_inline_completions;
2291 }
2292
2293 pub fn set_use_modal_editing(&mut self, to: bool) {
2294 self.use_modal_editing = to;
2295 }
2296
2297 pub fn use_modal_editing(&self) -> bool {
2298 self.use_modal_editing
2299 }
2300
2301 fn selections_did_change(
2302 &mut self,
2303 local: bool,
2304 old_cursor_position: &Anchor,
2305 show_completions: bool,
2306 cx: &mut ViewContext<Self>,
2307 ) {
2308 // Copy selections to primary selection buffer
2309 #[cfg(target_os = "linux")]
2310 if local {
2311 let selections = self.selections.all::<usize>(cx);
2312 let buffer_handle = self.buffer.read(cx).read(cx);
2313
2314 let mut text = String::new();
2315 for (index, selection) in selections.iter().enumerate() {
2316 let text_for_selection = buffer_handle
2317 .text_for_range(selection.start..selection.end)
2318 .collect::<String>();
2319
2320 text.push_str(&text_for_selection);
2321 if index != selections.len() - 1 {
2322 text.push('\n');
2323 }
2324 }
2325
2326 if !text.is_empty() {
2327 cx.write_to_primary(ClipboardItem::new_string(text));
2328 }
2329 }
2330
2331 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2332 self.buffer.update(cx, |buffer, cx| {
2333 buffer.set_active_selections(
2334 &self.selections.disjoint_anchors(),
2335 self.selections.line_mode,
2336 self.cursor_shape,
2337 cx,
2338 )
2339 });
2340 }
2341 let display_map = self
2342 .display_map
2343 .update(cx, |display_map, cx| display_map.snapshot(cx));
2344 let buffer = &display_map.buffer_snapshot;
2345 self.add_selections_state = None;
2346 self.select_next_state = None;
2347 self.select_prev_state = None;
2348 self.select_larger_syntax_node_stack.clear();
2349 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2350 self.snippet_stack
2351 .invalidate(&self.selections.disjoint_anchors(), buffer);
2352 self.take_rename(false, cx);
2353
2354 let new_cursor_position = self.selections.newest_anchor().head();
2355
2356 self.push_to_nav_history(
2357 *old_cursor_position,
2358 Some(new_cursor_position.to_point(buffer)),
2359 cx,
2360 );
2361
2362 if local {
2363 let new_cursor_position = self.selections.newest_anchor().head();
2364 let mut context_menu = self.context_menu.write();
2365 let completion_menu = match context_menu.as_ref() {
2366 Some(ContextMenu::Completions(menu)) => Some(menu),
2367
2368 _ => {
2369 *context_menu = None;
2370 None
2371 }
2372 };
2373
2374 if let Some(completion_menu) = completion_menu {
2375 let cursor_position = new_cursor_position.to_offset(buffer);
2376 let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
2377 if kind == Some(CharKind::Word)
2378 && word_range.to_inclusive().contains(&cursor_position)
2379 {
2380 let mut completion_menu = completion_menu.clone();
2381 drop(context_menu);
2382
2383 let query = Self::completion_query(buffer, cursor_position);
2384 cx.spawn(move |this, mut cx| async move {
2385 completion_menu
2386 .filter(query.as_deref(), cx.background_executor().clone())
2387 .await;
2388
2389 this.update(&mut cx, |this, cx| {
2390 let mut context_menu = this.context_menu.write();
2391 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2392 return;
2393 };
2394
2395 if menu.id > completion_menu.id {
2396 return;
2397 }
2398
2399 *context_menu = Some(ContextMenu::Completions(completion_menu));
2400 drop(context_menu);
2401 cx.notify();
2402 })
2403 })
2404 .detach();
2405
2406 if show_completions {
2407 self.show_completions(&ShowCompletions { trigger: None }, cx);
2408 }
2409 } else {
2410 drop(context_menu);
2411 self.hide_context_menu(cx);
2412 }
2413 } else {
2414 drop(context_menu);
2415 }
2416
2417 hide_hover(self, cx);
2418
2419 if old_cursor_position.to_display_point(&display_map).row()
2420 != new_cursor_position.to_display_point(&display_map).row()
2421 {
2422 self.available_code_actions.take();
2423 }
2424 self.refresh_code_actions(cx);
2425 self.refresh_document_highlights(cx);
2426 refresh_matching_bracket_highlights(self, cx);
2427 self.discard_inline_completion(false, cx);
2428 linked_editing_ranges::refresh_linked_ranges(self, cx);
2429 if self.git_blame_inline_enabled {
2430 self.start_inline_blame_timer(cx);
2431 }
2432 }
2433
2434 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2435 cx.emit(EditorEvent::SelectionsChanged { local });
2436
2437 if self.selections.disjoint_anchors().len() == 1 {
2438 cx.emit(SearchEvent::ActiveMatchChanged)
2439 }
2440 cx.notify();
2441 }
2442
2443 pub fn change_selections<R>(
2444 &mut self,
2445 autoscroll: Option<Autoscroll>,
2446 cx: &mut ViewContext<Self>,
2447 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2448 ) -> R {
2449 self.change_selections_inner(autoscroll, true, cx, change)
2450 }
2451
2452 pub fn change_selections_inner<R>(
2453 &mut self,
2454 autoscroll: Option<Autoscroll>,
2455 request_completions: bool,
2456 cx: &mut ViewContext<Self>,
2457 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2458 ) -> R {
2459 let old_cursor_position = self.selections.newest_anchor().head();
2460 self.push_to_selection_history();
2461
2462 let (changed, result) = self.selections.change_with(cx, change);
2463
2464 if changed {
2465 if let Some(autoscroll) = autoscroll {
2466 self.request_autoscroll(autoscroll, cx);
2467 }
2468 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2469
2470 if self.should_open_signature_help_automatically(
2471 &old_cursor_position,
2472 self.signature_help_state.backspace_pressed(),
2473 cx,
2474 ) {
2475 self.show_signature_help(&ShowSignatureHelp, cx);
2476 }
2477 self.signature_help_state.set_backspace_pressed(false);
2478 }
2479
2480 result
2481 }
2482
2483 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2484 where
2485 I: IntoIterator<Item = (Range<S>, T)>,
2486 S: ToOffset,
2487 T: Into<Arc<str>>,
2488 {
2489 if self.read_only(cx) {
2490 return;
2491 }
2492
2493 self.buffer
2494 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2495 }
2496
2497 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2498 where
2499 I: IntoIterator<Item = (Range<S>, T)>,
2500 S: ToOffset,
2501 T: Into<Arc<str>>,
2502 {
2503 if self.read_only(cx) {
2504 return;
2505 }
2506
2507 self.buffer.update(cx, |buffer, cx| {
2508 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2509 });
2510 }
2511
2512 pub fn edit_with_block_indent<I, S, T>(
2513 &mut self,
2514 edits: I,
2515 original_indent_columns: Vec<u32>,
2516 cx: &mut ViewContext<Self>,
2517 ) where
2518 I: IntoIterator<Item = (Range<S>, T)>,
2519 S: ToOffset,
2520 T: Into<Arc<str>>,
2521 {
2522 if self.read_only(cx) {
2523 return;
2524 }
2525
2526 self.buffer.update(cx, |buffer, cx| {
2527 buffer.edit(
2528 edits,
2529 Some(AutoindentMode::Block {
2530 original_indent_columns,
2531 }),
2532 cx,
2533 )
2534 });
2535 }
2536
2537 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2538 self.hide_context_menu(cx);
2539
2540 match phase {
2541 SelectPhase::Begin {
2542 position,
2543 add,
2544 click_count,
2545 } => self.begin_selection(position, add, click_count, cx),
2546 SelectPhase::BeginColumnar {
2547 position,
2548 goal_column,
2549 reset,
2550 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2551 SelectPhase::Extend {
2552 position,
2553 click_count,
2554 } => self.extend_selection(position, click_count, cx),
2555 SelectPhase::Update {
2556 position,
2557 goal_column,
2558 scroll_delta,
2559 } => self.update_selection(position, goal_column, scroll_delta, cx),
2560 SelectPhase::End => self.end_selection(cx),
2561 }
2562 }
2563
2564 fn extend_selection(
2565 &mut self,
2566 position: DisplayPoint,
2567 click_count: usize,
2568 cx: &mut ViewContext<Self>,
2569 ) {
2570 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2571 let tail = self.selections.newest::<usize>(cx).tail();
2572 self.begin_selection(position, false, click_count, cx);
2573
2574 let position = position.to_offset(&display_map, Bias::Left);
2575 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2576
2577 let mut pending_selection = self
2578 .selections
2579 .pending_anchor()
2580 .expect("extend_selection not called with pending selection");
2581 if position >= tail {
2582 pending_selection.start = tail_anchor;
2583 } else {
2584 pending_selection.end = tail_anchor;
2585 pending_selection.reversed = true;
2586 }
2587
2588 let mut pending_mode = self.selections.pending_mode().unwrap();
2589 match &mut pending_mode {
2590 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2591 _ => {}
2592 }
2593
2594 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2595 s.set_pending(pending_selection, pending_mode)
2596 });
2597 }
2598
2599 fn begin_selection(
2600 &mut self,
2601 position: DisplayPoint,
2602 add: bool,
2603 click_count: usize,
2604 cx: &mut ViewContext<Self>,
2605 ) {
2606 if !self.focus_handle.is_focused(cx) {
2607 self.last_focused_descendant = None;
2608 cx.focus(&self.focus_handle);
2609 }
2610
2611 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2612 let buffer = &display_map.buffer_snapshot;
2613 let newest_selection = self.selections.newest_anchor().clone();
2614 let position = display_map.clip_point(position, Bias::Left);
2615
2616 let start;
2617 let end;
2618 let mode;
2619 let auto_scroll;
2620 match click_count {
2621 1 => {
2622 start = buffer.anchor_before(position.to_point(&display_map));
2623 end = start;
2624 mode = SelectMode::Character;
2625 auto_scroll = true;
2626 }
2627 2 => {
2628 let range = movement::surrounding_word(&display_map, position);
2629 start = buffer.anchor_before(range.start.to_point(&display_map));
2630 end = buffer.anchor_before(range.end.to_point(&display_map));
2631 mode = SelectMode::Word(start..end);
2632 auto_scroll = true;
2633 }
2634 3 => {
2635 let position = display_map
2636 .clip_point(position, Bias::Left)
2637 .to_point(&display_map);
2638 let line_start = display_map.prev_line_boundary(position).0;
2639 let next_line_start = buffer.clip_point(
2640 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2641 Bias::Left,
2642 );
2643 start = buffer.anchor_before(line_start);
2644 end = buffer.anchor_before(next_line_start);
2645 mode = SelectMode::Line(start..end);
2646 auto_scroll = true;
2647 }
2648 _ => {
2649 start = buffer.anchor_before(0);
2650 end = buffer.anchor_before(buffer.len());
2651 mode = SelectMode::All;
2652 auto_scroll = false;
2653 }
2654 }
2655
2656 let point_to_delete: Option<usize> = {
2657 let selected_points: Vec<Selection<Point>> =
2658 self.selections.disjoint_in_range(start..end, cx);
2659
2660 if !add || click_count > 1 {
2661 None
2662 } else if selected_points.len() > 0 {
2663 Some(selected_points[0].id)
2664 } else {
2665 let clicked_point_already_selected =
2666 self.selections.disjoint.iter().find(|selection| {
2667 selection.start.to_point(buffer) == start.to_point(buffer)
2668 || selection.end.to_point(buffer) == end.to_point(buffer)
2669 });
2670
2671 if let Some(selection) = clicked_point_already_selected {
2672 Some(selection.id)
2673 } else {
2674 None
2675 }
2676 }
2677 };
2678
2679 let selections_count = self.selections.count();
2680
2681 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2682 if let Some(point_to_delete) = point_to_delete {
2683 s.delete(point_to_delete);
2684
2685 if selections_count == 1 {
2686 s.set_pending_anchor_range(start..end, mode);
2687 }
2688 } else {
2689 if !add {
2690 s.clear_disjoint();
2691 } else if click_count > 1 {
2692 s.delete(newest_selection.id)
2693 }
2694
2695 s.set_pending_anchor_range(start..end, mode);
2696 }
2697 });
2698 }
2699
2700 fn begin_columnar_selection(
2701 &mut self,
2702 position: DisplayPoint,
2703 goal_column: u32,
2704 reset: bool,
2705 cx: &mut ViewContext<Self>,
2706 ) {
2707 if !self.focus_handle.is_focused(cx) {
2708 self.last_focused_descendant = None;
2709 cx.focus(&self.focus_handle);
2710 }
2711
2712 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2713
2714 if reset {
2715 let pointer_position = display_map
2716 .buffer_snapshot
2717 .anchor_before(position.to_point(&display_map));
2718
2719 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2720 s.clear_disjoint();
2721 s.set_pending_anchor_range(
2722 pointer_position..pointer_position,
2723 SelectMode::Character,
2724 );
2725 });
2726 }
2727
2728 let tail = self.selections.newest::<Point>(cx).tail();
2729 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2730
2731 if !reset {
2732 self.select_columns(
2733 tail.to_display_point(&display_map),
2734 position,
2735 goal_column,
2736 &display_map,
2737 cx,
2738 );
2739 }
2740 }
2741
2742 fn update_selection(
2743 &mut self,
2744 position: DisplayPoint,
2745 goal_column: u32,
2746 scroll_delta: gpui::Point<f32>,
2747 cx: &mut ViewContext<Self>,
2748 ) {
2749 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2750
2751 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2752 let tail = tail.to_display_point(&display_map);
2753 self.select_columns(tail, position, goal_column, &display_map, cx);
2754 } else if let Some(mut pending) = self.selections.pending_anchor() {
2755 let buffer = self.buffer.read(cx).snapshot(cx);
2756 let head;
2757 let tail;
2758 let mode = self.selections.pending_mode().unwrap();
2759 match &mode {
2760 SelectMode::Character => {
2761 head = position.to_point(&display_map);
2762 tail = pending.tail().to_point(&buffer);
2763 }
2764 SelectMode::Word(original_range) => {
2765 let original_display_range = original_range.start.to_display_point(&display_map)
2766 ..original_range.end.to_display_point(&display_map);
2767 let original_buffer_range = original_display_range.start.to_point(&display_map)
2768 ..original_display_range.end.to_point(&display_map);
2769 if movement::is_inside_word(&display_map, position)
2770 || original_display_range.contains(&position)
2771 {
2772 let word_range = movement::surrounding_word(&display_map, position);
2773 if word_range.start < original_display_range.start {
2774 head = word_range.start.to_point(&display_map);
2775 } else {
2776 head = word_range.end.to_point(&display_map);
2777 }
2778 } else {
2779 head = position.to_point(&display_map);
2780 }
2781
2782 if head <= original_buffer_range.start {
2783 tail = original_buffer_range.end;
2784 } else {
2785 tail = original_buffer_range.start;
2786 }
2787 }
2788 SelectMode::Line(original_range) => {
2789 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2790
2791 let position = display_map
2792 .clip_point(position, Bias::Left)
2793 .to_point(&display_map);
2794 let line_start = display_map.prev_line_boundary(position).0;
2795 let next_line_start = buffer.clip_point(
2796 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2797 Bias::Left,
2798 );
2799
2800 if line_start < original_range.start {
2801 head = line_start
2802 } else {
2803 head = next_line_start
2804 }
2805
2806 if head <= original_range.start {
2807 tail = original_range.end;
2808 } else {
2809 tail = original_range.start;
2810 }
2811 }
2812 SelectMode::All => {
2813 return;
2814 }
2815 };
2816
2817 if head < tail {
2818 pending.start = buffer.anchor_before(head);
2819 pending.end = buffer.anchor_before(tail);
2820 pending.reversed = true;
2821 } else {
2822 pending.start = buffer.anchor_before(tail);
2823 pending.end = buffer.anchor_before(head);
2824 pending.reversed = false;
2825 }
2826
2827 self.change_selections(None, cx, |s| {
2828 s.set_pending(pending, mode);
2829 });
2830 } else {
2831 log::error!("update_selection dispatched with no pending selection");
2832 return;
2833 }
2834
2835 self.apply_scroll_delta(scroll_delta, cx);
2836 cx.notify();
2837 }
2838
2839 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2840 self.columnar_selection_tail.take();
2841 if self.selections.pending_anchor().is_some() {
2842 let selections = self.selections.all::<usize>(cx);
2843 self.change_selections(None, cx, |s| {
2844 s.select(selections);
2845 s.clear_pending();
2846 });
2847 }
2848 }
2849
2850 fn select_columns(
2851 &mut self,
2852 tail: DisplayPoint,
2853 head: DisplayPoint,
2854 goal_column: u32,
2855 display_map: &DisplaySnapshot,
2856 cx: &mut ViewContext<Self>,
2857 ) {
2858 let start_row = cmp::min(tail.row(), head.row());
2859 let end_row = cmp::max(tail.row(), head.row());
2860 let start_column = cmp::min(tail.column(), goal_column);
2861 let end_column = cmp::max(tail.column(), goal_column);
2862 let reversed = start_column < tail.column();
2863
2864 let selection_ranges = (start_row.0..=end_row.0)
2865 .map(DisplayRow)
2866 .filter_map(|row| {
2867 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2868 let start = display_map
2869 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2870 .to_point(display_map);
2871 let end = display_map
2872 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2873 .to_point(display_map);
2874 if reversed {
2875 Some(end..start)
2876 } else {
2877 Some(start..end)
2878 }
2879 } else {
2880 None
2881 }
2882 })
2883 .collect::<Vec<_>>();
2884
2885 self.change_selections(None, cx, |s| {
2886 s.select_ranges(selection_ranges);
2887 });
2888 cx.notify();
2889 }
2890
2891 pub fn has_pending_nonempty_selection(&self) -> bool {
2892 let pending_nonempty_selection = match self.selections.pending_anchor() {
2893 Some(Selection { start, end, .. }) => start != end,
2894 None => false,
2895 };
2896
2897 pending_nonempty_selection
2898 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2899 }
2900
2901 pub fn has_pending_selection(&self) -> bool {
2902 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2903 }
2904
2905 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2906 if self.clear_clicked_diff_hunks(cx) {
2907 cx.notify();
2908 return;
2909 }
2910 if self.dismiss_menus_and_popups(true, cx) {
2911 return;
2912 }
2913
2914 if self.mode == EditorMode::Full {
2915 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2916 return;
2917 }
2918 }
2919
2920 cx.propagate();
2921 }
2922
2923 pub fn dismiss_menus_and_popups(
2924 &mut self,
2925 should_report_inline_completion_event: bool,
2926 cx: &mut ViewContext<Self>,
2927 ) -> bool {
2928 if self.take_rename(false, cx).is_some() {
2929 return true;
2930 }
2931
2932 if hide_hover(self, cx) {
2933 return true;
2934 }
2935
2936 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2937 return true;
2938 }
2939
2940 if self.hide_context_menu(cx).is_some() {
2941 return true;
2942 }
2943
2944 if self.mouse_context_menu.take().is_some() {
2945 return true;
2946 }
2947
2948 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2949 return true;
2950 }
2951
2952 if self.snippet_stack.pop().is_some() {
2953 return true;
2954 }
2955
2956 if self.mode == EditorMode::Full {
2957 if self.active_diagnostics.is_some() {
2958 self.dismiss_diagnostics(cx);
2959 return true;
2960 }
2961 }
2962
2963 false
2964 }
2965
2966 fn linked_editing_ranges_for(
2967 &self,
2968 selection: Range<text::Anchor>,
2969 cx: &AppContext,
2970 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2971 if self.linked_edit_ranges.is_empty() {
2972 return None;
2973 }
2974 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2975 selection.end.buffer_id.and_then(|end_buffer_id| {
2976 if selection.start.buffer_id != Some(end_buffer_id) {
2977 return None;
2978 }
2979 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2980 let snapshot = buffer.read(cx).snapshot();
2981 self.linked_edit_ranges
2982 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2983 .map(|ranges| (ranges, snapshot, buffer))
2984 })?;
2985 use text::ToOffset as TO;
2986 // find offset from the start of current range to current cursor position
2987 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2988
2989 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2990 let start_difference = start_offset - start_byte_offset;
2991 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2992 let end_difference = end_offset - start_byte_offset;
2993 // Current range has associated linked ranges.
2994 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2995 for range in linked_ranges.iter() {
2996 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2997 let end_offset = start_offset + end_difference;
2998 let start_offset = start_offset + start_difference;
2999 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3000 continue;
3001 }
3002 let start = buffer_snapshot.anchor_after(start_offset);
3003 let end = buffer_snapshot.anchor_after(end_offset);
3004 linked_edits
3005 .entry(buffer.clone())
3006 .or_default()
3007 .push(start..end);
3008 }
3009 Some(linked_edits)
3010 }
3011
3012 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3013 let text: Arc<str> = text.into();
3014
3015 if self.read_only(cx) {
3016 return;
3017 }
3018
3019 let selections = self.selections.all_adjusted(cx);
3020 let mut bracket_inserted = false;
3021 let mut edits = Vec::new();
3022 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3023 let mut new_selections = Vec::with_capacity(selections.len());
3024 let mut new_autoclose_regions = Vec::new();
3025 let snapshot = self.buffer.read(cx).read(cx);
3026
3027 for (selection, autoclose_region) in
3028 self.selections_with_autoclose_regions(selections, &snapshot)
3029 {
3030 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3031 // Determine if the inserted text matches the opening or closing
3032 // bracket of any of this language's bracket pairs.
3033 let mut bracket_pair = None;
3034 let mut is_bracket_pair_start = false;
3035 let mut is_bracket_pair_end = false;
3036 if !text.is_empty() {
3037 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3038 // and they are removing the character that triggered IME popup.
3039 for (pair, enabled) in scope.brackets() {
3040 if !pair.close && !pair.surround {
3041 continue;
3042 }
3043
3044 if enabled && pair.start.ends_with(text.as_ref()) {
3045 bracket_pair = Some(pair.clone());
3046 is_bracket_pair_start = true;
3047 break;
3048 }
3049 if pair.end.as_str() == text.as_ref() {
3050 bracket_pair = Some(pair.clone());
3051 is_bracket_pair_end = true;
3052 break;
3053 }
3054 }
3055 }
3056
3057 if let Some(bracket_pair) = bracket_pair {
3058 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3059 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3060 let auto_surround =
3061 self.use_auto_surround && snapshot_settings.use_auto_surround;
3062 if selection.is_empty() {
3063 if is_bracket_pair_start {
3064 let prefix_len = bracket_pair.start.len() - text.len();
3065
3066 // If the inserted text is a suffix of an opening bracket and the
3067 // selection is preceded by the rest of the opening bracket, then
3068 // insert the closing bracket.
3069 let following_text_allows_autoclose = snapshot
3070 .chars_at(selection.start)
3071 .next()
3072 .map_or(true, |c| scope.should_autoclose_before(c));
3073 let preceding_text_matches_prefix = prefix_len == 0
3074 || (selection.start.column >= (prefix_len as u32)
3075 && snapshot.contains_str_at(
3076 Point::new(
3077 selection.start.row,
3078 selection.start.column - (prefix_len as u32),
3079 ),
3080 &bracket_pair.start[..prefix_len],
3081 ));
3082
3083 if autoclose
3084 && bracket_pair.close
3085 && following_text_allows_autoclose
3086 && preceding_text_matches_prefix
3087 {
3088 let anchor = snapshot.anchor_before(selection.end);
3089 new_selections.push((selection.map(|_| anchor), text.len()));
3090 new_autoclose_regions.push((
3091 anchor,
3092 text.len(),
3093 selection.id,
3094 bracket_pair.clone(),
3095 ));
3096 edits.push((
3097 selection.range(),
3098 format!("{}{}", text, bracket_pair.end).into(),
3099 ));
3100 bracket_inserted = true;
3101 continue;
3102 }
3103 }
3104
3105 if let Some(region) = autoclose_region {
3106 // If the selection is followed by an auto-inserted closing bracket,
3107 // then don't insert that closing bracket again; just move the selection
3108 // past the closing bracket.
3109 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3110 && text.as_ref() == region.pair.end.as_str();
3111 if should_skip {
3112 let anchor = snapshot.anchor_after(selection.end);
3113 new_selections
3114 .push((selection.map(|_| anchor), region.pair.end.len()));
3115 continue;
3116 }
3117 }
3118
3119 let always_treat_brackets_as_autoclosed = snapshot
3120 .settings_at(selection.start, cx)
3121 .always_treat_brackets_as_autoclosed;
3122 if always_treat_brackets_as_autoclosed
3123 && is_bracket_pair_end
3124 && snapshot.contains_str_at(selection.end, text.as_ref())
3125 {
3126 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3127 // and the inserted text is a closing bracket and the selection is followed
3128 // by the closing bracket then move the selection past the closing bracket.
3129 let anchor = snapshot.anchor_after(selection.end);
3130 new_selections.push((selection.map(|_| anchor), text.len()));
3131 continue;
3132 }
3133 }
3134 // If an opening bracket is 1 character long and is typed while
3135 // text is selected, then surround that text with the bracket pair.
3136 else if auto_surround
3137 && bracket_pair.surround
3138 && is_bracket_pair_start
3139 && bracket_pair.start.chars().count() == 1
3140 {
3141 edits.push((selection.start..selection.start, text.clone()));
3142 edits.push((
3143 selection.end..selection.end,
3144 bracket_pair.end.as_str().into(),
3145 ));
3146 bracket_inserted = true;
3147 new_selections.push((
3148 Selection {
3149 id: selection.id,
3150 start: snapshot.anchor_after(selection.start),
3151 end: snapshot.anchor_before(selection.end),
3152 reversed: selection.reversed,
3153 goal: selection.goal,
3154 },
3155 0,
3156 ));
3157 continue;
3158 }
3159 }
3160 }
3161
3162 if self.auto_replace_emoji_shortcode
3163 && selection.is_empty()
3164 && text.as_ref().ends_with(':')
3165 {
3166 if let Some(possible_emoji_short_code) =
3167 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3168 {
3169 if !possible_emoji_short_code.is_empty() {
3170 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3171 let emoji_shortcode_start = Point::new(
3172 selection.start.row,
3173 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3174 );
3175
3176 // Remove shortcode from buffer
3177 edits.push((
3178 emoji_shortcode_start..selection.start,
3179 "".to_string().into(),
3180 ));
3181 new_selections.push((
3182 Selection {
3183 id: selection.id,
3184 start: snapshot.anchor_after(emoji_shortcode_start),
3185 end: snapshot.anchor_before(selection.start),
3186 reversed: selection.reversed,
3187 goal: selection.goal,
3188 },
3189 0,
3190 ));
3191
3192 // Insert emoji
3193 let selection_start_anchor = snapshot.anchor_after(selection.start);
3194 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3195 edits.push((selection.start..selection.end, emoji.to_string().into()));
3196
3197 continue;
3198 }
3199 }
3200 }
3201 }
3202
3203 // If not handling any auto-close operation, then just replace the selected
3204 // text with the given input and move the selection to the end of the
3205 // newly inserted text.
3206 let anchor = snapshot.anchor_after(selection.end);
3207 if !self.linked_edit_ranges.is_empty() {
3208 let start_anchor = snapshot.anchor_before(selection.start);
3209
3210 let is_word_char = text.chars().next().map_or(true, |char| {
3211 let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
3212 let kind = char_kind(&scope, char);
3213
3214 kind == CharKind::Word
3215 });
3216
3217 if is_word_char {
3218 if let Some(ranges) = self
3219 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3220 {
3221 for (buffer, edits) in ranges {
3222 linked_edits
3223 .entry(buffer.clone())
3224 .or_default()
3225 .extend(edits.into_iter().map(|range| (range, text.clone())));
3226 }
3227 }
3228 }
3229 }
3230
3231 new_selections.push((selection.map(|_| anchor), 0));
3232 edits.push((selection.start..selection.end, text.clone()));
3233 }
3234
3235 drop(snapshot);
3236
3237 self.transact(cx, |this, cx| {
3238 this.buffer.update(cx, |buffer, cx| {
3239 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3240 });
3241 for (buffer, edits) in linked_edits {
3242 buffer.update(cx, |buffer, cx| {
3243 let snapshot = buffer.snapshot();
3244 let edits = edits
3245 .into_iter()
3246 .map(|(range, text)| {
3247 use text::ToPoint as TP;
3248 let end_point = TP::to_point(&range.end, &snapshot);
3249 let start_point = TP::to_point(&range.start, &snapshot);
3250 (start_point..end_point, text)
3251 })
3252 .sorted_by_key(|(range, _)| range.start)
3253 .collect::<Vec<_>>();
3254 buffer.edit(edits, None, cx);
3255 })
3256 }
3257 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3258 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3259 let snapshot = this.buffer.read(cx).read(cx);
3260 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3261 .zip(new_selection_deltas)
3262 .map(|(selection, delta)| Selection {
3263 id: selection.id,
3264 start: selection.start + delta,
3265 end: selection.end + delta,
3266 reversed: selection.reversed,
3267 goal: SelectionGoal::None,
3268 })
3269 .collect::<Vec<_>>();
3270
3271 let mut i = 0;
3272 for (position, delta, selection_id, pair) in new_autoclose_regions {
3273 let position = position.to_offset(&snapshot) + delta;
3274 let start = snapshot.anchor_before(position);
3275 let end = snapshot.anchor_after(position);
3276 while let Some(existing_state) = this.autoclose_regions.get(i) {
3277 match existing_state.range.start.cmp(&start, &snapshot) {
3278 Ordering::Less => i += 1,
3279 Ordering::Greater => break,
3280 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3281 Ordering::Less => i += 1,
3282 Ordering::Equal => break,
3283 Ordering::Greater => break,
3284 },
3285 }
3286 }
3287 this.autoclose_regions.insert(
3288 i,
3289 AutocloseRegion {
3290 selection_id,
3291 range: start..end,
3292 pair,
3293 },
3294 );
3295 }
3296
3297 drop(snapshot);
3298 let had_active_inline_completion = this.has_active_inline_completion(cx);
3299 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3300 s.select(new_selections)
3301 });
3302
3303 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3304 if let Some(on_type_format_task) =
3305 this.trigger_on_type_formatting(text.to_string(), cx)
3306 {
3307 on_type_format_task.detach_and_log_err(cx);
3308 }
3309 }
3310
3311 let editor_settings = EditorSettings::get_global(cx);
3312 if bracket_inserted
3313 && (editor_settings.auto_signature_help
3314 || editor_settings.show_signature_help_after_edits)
3315 {
3316 this.show_signature_help(&ShowSignatureHelp, cx);
3317 }
3318
3319 let trigger_in_words = !had_active_inline_completion;
3320 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3321 linked_editing_ranges::refresh_linked_ranges(this, cx);
3322 this.refresh_inline_completion(true, false, cx);
3323 });
3324 }
3325
3326 fn find_possible_emoji_shortcode_at_position(
3327 snapshot: &MultiBufferSnapshot,
3328 position: Point,
3329 ) -> Option<String> {
3330 let mut chars = Vec::new();
3331 let mut found_colon = false;
3332 for char in snapshot.reversed_chars_at(position).take(100) {
3333 // Found a possible emoji shortcode in the middle of the buffer
3334 if found_colon {
3335 if char.is_whitespace() {
3336 chars.reverse();
3337 return Some(chars.iter().collect());
3338 }
3339 // If the previous character is not a whitespace, we are in the middle of a word
3340 // and we only want to complete the shortcode if the word is made up of other emojis
3341 let mut containing_word = String::new();
3342 for ch in snapshot
3343 .reversed_chars_at(position)
3344 .skip(chars.len() + 1)
3345 .take(100)
3346 {
3347 if ch.is_whitespace() {
3348 break;
3349 }
3350 containing_word.push(ch);
3351 }
3352 let containing_word = containing_word.chars().rev().collect::<String>();
3353 if util::word_consists_of_emojis(containing_word.as_str()) {
3354 chars.reverse();
3355 return Some(chars.iter().collect());
3356 }
3357 }
3358
3359 if char.is_whitespace() || !char.is_ascii() {
3360 return None;
3361 }
3362 if char == ':' {
3363 found_colon = true;
3364 } else {
3365 chars.push(char);
3366 }
3367 }
3368 // Found a possible emoji shortcode at the beginning of the buffer
3369 chars.reverse();
3370 Some(chars.iter().collect())
3371 }
3372
3373 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3374 self.transact(cx, |this, cx| {
3375 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3376 let selections = this.selections.all::<usize>(cx);
3377 let multi_buffer = this.buffer.read(cx);
3378 let buffer = multi_buffer.snapshot(cx);
3379 selections
3380 .iter()
3381 .map(|selection| {
3382 let start_point = selection.start.to_point(&buffer);
3383 let mut indent =
3384 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3385 indent.len = cmp::min(indent.len, start_point.column);
3386 let start = selection.start;
3387 let end = selection.end;
3388 let selection_is_empty = start == end;
3389 let language_scope = buffer.language_scope_at(start);
3390 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3391 &language_scope
3392 {
3393 let leading_whitespace_len = buffer
3394 .reversed_chars_at(start)
3395 .take_while(|c| c.is_whitespace() && *c != '\n')
3396 .map(|c| c.len_utf8())
3397 .sum::<usize>();
3398
3399 let trailing_whitespace_len = buffer
3400 .chars_at(end)
3401 .take_while(|c| c.is_whitespace() && *c != '\n')
3402 .map(|c| c.len_utf8())
3403 .sum::<usize>();
3404
3405 let insert_extra_newline =
3406 language.brackets().any(|(pair, enabled)| {
3407 let pair_start = pair.start.trim_end();
3408 let pair_end = pair.end.trim_start();
3409
3410 enabled
3411 && pair.newline
3412 && buffer.contains_str_at(
3413 end + trailing_whitespace_len,
3414 pair_end,
3415 )
3416 && buffer.contains_str_at(
3417 (start - leading_whitespace_len)
3418 .saturating_sub(pair_start.len()),
3419 pair_start,
3420 )
3421 });
3422
3423 // Comment extension on newline is allowed only for cursor selections
3424 let comment_delimiter = maybe!({
3425 if !selection_is_empty {
3426 return None;
3427 }
3428
3429 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3430 return None;
3431 }
3432
3433 let delimiters = language.line_comment_prefixes();
3434 let max_len_of_delimiter =
3435 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3436 let (snapshot, range) =
3437 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3438
3439 let mut index_of_first_non_whitespace = 0;
3440 let comment_candidate = snapshot
3441 .chars_for_range(range)
3442 .skip_while(|c| {
3443 let should_skip = c.is_whitespace();
3444 if should_skip {
3445 index_of_first_non_whitespace += 1;
3446 }
3447 should_skip
3448 })
3449 .take(max_len_of_delimiter)
3450 .collect::<String>();
3451 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3452 comment_candidate.starts_with(comment_prefix.as_ref())
3453 })?;
3454 let cursor_is_placed_after_comment_marker =
3455 index_of_first_non_whitespace + comment_prefix.len()
3456 <= start_point.column as usize;
3457 if cursor_is_placed_after_comment_marker {
3458 Some(comment_prefix.clone())
3459 } else {
3460 None
3461 }
3462 });
3463 (comment_delimiter, insert_extra_newline)
3464 } else {
3465 (None, false)
3466 };
3467
3468 let capacity_for_delimiter = comment_delimiter
3469 .as_deref()
3470 .map(str::len)
3471 .unwrap_or_default();
3472 let mut new_text =
3473 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3474 new_text.push_str("\n");
3475 new_text.extend(indent.chars());
3476 if let Some(delimiter) = &comment_delimiter {
3477 new_text.push_str(&delimiter);
3478 }
3479 if insert_extra_newline {
3480 new_text = new_text.repeat(2);
3481 }
3482
3483 let anchor = buffer.anchor_after(end);
3484 let new_selection = selection.map(|_| anchor);
3485 (
3486 (start..end, new_text),
3487 (insert_extra_newline, new_selection),
3488 )
3489 })
3490 .unzip()
3491 };
3492
3493 this.edit_with_autoindent(edits, cx);
3494 let buffer = this.buffer.read(cx).snapshot(cx);
3495 let new_selections = selection_fixup_info
3496 .into_iter()
3497 .map(|(extra_newline_inserted, new_selection)| {
3498 let mut cursor = new_selection.end.to_point(&buffer);
3499 if extra_newline_inserted {
3500 cursor.row -= 1;
3501 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3502 }
3503 new_selection.map(|_| cursor)
3504 })
3505 .collect();
3506
3507 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3508 this.refresh_inline_completion(true, false, cx);
3509 });
3510 }
3511
3512 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3513 let buffer = self.buffer.read(cx);
3514 let snapshot = buffer.snapshot(cx);
3515
3516 let mut edits = Vec::new();
3517 let mut rows = Vec::new();
3518
3519 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3520 let cursor = selection.head();
3521 let row = cursor.row;
3522
3523 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3524
3525 let newline = "\n".to_string();
3526 edits.push((start_of_line..start_of_line, newline));
3527
3528 rows.push(row + rows_inserted as u32);
3529 }
3530
3531 self.transact(cx, |editor, cx| {
3532 editor.edit(edits, cx);
3533
3534 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3535 let mut index = 0;
3536 s.move_cursors_with(|map, _, _| {
3537 let row = rows[index];
3538 index += 1;
3539
3540 let point = Point::new(row, 0);
3541 let boundary = map.next_line_boundary(point).1;
3542 let clipped = map.clip_point(boundary, Bias::Left);
3543
3544 (clipped, SelectionGoal::None)
3545 });
3546 });
3547
3548 let mut indent_edits = Vec::new();
3549 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3550 for row in rows {
3551 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3552 for (row, indent) in indents {
3553 if indent.len == 0 {
3554 continue;
3555 }
3556
3557 let text = match indent.kind {
3558 IndentKind::Space => " ".repeat(indent.len as usize),
3559 IndentKind::Tab => "\t".repeat(indent.len as usize),
3560 };
3561 let point = Point::new(row.0, 0);
3562 indent_edits.push((point..point, text));
3563 }
3564 }
3565 editor.edit(indent_edits, cx);
3566 });
3567 }
3568
3569 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3570 let buffer = self.buffer.read(cx);
3571 let snapshot = buffer.snapshot(cx);
3572
3573 let mut edits = Vec::new();
3574 let mut rows = Vec::new();
3575 let mut rows_inserted = 0;
3576
3577 for selection in self.selections.all_adjusted(cx) {
3578 let cursor = selection.head();
3579 let row = cursor.row;
3580
3581 let point = Point::new(row + 1, 0);
3582 let start_of_line = snapshot.clip_point(point, Bias::Left);
3583
3584 let newline = "\n".to_string();
3585 edits.push((start_of_line..start_of_line, newline));
3586
3587 rows_inserted += 1;
3588 rows.push(row + rows_inserted);
3589 }
3590
3591 self.transact(cx, |editor, cx| {
3592 editor.edit(edits, cx);
3593
3594 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3595 let mut index = 0;
3596 s.move_cursors_with(|map, _, _| {
3597 let row = rows[index];
3598 index += 1;
3599
3600 let point = Point::new(row, 0);
3601 let boundary = map.next_line_boundary(point).1;
3602 let clipped = map.clip_point(boundary, Bias::Left);
3603
3604 (clipped, SelectionGoal::None)
3605 });
3606 });
3607
3608 let mut indent_edits = Vec::new();
3609 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3610 for row in rows {
3611 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3612 for (row, indent) in indents {
3613 if indent.len == 0 {
3614 continue;
3615 }
3616
3617 let text = match indent.kind {
3618 IndentKind::Space => " ".repeat(indent.len as usize),
3619 IndentKind::Tab => "\t".repeat(indent.len as usize),
3620 };
3621 let point = Point::new(row.0, 0);
3622 indent_edits.push((point..point, text));
3623 }
3624 }
3625 editor.edit(indent_edits, cx);
3626 });
3627 }
3628
3629 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3630 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3631 original_indent_columns: Vec::new(),
3632 });
3633 self.insert_with_autoindent_mode(text, autoindent, cx);
3634 }
3635
3636 fn insert_with_autoindent_mode(
3637 &mut self,
3638 text: &str,
3639 autoindent_mode: Option<AutoindentMode>,
3640 cx: &mut ViewContext<Self>,
3641 ) {
3642 if self.read_only(cx) {
3643 return;
3644 }
3645
3646 let text: Arc<str> = text.into();
3647 self.transact(cx, |this, cx| {
3648 let old_selections = this.selections.all_adjusted(cx);
3649 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3650 let anchors = {
3651 let snapshot = buffer.read(cx);
3652 old_selections
3653 .iter()
3654 .map(|s| {
3655 let anchor = snapshot.anchor_after(s.head());
3656 s.map(|_| anchor)
3657 })
3658 .collect::<Vec<_>>()
3659 };
3660 buffer.edit(
3661 old_selections
3662 .iter()
3663 .map(|s| (s.start..s.end, text.clone())),
3664 autoindent_mode,
3665 cx,
3666 );
3667 anchors
3668 });
3669
3670 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3671 s.select_anchors(selection_anchors);
3672 })
3673 });
3674 }
3675
3676 fn trigger_completion_on_input(
3677 &mut self,
3678 text: &str,
3679 trigger_in_words: bool,
3680 cx: &mut ViewContext<Self>,
3681 ) {
3682 if self.is_completion_trigger(text, trigger_in_words, cx) {
3683 self.show_completions(
3684 &ShowCompletions {
3685 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3686 },
3687 cx,
3688 );
3689 } else {
3690 self.hide_context_menu(cx);
3691 }
3692 }
3693
3694 fn is_completion_trigger(
3695 &self,
3696 text: &str,
3697 trigger_in_words: bool,
3698 cx: &mut ViewContext<Self>,
3699 ) -> bool {
3700 let position = self.selections.newest_anchor().head();
3701 let multibuffer = self.buffer.read(cx);
3702 let Some(buffer) = position
3703 .buffer_id
3704 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3705 else {
3706 return false;
3707 };
3708
3709 if let Some(completion_provider) = &self.completion_provider {
3710 completion_provider.is_completion_trigger(
3711 &buffer,
3712 position.text_anchor,
3713 text,
3714 trigger_in_words,
3715 cx,
3716 )
3717 } else {
3718 false
3719 }
3720 }
3721
3722 /// If any empty selections is touching the start of its innermost containing autoclose
3723 /// region, expand it to select the brackets.
3724 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3725 let selections = self.selections.all::<usize>(cx);
3726 let buffer = self.buffer.read(cx).read(cx);
3727 let new_selections = self
3728 .selections_with_autoclose_regions(selections, &buffer)
3729 .map(|(mut selection, region)| {
3730 if !selection.is_empty() {
3731 return selection;
3732 }
3733
3734 if let Some(region) = region {
3735 let mut range = region.range.to_offset(&buffer);
3736 if selection.start == range.start && range.start >= region.pair.start.len() {
3737 range.start -= region.pair.start.len();
3738 if buffer.contains_str_at(range.start, ®ion.pair.start)
3739 && buffer.contains_str_at(range.end, ®ion.pair.end)
3740 {
3741 range.end += region.pair.end.len();
3742 selection.start = range.start;
3743 selection.end = range.end;
3744
3745 return selection;
3746 }
3747 }
3748 }
3749
3750 let always_treat_brackets_as_autoclosed = buffer
3751 .settings_at(selection.start, cx)
3752 .always_treat_brackets_as_autoclosed;
3753
3754 if !always_treat_brackets_as_autoclosed {
3755 return selection;
3756 }
3757
3758 if let Some(scope) = buffer.language_scope_at(selection.start) {
3759 for (pair, enabled) in scope.brackets() {
3760 if !enabled || !pair.close {
3761 continue;
3762 }
3763
3764 if buffer.contains_str_at(selection.start, &pair.end) {
3765 let pair_start_len = pair.start.len();
3766 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3767 {
3768 selection.start -= pair_start_len;
3769 selection.end += pair.end.len();
3770
3771 return selection;
3772 }
3773 }
3774 }
3775 }
3776
3777 selection
3778 })
3779 .collect();
3780
3781 drop(buffer);
3782 self.change_selections(None, cx, |selections| selections.select(new_selections));
3783 }
3784
3785 /// Iterate the given selections, and for each one, find the smallest surrounding
3786 /// autoclose region. This uses the ordering of the selections and the autoclose
3787 /// regions to avoid repeated comparisons.
3788 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3789 &'a self,
3790 selections: impl IntoIterator<Item = Selection<D>>,
3791 buffer: &'a MultiBufferSnapshot,
3792 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3793 let mut i = 0;
3794 let mut regions = self.autoclose_regions.as_slice();
3795 selections.into_iter().map(move |selection| {
3796 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3797
3798 let mut enclosing = None;
3799 while let Some(pair_state) = regions.get(i) {
3800 if pair_state.range.end.to_offset(buffer) < range.start {
3801 regions = ®ions[i + 1..];
3802 i = 0;
3803 } else if pair_state.range.start.to_offset(buffer) > range.end {
3804 break;
3805 } else {
3806 if pair_state.selection_id == selection.id {
3807 enclosing = Some(pair_state);
3808 }
3809 i += 1;
3810 }
3811 }
3812
3813 (selection.clone(), enclosing)
3814 })
3815 }
3816
3817 /// Remove any autoclose regions that no longer contain their selection.
3818 fn invalidate_autoclose_regions(
3819 &mut self,
3820 mut selections: &[Selection<Anchor>],
3821 buffer: &MultiBufferSnapshot,
3822 ) {
3823 self.autoclose_regions.retain(|state| {
3824 let mut i = 0;
3825 while let Some(selection) = selections.get(i) {
3826 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3827 selections = &selections[1..];
3828 continue;
3829 }
3830 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3831 break;
3832 }
3833 if selection.id == state.selection_id {
3834 return true;
3835 } else {
3836 i += 1;
3837 }
3838 }
3839 false
3840 });
3841 }
3842
3843 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3844 let offset = position.to_offset(buffer);
3845 let (word_range, kind) = buffer.surrounding_word(offset);
3846 if offset > word_range.start && kind == Some(CharKind::Word) {
3847 Some(
3848 buffer
3849 .text_for_range(word_range.start..offset)
3850 .collect::<String>(),
3851 )
3852 } else {
3853 None
3854 }
3855 }
3856
3857 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3858 self.refresh_inlay_hints(
3859 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3860 cx,
3861 );
3862 }
3863
3864 pub fn inlay_hints_enabled(&self) -> bool {
3865 self.inlay_hint_cache.enabled
3866 }
3867
3868 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3869 if self.project.is_none() || self.mode != EditorMode::Full {
3870 return;
3871 }
3872
3873 let reason_description = reason.description();
3874 let ignore_debounce = matches!(
3875 reason,
3876 InlayHintRefreshReason::SettingsChange(_)
3877 | InlayHintRefreshReason::Toggle(_)
3878 | InlayHintRefreshReason::ExcerptsRemoved(_)
3879 );
3880 let (invalidate_cache, required_languages) = match reason {
3881 InlayHintRefreshReason::Toggle(enabled) => {
3882 self.inlay_hint_cache.enabled = enabled;
3883 if enabled {
3884 (InvalidationStrategy::RefreshRequested, None)
3885 } else {
3886 self.inlay_hint_cache.clear();
3887 self.splice_inlays(
3888 self.visible_inlay_hints(cx)
3889 .iter()
3890 .map(|inlay| inlay.id)
3891 .collect(),
3892 Vec::new(),
3893 cx,
3894 );
3895 return;
3896 }
3897 }
3898 InlayHintRefreshReason::SettingsChange(new_settings) => {
3899 match self.inlay_hint_cache.update_settings(
3900 &self.buffer,
3901 new_settings,
3902 self.visible_inlay_hints(cx),
3903 cx,
3904 ) {
3905 ControlFlow::Break(Some(InlaySplice {
3906 to_remove,
3907 to_insert,
3908 })) => {
3909 self.splice_inlays(to_remove, to_insert, cx);
3910 return;
3911 }
3912 ControlFlow::Break(None) => return,
3913 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3914 }
3915 }
3916 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3917 if let Some(InlaySplice {
3918 to_remove,
3919 to_insert,
3920 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3921 {
3922 self.splice_inlays(to_remove, to_insert, cx);
3923 }
3924 return;
3925 }
3926 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3927 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3928 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3929 }
3930 InlayHintRefreshReason::RefreshRequested => {
3931 (InvalidationStrategy::RefreshRequested, None)
3932 }
3933 };
3934
3935 if let Some(InlaySplice {
3936 to_remove,
3937 to_insert,
3938 }) = self.inlay_hint_cache.spawn_hint_refresh(
3939 reason_description,
3940 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3941 invalidate_cache,
3942 ignore_debounce,
3943 cx,
3944 ) {
3945 self.splice_inlays(to_remove, to_insert, cx);
3946 }
3947 }
3948
3949 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3950 self.display_map
3951 .read(cx)
3952 .current_inlays()
3953 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3954 .cloned()
3955 .collect()
3956 }
3957
3958 pub fn excerpts_for_inlay_hints_query(
3959 &self,
3960 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3961 cx: &mut ViewContext<Editor>,
3962 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3963 let Some(project) = self.project.as_ref() else {
3964 return HashMap::default();
3965 };
3966 let project = project.read(cx);
3967 let multi_buffer = self.buffer().read(cx);
3968 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3969 let multi_buffer_visible_start = self
3970 .scroll_manager
3971 .anchor()
3972 .anchor
3973 .to_point(&multi_buffer_snapshot);
3974 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3975 multi_buffer_visible_start
3976 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3977 Bias::Left,
3978 );
3979 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3980 multi_buffer
3981 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3982 .into_iter()
3983 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3984 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3985 let buffer = buffer_handle.read(cx);
3986 let buffer_file = project::File::from_dyn(buffer.file())?;
3987 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3988 let worktree_entry = buffer_worktree
3989 .read(cx)
3990 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3991 if worktree_entry.is_ignored {
3992 return None;
3993 }
3994
3995 let language = buffer.language()?;
3996 if let Some(restrict_to_languages) = restrict_to_languages {
3997 if !restrict_to_languages.contains(language) {
3998 return None;
3999 }
4000 }
4001 Some((
4002 excerpt_id,
4003 (
4004 buffer_handle,
4005 buffer.version().clone(),
4006 excerpt_visible_range,
4007 ),
4008 ))
4009 })
4010 .collect()
4011 }
4012
4013 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4014 TextLayoutDetails {
4015 text_system: cx.text_system().clone(),
4016 editor_style: self.style.clone().unwrap(),
4017 rem_size: cx.rem_size(),
4018 scroll_anchor: self.scroll_manager.anchor(),
4019 visible_rows: self.visible_line_count(),
4020 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4021 }
4022 }
4023
4024 fn splice_inlays(
4025 &self,
4026 to_remove: Vec<InlayId>,
4027 to_insert: Vec<Inlay>,
4028 cx: &mut ViewContext<Self>,
4029 ) {
4030 self.display_map.update(cx, |display_map, cx| {
4031 display_map.splice_inlays(to_remove, to_insert, cx);
4032 });
4033 cx.notify();
4034 }
4035
4036 fn trigger_on_type_formatting(
4037 &self,
4038 input: String,
4039 cx: &mut ViewContext<Self>,
4040 ) -> Option<Task<Result<()>>> {
4041 if input.len() != 1 {
4042 return None;
4043 }
4044
4045 let project = self.project.as_ref()?;
4046 let position = self.selections.newest_anchor().head();
4047 let (buffer, buffer_position) = self
4048 .buffer
4049 .read(cx)
4050 .text_anchor_for_position(position, cx)?;
4051
4052 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4053 // hence we do LSP request & edit on host side only — add formats to host's history.
4054 let push_to_lsp_host_history = true;
4055 // If this is not the host, append its history with new edits.
4056 let push_to_client_history = project.read(cx).is_remote();
4057
4058 let on_type_formatting = project.update(cx, |project, cx| {
4059 project.on_type_format(
4060 buffer.clone(),
4061 buffer_position,
4062 input,
4063 push_to_lsp_host_history,
4064 cx,
4065 )
4066 });
4067 Some(cx.spawn(|editor, mut cx| async move {
4068 if let Some(transaction) = on_type_formatting.await? {
4069 if push_to_client_history {
4070 buffer
4071 .update(&mut cx, |buffer, _| {
4072 buffer.push_transaction(transaction, Instant::now());
4073 })
4074 .ok();
4075 }
4076 editor.update(&mut cx, |editor, cx| {
4077 editor.refresh_document_highlights(cx);
4078 })?;
4079 }
4080 Ok(())
4081 }))
4082 }
4083
4084 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4085 if self.pending_rename.is_some() {
4086 return;
4087 }
4088
4089 let Some(provider) = self.completion_provider.as_ref() else {
4090 return;
4091 };
4092
4093 let position = self.selections.newest_anchor().head();
4094 let (buffer, buffer_position) =
4095 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4096 output
4097 } else {
4098 return;
4099 };
4100
4101 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4102 let is_followup_invoke = {
4103 let context_menu_state = self.context_menu.read();
4104 matches!(
4105 context_menu_state.deref(),
4106 Some(ContextMenu::Completions(_))
4107 )
4108 };
4109 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4110 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4111 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
4112 CompletionTriggerKind::TRIGGER_CHARACTER
4113 }
4114
4115 _ => CompletionTriggerKind::INVOKED,
4116 };
4117 let completion_context = CompletionContext {
4118 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4119 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4120 Some(String::from(trigger))
4121 } else {
4122 None
4123 }
4124 }),
4125 trigger_kind,
4126 };
4127 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4128 let sort_completions = provider.sort_completions();
4129
4130 let id = post_inc(&mut self.next_completion_id);
4131 let task = cx.spawn(|this, mut cx| {
4132 async move {
4133 this.update(&mut cx, |this, _| {
4134 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4135 })?;
4136 let completions = completions.await.log_err();
4137 let menu = if let Some(completions) = completions {
4138 let mut menu = CompletionsMenu {
4139 id,
4140 sort_completions,
4141 initial_position: position,
4142 match_candidates: completions
4143 .iter()
4144 .enumerate()
4145 .map(|(id, completion)| {
4146 StringMatchCandidate::new(
4147 id,
4148 completion.label.text[completion.label.filter_range.clone()]
4149 .into(),
4150 )
4151 })
4152 .collect(),
4153 buffer: buffer.clone(),
4154 completions: Arc::new(RwLock::new(completions.into())),
4155 matches: Vec::new().into(),
4156 selected_item: 0,
4157 scroll_handle: UniformListScrollHandle::new(),
4158 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4159 DebouncedDelay::new(),
4160 )),
4161 };
4162 menu.filter(query.as_deref(), cx.background_executor().clone())
4163 .await;
4164
4165 if menu.matches.is_empty() {
4166 None
4167 } else {
4168 this.update(&mut cx, |editor, cx| {
4169 let completions = menu.completions.clone();
4170 let matches = menu.matches.clone();
4171
4172 let delay_ms = EditorSettings::get_global(cx)
4173 .completion_documentation_secondary_query_debounce;
4174 let delay = Duration::from_millis(delay_ms);
4175 editor
4176 .completion_documentation_pre_resolve_debounce
4177 .fire_new(delay, cx, |editor, cx| {
4178 CompletionsMenu::pre_resolve_completion_documentation(
4179 buffer,
4180 completions,
4181 matches,
4182 editor,
4183 cx,
4184 )
4185 });
4186 })
4187 .ok();
4188 Some(menu)
4189 }
4190 } else {
4191 None
4192 };
4193
4194 this.update(&mut cx, |this, cx| {
4195 let mut context_menu = this.context_menu.write();
4196 match context_menu.as_ref() {
4197 None => {}
4198
4199 Some(ContextMenu::Completions(prev_menu)) => {
4200 if prev_menu.id > id {
4201 return;
4202 }
4203 }
4204
4205 _ => return,
4206 }
4207
4208 if this.focus_handle.is_focused(cx) && menu.is_some() {
4209 let menu = menu.unwrap();
4210 *context_menu = Some(ContextMenu::Completions(menu));
4211 drop(context_menu);
4212 this.discard_inline_completion(false, cx);
4213 cx.notify();
4214 } else if this.completion_tasks.len() <= 1 {
4215 // If there are no more completion tasks and the last menu was
4216 // empty, we should hide it. If it was already hidden, we should
4217 // also show the copilot completion when available.
4218 drop(context_menu);
4219 if this.hide_context_menu(cx).is_none() {
4220 this.update_visible_inline_completion(cx);
4221 }
4222 }
4223 })?;
4224
4225 Ok::<_, anyhow::Error>(())
4226 }
4227 .log_err()
4228 });
4229
4230 self.completion_tasks.push((id, task));
4231 }
4232
4233 pub fn confirm_completion(
4234 &mut self,
4235 action: &ConfirmCompletion,
4236 cx: &mut ViewContext<Self>,
4237 ) -> Option<Task<Result<()>>> {
4238 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4239 }
4240
4241 pub fn compose_completion(
4242 &mut self,
4243 action: &ComposeCompletion,
4244 cx: &mut ViewContext<Self>,
4245 ) -> Option<Task<Result<()>>> {
4246 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4247 }
4248
4249 fn do_completion(
4250 &mut self,
4251 item_ix: Option<usize>,
4252 intent: CompletionIntent,
4253 cx: &mut ViewContext<Editor>,
4254 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4255 use language::ToOffset as _;
4256
4257 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4258 menu
4259 } else {
4260 return None;
4261 };
4262
4263 let mat = completions_menu
4264 .matches
4265 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4266 let buffer_handle = completions_menu.buffer;
4267 let completions = completions_menu.completions.read();
4268 let completion = completions.get(mat.candidate_id)?;
4269 cx.stop_propagation();
4270
4271 let snippet;
4272 let text;
4273
4274 if completion.is_snippet() {
4275 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4276 text = snippet.as_ref().unwrap().text.clone();
4277 } else {
4278 snippet = None;
4279 text = completion.new_text.clone();
4280 };
4281 let selections = self.selections.all::<usize>(cx);
4282 let buffer = buffer_handle.read(cx);
4283 let old_range = completion.old_range.to_offset(buffer);
4284 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4285
4286 let newest_selection = self.selections.newest_anchor();
4287 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4288 return None;
4289 }
4290
4291 let lookbehind = newest_selection
4292 .start
4293 .text_anchor
4294 .to_offset(buffer)
4295 .saturating_sub(old_range.start);
4296 let lookahead = old_range
4297 .end
4298 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4299 let mut common_prefix_len = old_text
4300 .bytes()
4301 .zip(text.bytes())
4302 .take_while(|(a, b)| a == b)
4303 .count();
4304
4305 let snapshot = self.buffer.read(cx).snapshot(cx);
4306 let mut range_to_replace: Option<Range<isize>> = None;
4307 let mut ranges = Vec::new();
4308 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4309 for selection in &selections {
4310 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4311 let start = selection.start.saturating_sub(lookbehind);
4312 let end = selection.end + lookahead;
4313 if selection.id == newest_selection.id {
4314 range_to_replace = Some(
4315 ((start + common_prefix_len) as isize - selection.start as isize)
4316 ..(end as isize - selection.start as isize),
4317 );
4318 }
4319 ranges.push(start + common_prefix_len..end);
4320 } else {
4321 common_prefix_len = 0;
4322 ranges.clear();
4323 ranges.extend(selections.iter().map(|s| {
4324 if s.id == newest_selection.id {
4325 range_to_replace = Some(
4326 old_range.start.to_offset_utf16(&snapshot).0 as isize
4327 - selection.start as isize
4328 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4329 - selection.start as isize,
4330 );
4331 old_range.clone()
4332 } else {
4333 s.start..s.end
4334 }
4335 }));
4336 break;
4337 }
4338 if !self.linked_edit_ranges.is_empty() {
4339 let start_anchor = snapshot.anchor_before(selection.head());
4340 let end_anchor = snapshot.anchor_after(selection.tail());
4341 if let Some(ranges) = self
4342 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4343 {
4344 for (buffer, edits) in ranges {
4345 linked_edits.entry(buffer.clone()).or_default().extend(
4346 edits
4347 .into_iter()
4348 .map(|range| (range, text[common_prefix_len..].to_owned())),
4349 );
4350 }
4351 }
4352 }
4353 }
4354 let text = &text[common_prefix_len..];
4355
4356 cx.emit(EditorEvent::InputHandled {
4357 utf16_range_to_replace: range_to_replace,
4358 text: text.into(),
4359 });
4360
4361 self.transact(cx, |this, cx| {
4362 if let Some(mut snippet) = snippet {
4363 snippet.text = text.to_string();
4364 for tabstop in snippet.tabstops.iter_mut().flatten() {
4365 tabstop.start -= common_prefix_len as isize;
4366 tabstop.end -= common_prefix_len as isize;
4367 }
4368
4369 this.insert_snippet(&ranges, snippet, cx).log_err();
4370 } else {
4371 this.buffer.update(cx, |buffer, cx| {
4372 buffer.edit(
4373 ranges.iter().map(|range| (range.clone(), text)),
4374 this.autoindent_mode.clone(),
4375 cx,
4376 );
4377 });
4378 }
4379 for (buffer, edits) in linked_edits {
4380 buffer.update(cx, |buffer, cx| {
4381 let snapshot = buffer.snapshot();
4382 let edits = edits
4383 .into_iter()
4384 .map(|(range, text)| {
4385 use text::ToPoint as TP;
4386 let end_point = TP::to_point(&range.end, &snapshot);
4387 let start_point = TP::to_point(&range.start, &snapshot);
4388 (start_point..end_point, text)
4389 })
4390 .sorted_by_key(|(range, _)| range.start)
4391 .collect::<Vec<_>>();
4392 buffer.edit(edits, None, cx);
4393 })
4394 }
4395
4396 this.refresh_inline_completion(true, false, cx);
4397 });
4398
4399 let show_new_completions_on_confirm = completion
4400 .confirm
4401 .as_ref()
4402 .map_or(false, |confirm| confirm(intent, cx));
4403 if show_new_completions_on_confirm {
4404 self.show_completions(&ShowCompletions { trigger: None }, cx);
4405 }
4406
4407 let provider = self.completion_provider.as_ref()?;
4408 let apply_edits = provider.apply_additional_edits_for_completion(
4409 buffer_handle,
4410 completion.clone(),
4411 true,
4412 cx,
4413 );
4414
4415 let editor_settings = EditorSettings::get_global(cx);
4416 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4417 // After the code completion is finished, users often want to know what signatures are needed.
4418 // so we should automatically call signature_help
4419 self.show_signature_help(&ShowSignatureHelp, cx);
4420 }
4421
4422 Some(cx.foreground_executor().spawn(async move {
4423 apply_edits.await?;
4424 Ok(())
4425 }))
4426 }
4427
4428 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4429 let mut context_menu = self.context_menu.write();
4430 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4431 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4432 // Toggle if we're selecting the same one
4433 *context_menu = None;
4434 cx.notify();
4435 return;
4436 } else {
4437 // Otherwise, clear it and start a new one
4438 *context_menu = None;
4439 cx.notify();
4440 }
4441 }
4442 drop(context_menu);
4443 let snapshot = self.snapshot(cx);
4444 let deployed_from_indicator = action.deployed_from_indicator;
4445 let mut task = self.code_actions_task.take();
4446 let action = action.clone();
4447 cx.spawn(|editor, mut cx| async move {
4448 while let Some(prev_task) = task {
4449 prev_task.await;
4450 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4451 }
4452
4453 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4454 if editor.focus_handle.is_focused(cx) {
4455 let multibuffer_point = action
4456 .deployed_from_indicator
4457 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4458 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4459 let (buffer, buffer_row) = snapshot
4460 .buffer_snapshot
4461 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4462 .and_then(|(buffer_snapshot, range)| {
4463 editor
4464 .buffer
4465 .read(cx)
4466 .buffer(buffer_snapshot.remote_id())
4467 .map(|buffer| (buffer, range.start.row))
4468 })?;
4469 let (_, code_actions) = editor
4470 .available_code_actions
4471 .clone()
4472 .and_then(|(location, code_actions)| {
4473 let snapshot = location.buffer.read(cx).snapshot();
4474 let point_range = location.range.to_point(&snapshot);
4475 let point_range = point_range.start.row..=point_range.end.row;
4476 if point_range.contains(&buffer_row) {
4477 Some((location, code_actions))
4478 } else {
4479 None
4480 }
4481 })
4482 .unzip();
4483 let buffer_id = buffer.read(cx).remote_id();
4484 let tasks = editor
4485 .tasks
4486 .get(&(buffer_id, buffer_row))
4487 .map(|t| Arc::new(t.to_owned()));
4488 if tasks.is_none() && code_actions.is_none() {
4489 return None;
4490 }
4491
4492 editor.completion_tasks.clear();
4493 editor.discard_inline_completion(false, cx);
4494 let task_context =
4495 tasks
4496 .as_ref()
4497 .zip(editor.project.clone())
4498 .map(|(tasks, project)| {
4499 let position = Point::new(buffer_row, tasks.column);
4500 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4501 let location = Location {
4502 buffer: buffer.clone(),
4503 range: range_start..range_start,
4504 };
4505 // Fill in the environmental variables from the tree-sitter captures
4506 let mut captured_task_variables = TaskVariables::default();
4507 for (capture_name, value) in tasks.extra_variables.clone() {
4508 captured_task_variables.insert(
4509 task::VariableName::Custom(capture_name.into()),
4510 value.clone(),
4511 );
4512 }
4513 project.update(cx, |project, cx| {
4514 project.task_context_for_location(
4515 captured_task_variables,
4516 location,
4517 cx,
4518 )
4519 })
4520 });
4521
4522 Some(cx.spawn(|editor, mut cx| async move {
4523 let task_context = match task_context {
4524 Some(task_context) => task_context.await,
4525 None => None,
4526 };
4527 let resolved_tasks =
4528 tasks.zip(task_context).map(|(tasks, task_context)| {
4529 Arc::new(ResolvedTasks {
4530 templates: tasks
4531 .templates
4532 .iter()
4533 .filter_map(|(kind, template)| {
4534 template
4535 .resolve_task(&kind.to_id_base(), &task_context)
4536 .map(|task| (kind.clone(), task))
4537 })
4538 .collect(),
4539 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4540 multibuffer_point.row,
4541 tasks.column,
4542 )),
4543 })
4544 });
4545 let spawn_straight_away = resolved_tasks
4546 .as_ref()
4547 .map_or(false, |tasks| tasks.templates.len() == 1)
4548 && code_actions
4549 .as_ref()
4550 .map_or(true, |actions| actions.is_empty());
4551 if let Some(task) = editor
4552 .update(&mut cx, |editor, cx| {
4553 *editor.context_menu.write() =
4554 Some(ContextMenu::CodeActions(CodeActionsMenu {
4555 buffer,
4556 actions: CodeActionContents {
4557 tasks: resolved_tasks,
4558 actions: code_actions,
4559 },
4560 selected_item: Default::default(),
4561 scroll_handle: UniformListScrollHandle::default(),
4562 deployed_from_indicator,
4563 }));
4564 if spawn_straight_away {
4565 if let Some(task) = editor.confirm_code_action(
4566 &ConfirmCodeAction { item_ix: Some(0) },
4567 cx,
4568 ) {
4569 cx.notify();
4570 return task;
4571 }
4572 }
4573 cx.notify();
4574 Task::ready(Ok(()))
4575 })
4576 .ok()
4577 {
4578 task.await
4579 } else {
4580 Ok(())
4581 }
4582 }))
4583 } else {
4584 Some(Task::ready(Ok(())))
4585 }
4586 })?;
4587 if let Some(task) = spawned_test_task {
4588 task.await?;
4589 }
4590
4591 Ok::<_, anyhow::Error>(())
4592 })
4593 .detach_and_log_err(cx);
4594 }
4595
4596 pub fn confirm_code_action(
4597 &mut self,
4598 action: &ConfirmCodeAction,
4599 cx: &mut ViewContext<Self>,
4600 ) -> Option<Task<Result<()>>> {
4601 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4602 menu
4603 } else {
4604 return None;
4605 };
4606 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4607 let action = actions_menu.actions.get(action_ix)?;
4608 let title = action.label();
4609 let buffer = actions_menu.buffer;
4610 let workspace = self.workspace()?;
4611
4612 match action {
4613 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4614 workspace.update(cx, |workspace, cx| {
4615 workspace::tasks::schedule_resolved_task(
4616 workspace,
4617 task_source_kind,
4618 resolved_task,
4619 false,
4620 cx,
4621 );
4622
4623 Some(Task::ready(Ok(())))
4624 })
4625 }
4626 CodeActionsItem::CodeAction(action) => {
4627 let apply_code_actions = workspace
4628 .read(cx)
4629 .project()
4630 .clone()
4631 .update(cx, |project, cx| {
4632 project.apply_code_action(buffer, action, true, cx)
4633 });
4634 let workspace = workspace.downgrade();
4635 Some(cx.spawn(|editor, cx| async move {
4636 let project_transaction = apply_code_actions.await?;
4637 Self::open_project_transaction(
4638 &editor,
4639 workspace,
4640 project_transaction,
4641 title,
4642 cx,
4643 )
4644 .await
4645 }))
4646 }
4647 }
4648 }
4649
4650 pub async fn open_project_transaction(
4651 this: &WeakView<Editor>,
4652 workspace: WeakView<Workspace>,
4653 transaction: ProjectTransaction,
4654 title: String,
4655 mut cx: AsyncWindowContext,
4656 ) -> Result<()> {
4657 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4658
4659 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4660 cx.update(|cx| {
4661 entries.sort_unstable_by_key(|(buffer, _)| {
4662 buffer.read(cx).file().map(|f| f.path().clone())
4663 });
4664 })?;
4665
4666 // If the project transaction's edits are all contained within this editor, then
4667 // avoid opening a new editor to display them.
4668
4669 if let Some((buffer, transaction)) = entries.first() {
4670 if entries.len() == 1 {
4671 let excerpt = this.update(&mut cx, |editor, cx| {
4672 editor
4673 .buffer()
4674 .read(cx)
4675 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4676 })?;
4677 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4678 if excerpted_buffer == *buffer {
4679 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4680 let excerpt_range = excerpt_range.to_offset(buffer);
4681 buffer
4682 .edited_ranges_for_transaction::<usize>(transaction)
4683 .all(|range| {
4684 excerpt_range.start <= range.start
4685 && excerpt_range.end >= range.end
4686 })
4687 })?;
4688
4689 if all_edits_within_excerpt {
4690 return Ok(());
4691 }
4692 }
4693 }
4694 }
4695 } else {
4696 return Ok(());
4697 }
4698
4699 let mut ranges_to_highlight = Vec::new();
4700 let excerpt_buffer = cx.new_model(|cx| {
4701 let mut multibuffer =
4702 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4703 for (buffer_handle, transaction) in &entries {
4704 let buffer = buffer_handle.read(cx);
4705 ranges_to_highlight.extend(
4706 multibuffer.push_excerpts_with_context_lines(
4707 buffer_handle.clone(),
4708 buffer
4709 .edited_ranges_for_transaction::<usize>(transaction)
4710 .collect(),
4711 DEFAULT_MULTIBUFFER_CONTEXT,
4712 cx,
4713 ),
4714 );
4715 }
4716 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4717 multibuffer
4718 })?;
4719
4720 workspace.update(&mut cx, |workspace, cx| {
4721 let project = workspace.project().clone();
4722 let editor =
4723 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4724 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4725 editor.update(cx, |editor, cx| {
4726 editor.highlight_background::<Self>(
4727 &ranges_to_highlight,
4728 |theme| theme.editor_highlighted_line_background,
4729 cx,
4730 );
4731 });
4732 })?;
4733
4734 Ok(())
4735 }
4736
4737 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4738 let project = self.project.clone()?;
4739 let buffer = self.buffer.read(cx);
4740 let newest_selection = self.selections.newest_anchor().clone();
4741 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4742 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4743 if start_buffer != end_buffer {
4744 return None;
4745 }
4746
4747 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4748 cx.background_executor()
4749 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4750 .await;
4751
4752 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4753 project.code_actions(&start_buffer, start..end, cx)
4754 }) {
4755 code_actions.await
4756 } else {
4757 Vec::new()
4758 };
4759
4760 this.update(&mut cx, |this, cx| {
4761 this.available_code_actions = if actions.is_empty() {
4762 None
4763 } else {
4764 Some((
4765 Location {
4766 buffer: start_buffer,
4767 range: start..end,
4768 },
4769 actions.into(),
4770 ))
4771 };
4772 cx.notify();
4773 })
4774 .log_err();
4775 }));
4776 None
4777 }
4778
4779 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4780 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4781 self.show_git_blame_inline = false;
4782
4783 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4784 cx.background_executor().timer(delay).await;
4785
4786 this.update(&mut cx, |this, cx| {
4787 this.show_git_blame_inline = true;
4788 cx.notify();
4789 })
4790 .log_err();
4791 }));
4792 }
4793 }
4794
4795 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4796 if self.pending_rename.is_some() {
4797 return None;
4798 }
4799
4800 let project = self.project.clone()?;
4801 let buffer = self.buffer.read(cx);
4802 let newest_selection = self.selections.newest_anchor().clone();
4803 let cursor_position = newest_selection.head();
4804 let (cursor_buffer, cursor_buffer_position) =
4805 buffer.text_anchor_for_position(cursor_position, cx)?;
4806 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4807 if cursor_buffer != tail_buffer {
4808 return None;
4809 }
4810
4811 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4812 cx.background_executor()
4813 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4814 .await;
4815
4816 let highlights = if let Some(highlights) = project
4817 .update(&mut cx, |project, cx| {
4818 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4819 })
4820 .log_err()
4821 {
4822 highlights.await.log_err()
4823 } else {
4824 None
4825 };
4826
4827 if let Some(highlights) = highlights {
4828 this.update(&mut cx, |this, cx| {
4829 if this.pending_rename.is_some() {
4830 return;
4831 }
4832
4833 let buffer_id = cursor_position.buffer_id;
4834 let buffer = this.buffer.read(cx);
4835 if !buffer
4836 .text_anchor_for_position(cursor_position, cx)
4837 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4838 {
4839 return;
4840 }
4841
4842 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4843 let mut write_ranges = Vec::new();
4844 let mut read_ranges = Vec::new();
4845 for highlight in highlights {
4846 for (excerpt_id, excerpt_range) in
4847 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4848 {
4849 let start = highlight
4850 .range
4851 .start
4852 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4853 let end = highlight
4854 .range
4855 .end
4856 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4857 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4858 continue;
4859 }
4860
4861 let range = Anchor {
4862 buffer_id,
4863 excerpt_id,
4864 text_anchor: start,
4865 }..Anchor {
4866 buffer_id,
4867 excerpt_id,
4868 text_anchor: end,
4869 };
4870 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4871 write_ranges.push(range);
4872 } else {
4873 read_ranges.push(range);
4874 }
4875 }
4876 }
4877
4878 this.highlight_background::<DocumentHighlightRead>(
4879 &read_ranges,
4880 |theme| theme.editor_document_highlight_read_background,
4881 cx,
4882 );
4883 this.highlight_background::<DocumentHighlightWrite>(
4884 &write_ranges,
4885 |theme| theme.editor_document_highlight_write_background,
4886 cx,
4887 );
4888 cx.notify();
4889 })
4890 .log_err();
4891 }
4892 }));
4893 None
4894 }
4895
4896 pub fn refresh_inline_completion(
4897 &mut self,
4898 debounce: bool,
4899 user_requested: bool,
4900 cx: &mut ViewContext<Self>,
4901 ) -> Option<()> {
4902 let provider = self.inline_completion_provider()?;
4903 let cursor = self.selections.newest_anchor().head();
4904 let (buffer, cursor_buffer_position) =
4905 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4906 if !user_requested
4907 && (!self.show_inline_completions
4908 || !provider.is_enabled(&buffer, cursor_buffer_position, cx))
4909 {
4910 self.discard_inline_completion(false, cx);
4911 return None;
4912 }
4913
4914 self.update_visible_inline_completion(cx);
4915 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4916 Some(())
4917 }
4918
4919 fn cycle_inline_completion(
4920 &mut self,
4921 direction: Direction,
4922 cx: &mut ViewContext<Self>,
4923 ) -> Option<()> {
4924 let provider = self.inline_completion_provider()?;
4925 let cursor = self.selections.newest_anchor().head();
4926 let (buffer, cursor_buffer_position) =
4927 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4928 if !self.show_inline_completions
4929 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4930 {
4931 return None;
4932 }
4933
4934 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4935 self.update_visible_inline_completion(cx);
4936
4937 Some(())
4938 }
4939
4940 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4941 if !self.has_active_inline_completion(cx) {
4942 self.refresh_inline_completion(false, true, cx);
4943 return;
4944 }
4945
4946 self.update_visible_inline_completion(cx);
4947 }
4948
4949 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4950 self.show_cursor_names(cx);
4951 }
4952
4953 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4954 self.show_cursor_names = true;
4955 cx.notify();
4956 cx.spawn(|this, mut cx| async move {
4957 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4958 this.update(&mut cx, |this, cx| {
4959 this.show_cursor_names = false;
4960 cx.notify()
4961 })
4962 .ok()
4963 })
4964 .detach();
4965 }
4966
4967 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4968 if self.has_active_inline_completion(cx) {
4969 self.cycle_inline_completion(Direction::Next, cx);
4970 } else {
4971 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4972 if is_copilot_disabled {
4973 cx.propagate();
4974 }
4975 }
4976 }
4977
4978 pub fn previous_inline_completion(
4979 &mut self,
4980 _: &PreviousInlineCompletion,
4981 cx: &mut ViewContext<Self>,
4982 ) {
4983 if self.has_active_inline_completion(cx) {
4984 self.cycle_inline_completion(Direction::Prev, cx);
4985 } else {
4986 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
4987 if is_copilot_disabled {
4988 cx.propagate();
4989 }
4990 }
4991 }
4992
4993 pub fn accept_inline_completion(
4994 &mut self,
4995 _: &AcceptInlineCompletion,
4996 cx: &mut ViewContext<Self>,
4997 ) {
4998 let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
4999 return;
5000 };
5001 if let Some(provider) = self.inline_completion_provider() {
5002 provider.accept(cx);
5003 }
5004
5005 cx.emit(EditorEvent::InputHandled {
5006 utf16_range_to_replace: None,
5007 text: completion.text.to_string().into(),
5008 });
5009
5010 if let Some(range) = delete_range {
5011 self.change_selections(None, cx, |s| s.select_ranges([range]))
5012 }
5013 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5014 self.refresh_inline_completion(true, true, cx);
5015 cx.notify();
5016 }
5017
5018 pub fn accept_partial_inline_completion(
5019 &mut self,
5020 _: &AcceptPartialInlineCompletion,
5021 cx: &mut ViewContext<Self>,
5022 ) {
5023 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5024 if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
5025 let mut partial_completion = completion
5026 .text
5027 .chars()
5028 .by_ref()
5029 .take_while(|c| c.is_alphabetic())
5030 .collect::<String>();
5031 if partial_completion.is_empty() {
5032 partial_completion = completion
5033 .text
5034 .chars()
5035 .by_ref()
5036 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5037 .collect::<String>();
5038 }
5039
5040 cx.emit(EditorEvent::InputHandled {
5041 utf16_range_to_replace: None,
5042 text: partial_completion.clone().into(),
5043 });
5044
5045 if let Some(range) = delete_range {
5046 self.change_selections(None, cx, |s| s.select_ranges([range]))
5047 }
5048 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5049
5050 self.refresh_inline_completion(true, true, cx);
5051 cx.notify();
5052 }
5053 }
5054 }
5055
5056 fn discard_inline_completion(
5057 &mut self,
5058 should_report_inline_completion_event: bool,
5059 cx: &mut ViewContext<Self>,
5060 ) -> bool {
5061 if let Some(provider) = self.inline_completion_provider() {
5062 provider.discard(should_report_inline_completion_event, cx);
5063 }
5064
5065 self.take_active_inline_completion(cx).is_some()
5066 }
5067
5068 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5069 if let Some(completion) = self.active_inline_completion.as_ref() {
5070 let buffer = self.buffer.read(cx).read(cx);
5071 completion.0.position.is_valid(&buffer)
5072 } else {
5073 false
5074 }
5075 }
5076
5077 fn take_active_inline_completion(
5078 &mut self,
5079 cx: &mut ViewContext<Self>,
5080 ) -> Option<(Inlay, Option<Range<Anchor>>)> {
5081 let completion = self.active_inline_completion.take()?;
5082 self.display_map.update(cx, |map, cx| {
5083 map.splice_inlays(vec![completion.0.id], Default::default(), cx);
5084 });
5085 let buffer = self.buffer.read(cx).read(cx);
5086
5087 if completion.0.position.is_valid(&buffer) {
5088 Some(completion)
5089 } else {
5090 None
5091 }
5092 }
5093
5094 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5095 let selection = self.selections.newest_anchor();
5096 let cursor = selection.head();
5097
5098 let excerpt_id = cursor.excerpt_id;
5099
5100 if self.context_menu.read().is_none()
5101 && self.completion_tasks.is_empty()
5102 && selection.start == selection.end
5103 {
5104 if let Some(provider) = self.inline_completion_provider() {
5105 if let Some((buffer, cursor_buffer_position)) =
5106 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5107 {
5108 if let Some((text, text_anchor_range)) =
5109 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5110 {
5111 let text = Rope::from(text);
5112 let mut to_remove = Vec::new();
5113 if let Some(completion) = self.active_inline_completion.take() {
5114 to_remove.push(completion.0.id);
5115 }
5116
5117 let completion_inlay =
5118 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
5119
5120 let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
5121 let snapshot = self.buffer.read(cx).snapshot(cx);
5122 Some(
5123 snapshot.anchor_in_excerpt(excerpt_id, range.start)?
5124 ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
5125 )
5126 });
5127 self.active_inline_completion =
5128 Some((completion_inlay.clone(), multibuffer_anchor_range));
5129
5130 self.display_map.update(cx, move |map, cx| {
5131 map.splice_inlays(to_remove, vec![completion_inlay], cx)
5132 });
5133 cx.notify();
5134 return;
5135 }
5136 }
5137 }
5138 }
5139
5140 self.discard_inline_completion(false, cx);
5141 }
5142
5143 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5144 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5145 }
5146
5147 fn render_code_actions_indicator(
5148 &self,
5149 _style: &EditorStyle,
5150 row: DisplayRow,
5151 is_active: bool,
5152 cx: &mut ViewContext<Self>,
5153 ) -> Option<IconButton> {
5154 if self.available_code_actions.is_some() {
5155 Some(
5156 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5157 .shape(ui::IconButtonShape::Square)
5158 .icon_size(IconSize::XSmall)
5159 .icon_color(Color::Muted)
5160 .selected(is_active)
5161 .on_click(cx.listener(move |editor, _e, cx| {
5162 editor.focus(cx);
5163 editor.toggle_code_actions(
5164 &ToggleCodeActions {
5165 deployed_from_indicator: Some(row),
5166 },
5167 cx,
5168 );
5169 })),
5170 )
5171 } else {
5172 None
5173 }
5174 }
5175
5176 fn clear_tasks(&mut self) {
5177 self.tasks.clear()
5178 }
5179
5180 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5181 if let Some(_) = self.tasks.insert(key, value) {
5182 // This case should hopefully be rare, but just in case...
5183 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5184 }
5185 }
5186
5187 fn render_run_indicator(
5188 &self,
5189 _style: &EditorStyle,
5190 is_active: bool,
5191 row: DisplayRow,
5192 cx: &mut ViewContext<Self>,
5193 ) -> IconButton {
5194 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5195 .shape(ui::IconButtonShape::Square)
5196 .icon_size(IconSize::XSmall)
5197 .icon_color(Color::Muted)
5198 .selected(is_active)
5199 .on_click(cx.listener(move |editor, _e, cx| {
5200 editor.focus(cx);
5201 editor.toggle_code_actions(
5202 &ToggleCodeActions {
5203 deployed_from_indicator: Some(row),
5204 },
5205 cx,
5206 );
5207 }))
5208 }
5209
5210 fn close_hunk_diff_button(
5211 &self,
5212 hunk: HoveredHunk,
5213 row: DisplayRow,
5214 cx: &mut ViewContext<Self>,
5215 ) -> IconButton {
5216 IconButton::new(
5217 ("close_hunk_diff_indicator", row.0 as usize),
5218 ui::IconName::Close,
5219 )
5220 .shape(ui::IconButtonShape::Square)
5221 .icon_size(IconSize::XSmall)
5222 .icon_color(Color::Muted)
5223 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5224 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5225 }
5226
5227 pub fn context_menu_visible(&self) -> bool {
5228 self.context_menu
5229 .read()
5230 .as_ref()
5231 .map_or(false, |menu| menu.visible())
5232 }
5233
5234 fn render_context_menu(
5235 &self,
5236 cursor_position: DisplayPoint,
5237 style: &EditorStyle,
5238 max_height: Pixels,
5239 cx: &mut ViewContext<Editor>,
5240 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5241 self.context_menu.read().as_ref().map(|menu| {
5242 menu.render(
5243 cursor_position,
5244 style,
5245 max_height,
5246 self.workspace.as_ref().map(|(w, _)| w.clone()),
5247 cx,
5248 )
5249 })
5250 }
5251
5252 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5253 cx.notify();
5254 self.completion_tasks.clear();
5255 let context_menu = self.context_menu.write().take();
5256 if context_menu.is_some() {
5257 self.update_visible_inline_completion(cx);
5258 }
5259 context_menu
5260 }
5261
5262 pub fn insert_snippet(
5263 &mut self,
5264 insertion_ranges: &[Range<usize>],
5265 snippet: Snippet,
5266 cx: &mut ViewContext<Self>,
5267 ) -> Result<()> {
5268 struct Tabstop<T> {
5269 is_end_tabstop: bool,
5270 ranges: Vec<Range<T>>,
5271 }
5272
5273 let tabstops = self.buffer.update(cx, |buffer, cx| {
5274 let snippet_text: Arc<str> = snippet.text.clone().into();
5275 buffer.edit(
5276 insertion_ranges
5277 .iter()
5278 .cloned()
5279 .map(|range| (range, snippet_text.clone())),
5280 Some(AutoindentMode::EachLine),
5281 cx,
5282 );
5283
5284 let snapshot = &*buffer.read(cx);
5285 let snippet = &snippet;
5286 snippet
5287 .tabstops
5288 .iter()
5289 .map(|tabstop| {
5290 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5291 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5292 });
5293 let mut tabstop_ranges = tabstop
5294 .iter()
5295 .flat_map(|tabstop_range| {
5296 let mut delta = 0_isize;
5297 insertion_ranges.iter().map(move |insertion_range| {
5298 let insertion_start = insertion_range.start as isize + delta;
5299 delta +=
5300 snippet.text.len() as isize - insertion_range.len() as isize;
5301
5302 let start = ((insertion_start + tabstop_range.start) as usize)
5303 .min(snapshot.len());
5304 let end = ((insertion_start + tabstop_range.end) as usize)
5305 .min(snapshot.len());
5306 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5307 })
5308 })
5309 .collect::<Vec<_>>();
5310 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5311
5312 Tabstop {
5313 is_end_tabstop,
5314 ranges: tabstop_ranges,
5315 }
5316 })
5317 .collect::<Vec<_>>()
5318 });
5319 if let Some(tabstop) = tabstops.first() {
5320 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5321 s.select_ranges(tabstop.ranges.iter().cloned());
5322 });
5323
5324 // If we're already at the last tabstop and it's at the end of the snippet,
5325 // we're done, we don't need to keep the state around.
5326 if !tabstop.is_end_tabstop {
5327 let ranges = tabstops
5328 .into_iter()
5329 .map(|tabstop| tabstop.ranges)
5330 .collect::<Vec<_>>();
5331 self.snippet_stack.push(SnippetState {
5332 active_index: 0,
5333 ranges,
5334 });
5335 }
5336
5337 // Check whether the just-entered snippet ends with an auto-closable bracket.
5338 if self.autoclose_regions.is_empty() {
5339 let snapshot = self.buffer.read(cx).snapshot(cx);
5340 for selection in &mut self.selections.all::<Point>(cx) {
5341 let selection_head = selection.head();
5342 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5343 continue;
5344 };
5345
5346 let mut bracket_pair = None;
5347 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5348 let prev_chars = snapshot
5349 .reversed_chars_at(selection_head)
5350 .collect::<String>();
5351 for (pair, enabled) in scope.brackets() {
5352 if enabled
5353 && pair.close
5354 && prev_chars.starts_with(pair.start.as_str())
5355 && next_chars.starts_with(pair.end.as_str())
5356 {
5357 bracket_pair = Some(pair.clone());
5358 break;
5359 }
5360 }
5361 if let Some(pair) = bracket_pair {
5362 let start = snapshot.anchor_after(selection_head);
5363 let end = snapshot.anchor_after(selection_head);
5364 self.autoclose_regions.push(AutocloseRegion {
5365 selection_id: selection.id,
5366 range: start..end,
5367 pair,
5368 });
5369 }
5370 }
5371 }
5372 }
5373 Ok(())
5374 }
5375
5376 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5377 self.move_to_snippet_tabstop(Bias::Right, cx)
5378 }
5379
5380 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5381 self.move_to_snippet_tabstop(Bias::Left, cx)
5382 }
5383
5384 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5385 if let Some(mut snippet) = self.snippet_stack.pop() {
5386 match bias {
5387 Bias::Left => {
5388 if snippet.active_index > 0 {
5389 snippet.active_index -= 1;
5390 } else {
5391 self.snippet_stack.push(snippet);
5392 return false;
5393 }
5394 }
5395 Bias::Right => {
5396 if snippet.active_index + 1 < snippet.ranges.len() {
5397 snippet.active_index += 1;
5398 } else {
5399 self.snippet_stack.push(snippet);
5400 return false;
5401 }
5402 }
5403 }
5404 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5405 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5406 s.select_anchor_ranges(current_ranges.iter().cloned())
5407 });
5408 // If snippet state is not at the last tabstop, push it back on the stack
5409 if snippet.active_index + 1 < snippet.ranges.len() {
5410 self.snippet_stack.push(snippet);
5411 }
5412 return true;
5413 }
5414 }
5415
5416 false
5417 }
5418
5419 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5420 self.transact(cx, |this, cx| {
5421 this.select_all(&SelectAll, cx);
5422 this.insert("", cx);
5423 });
5424 }
5425
5426 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5427 self.transact(cx, |this, cx| {
5428 this.select_autoclose_pair(cx);
5429 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5430 if !this.linked_edit_ranges.is_empty() {
5431 let selections = this.selections.all::<MultiBufferPoint>(cx);
5432 let snapshot = this.buffer.read(cx).snapshot(cx);
5433
5434 for selection in selections.iter() {
5435 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5436 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5437 if selection_start.buffer_id != selection_end.buffer_id {
5438 continue;
5439 }
5440 if let Some(ranges) =
5441 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5442 {
5443 for (buffer, entries) in ranges {
5444 linked_ranges.entry(buffer).or_default().extend(entries);
5445 }
5446 }
5447 }
5448 }
5449
5450 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5451 if !this.selections.line_mode {
5452 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5453 for selection in &mut selections {
5454 if selection.is_empty() {
5455 let old_head = selection.head();
5456 let mut new_head =
5457 movement::left(&display_map, old_head.to_display_point(&display_map))
5458 .to_point(&display_map);
5459 if let Some((buffer, line_buffer_range)) = display_map
5460 .buffer_snapshot
5461 .buffer_line_for_row(MultiBufferRow(old_head.row))
5462 {
5463 let indent_size =
5464 buffer.indent_size_for_line(line_buffer_range.start.row);
5465 let indent_len = match indent_size.kind {
5466 IndentKind::Space => {
5467 buffer.settings_at(line_buffer_range.start, cx).tab_size
5468 }
5469 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5470 };
5471 if old_head.column <= indent_size.len && old_head.column > 0 {
5472 let indent_len = indent_len.get();
5473 new_head = cmp::min(
5474 new_head,
5475 MultiBufferPoint::new(
5476 old_head.row,
5477 ((old_head.column - 1) / indent_len) * indent_len,
5478 ),
5479 );
5480 }
5481 }
5482
5483 selection.set_head(new_head, SelectionGoal::None);
5484 }
5485 }
5486 }
5487
5488 this.signature_help_state.set_backspace_pressed(true);
5489 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5490 this.insert("", cx);
5491 let empty_str: Arc<str> = Arc::from("");
5492 for (buffer, edits) in linked_ranges {
5493 let snapshot = buffer.read(cx).snapshot();
5494 use text::ToPoint as TP;
5495
5496 let edits = edits
5497 .into_iter()
5498 .map(|range| {
5499 let end_point = TP::to_point(&range.end, &snapshot);
5500 let mut start_point = TP::to_point(&range.start, &snapshot);
5501
5502 if end_point == start_point {
5503 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5504 .saturating_sub(1);
5505 start_point = TP::to_point(&offset, &snapshot);
5506 };
5507
5508 (start_point..end_point, empty_str.clone())
5509 })
5510 .sorted_by_key(|(range, _)| range.start)
5511 .collect::<Vec<_>>();
5512 buffer.update(cx, |this, cx| {
5513 this.edit(edits, None, cx);
5514 })
5515 }
5516 this.refresh_inline_completion(true, false, cx);
5517 linked_editing_ranges::refresh_linked_ranges(this, cx);
5518 });
5519 }
5520
5521 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5522 self.transact(cx, |this, cx| {
5523 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5524 let line_mode = s.line_mode;
5525 s.move_with(|map, selection| {
5526 if selection.is_empty() && !line_mode {
5527 let cursor = movement::right(map, selection.head());
5528 selection.end = cursor;
5529 selection.reversed = true;
5530 selection.goal = SelectionGoal::None;
5531 }
5532 })
5533 });
5534 this.insert("", cx);
5535 this.refresh_inline_completion(true, false, cx);
5536 });
5537 }
5538
5539 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5540 if self.move_to_prev_snippet_tabstop(cx) {
5541 return;
5542 }
5543
5544 self.outdent(&Outdent, cx);
5545 }
5546
5547 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5548 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5549 return;
5550 }
5551
5552 let mut selections = self.selections.all_adjusted(cx);
5553 let buffer = self.buffer.read(cx);
5554 let snapshot = buffer.snapshot(cx);
5555 let rows_iter = selections.iter().map(|s| s.head().row);
5556 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5557
5558 let mut edits = Vec::new();
5559 let mut prev_edited_row = 0;
5560 let mut row_delta = 0;
5561 for selection in &mut selections {
5562 if selection.start.row != prev_edited_row {
5563 row_delta = 0;
5564 }
5565 prev_edited_row = selection.end.row;
5566
5567 // If the selection is non-empty, then increase the indentation of the selected lines.
5568 if !selection.is_empty() {
5569 row_delta =
5570 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5571 continue;
5572 }
5573
5574 // If the selection is empty and the cursor is in the leading whitespace before the
5575 // suggested indentation, then auto-indent the line.
5576 let cursor = selection.head();
5577 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5578 if let Some(suggested_indent) =
5579 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5580 {
5581 if cursor.column < suggested_indent.len
5582 && cursor.column <= current_indent.len
5583 && current_indent.len <= suggested_indent.len
5584 {
5585 selection.start = Point::new(cursor.row, suggested_indent.len);
5586 selection.end = selection.start;
5587 if row_delta == 0 {
5588 edits.extend(Buffer::edit_for_indent_size_adjustment(
5589 cursor.row,
5590 current_indent,
5591 suggested_indent,
5592 ));
5593 row_delta = suggested_indent.len - current_indent.len;
5594 }
5595 continue;
5596 }
5597 }
5598
5599 // Otherwise, insert a hard or soft tab.
5600 let settings = buffer.settings_at(cursor, cx);
5601 let tab_size = if settings.hard_tabs {
5602 IndentSize::tab()
5603 } else {
5604 let tab_size = settings.tab_size.get();
5605 let char_column = snapshot
5606 .text_for_range(Point::new(cursor.row, 0)..cursor)
5607 .flat_map(str::chars)
5608 .count()
5609 + row_delta as usize;
5610 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5611 IndentSize::spaces(chars_to_next_tab_stop)
5612 };
5613 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5614 selection.end = selection.start;
5615 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5616 row_delta += tab_size.len;
5617 }
5618
5619 self.transact(cx, |this, cx| {
5620 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5621 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5622 this.refresh_inline_completion(true, false, cx);
5623 });
5624 }
5625
5626 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5627 if self.read_only(cx) {
5628 return;
5629 }
5630 let mut selections = self.selections.all::<Point>(cx);
5631 let mut prev_edited_row = 0;
5632 let mut row_delta = 0;
5633 let mut edits = Vec::new();
5634 let buffer = self.buffer.read(cx);
5635 let snapshot = buffer.snapshot(cx);
5636 for selection in &mut selections {
5637 if selection.start.row != prev_edited_row {
5638 row_delta = 0;
5639 }
5640 prev_edited_row = selection.end.row;
5641
5642 row_delta =
5643 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5644 }
5645
5646 self.transact(cx, |this, cx| {
5647 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5648 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5649 });
5650 }
5651
5652 fn indent_selection(
5653 buffer: &MultiBuffer,
5654 snapshot: &MultiBufferSnapshot,
5655 selection: &mut Selection<Point>,
5656 edits: &mut Vec<(Range<Point>, String)>,
5657 delta_for_start_row: u32,
5658 cx: &AppContext,
5659 ) -> u32 {
5660 let settings = buffer.settings_at(selection.start, cx);
5661 let tab_size = settings.tab_size.get();
5662 let indent_kind = if settings.hard_tabs {
5663 IndentKind::Tab
5664 } else {
5665 IndentKind::Space
5666 };
5667 let mut start_row = selection.start.row;
5668 let mut end_row = selection.end.row + 1;
5669
5670 // If a selection ends at the beginning of a line, don't indent
5671 // that last line.
5672 if selection.end.column == 0 && selection.end.row > selection.start.row {
5673 end_row -= 1;
5674 }
5675
5676 // Avoid re-indenting a row that has already been indented by a
5677 // previous selection, but still update this selection's column
5678 // to reflect that indentation.
5679 if delta_for_start_row > 0 {
5680 start_row += 1;
5681 selection.start.column += delta_for_start_row;
5682 if selection.end.row == selection.start.row {
5683 selection.end.column += delta_for_start_row;
5684 }
5685 }
5686
5687 let mut delta_for_end_row = 0;
5688 let has_multiple_rows = start_row + 1 != end_row;
5689 for row in start_row..end_row {
5690 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5691 let indent_delta = match (current_indent.kind, indent_kind) {
5692 (IndentKind::Space, IndentKind::Space) => {
5693 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5694 IndentSize::spaces(columns_to_next_tab_stop)
5695 }
5696 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5697 (_, IndentKind::Tab) => IndentSize::tab(),
5698 };
5699
5700 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5701 0
5702 } else {
5703 selection.start.column
5704 };
5705 let row_start = Point::new(row, start);
5706 edits.push((
5707 row_start..row_start,
5708 indent_delta.chars().collect::<String>(),
5709 ));
5710
5711 // Update this selection's endpoints to reflect the indentation.
5712 if row == selection.start.row {
5713 selection.start.column += indent_delta.len;
5714 }
5715 if row == selection.end.row {
5716 selection.end.column += indent_delta.len;
5717 delta_for_end_row = indent_delta.len;
5718 }
5719 }
5720
5721 if selection.start.row == selection.end.row {
5722 delta_for_start_row + delta_for_end_row
5723 } else {
5724 delta_for_end_row
5725 }
5726 }
5727
5728 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5729 if self.read_only(cx) {
5730 return;
5731 }
5732 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5733 let selections = self.selections.all::<Point>(cx);
5734 let mut deletion_ranges = Vec::new();
5735 let mut last_outdent = None;
5736 {
5737 let buffer = self.buffer.read(cx);
5738 let snapshot = buffer.snapshot(cx);
5739 for selection in &selections {
5740 let settings = buffer.settings_at(selection.start, cx);
5741 let tab_size = settings.tab_size.get();
5742 let mut rows = selection.spanned_rows(false, &display_map);
5743
5744 // Avoid re-outdenting a row that has already been outdented by a
5745 // previous selection.
5746 if let Some(last_row) = last_outdent {
5747 if last_row == rows.start {
5748 rows.start = rows.start.next_row();
5749 }
5750 }
5751 let has_multiple_rows = rows.len() > 1;
5752 for row in rows.iter_rows() {
5753 let indent_size = snapshot.indent_size_for_line(row);
5754 if indent_size.len > 0 {
5755 let deletion_len = match indent_size.kind {
5756 IndentKind::Space => {
5757 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5758 if columns_to_prev_tab_stop == 0 {
5759 tab_size
5760 } else {
5761 columns_to_prev_tab_stop
5762 }
5763 }
5764 IndentKind::Tab => 1,
5765 };
5766 let start = if has_multiple_rows
5767 || deletion_len > selection.start.column
5768 || indent_size.len < selection.start.column
5769 {
5770 0
5771 } else {
5772 selection.start.column - deletion_len
5773 };
5774 deletion_ranges.push(
5775 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5776 );
5777 last_outdent = Some(row);
5778 }
5779 }
5780 }
5781 }
5782
5783 self.transact(cx, |this, cx| {
5784 this.buffer.update(cx, |buffer, cx| {
5785 let empty_str: Arc<str> = Arc::default();
5786 buffer.edit(
5787 deletion_ranges
5788 .into_iter()
5789 .map(|range| (range, empty_str.clone())),
5790 None,
5791 cx,
5792 );
5793 });
5794 let selections = this.selections.all::<usize>(cx);
5795 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5796 });
5797 }
5798
5799 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5800 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5801 let selections = self.selections.all::<Point>(cx);
5802
5803 let mut new_cursors = Vec::new();
5804 let mut edit_ranges = Vec::new();
5805 let mut selections = selections.iter().peekable();
5806 while let Some(selection) = selections.next() {
5807 let mut rows = selection.spanned_rows(false, &display_map);
5808 let goal_display_column = selection.head().to_display_point(&display_map).column();
5809
5810 // Accumulate contiguous regions of rows that we want to delete.
5811 while let Some(next_selection) = selections.peek() {
5812 let next_rows = next_selection.spanned_rows(false, &display_map);
5813 if next_rows.start <= rows.end {
5814 rows.end = next_rows.end;
5815 selections.next().unwrap();
5816 } else {
5817 break;
5818 }
5819 }
5820
5821 let buffer = &display_map.buffer_snapshot;
5822 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5823 let edit_end;
5824 let cursor_buffer_row;
5825 if buffer.max_point().row >= rows.end.0 {
5826 // If there's a line after the range, delete the \n from the end of the row range
5827 // and position the cursor on the next line.
5828 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5829 cursor_buffer_row = rows.end;
5830 } else {
5831 // If there isn't a line after the range, delete the \n from the line before the
5832 // start of the row range and position the cursor there.
5833 edit_start = edit_start.saturating_sub(1);
5834 edit_end = buffer.len();
5835 cursor_buffer_row = rows.start.previous_row();
5836 }
5837
5838 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5839 *cursor.column_mut() =
5840 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5841
5842 new_cursors.push((
5843 selection.id,
5844 buffer.anchor_after(cursor.to_point(&display_map)),
5845 ));
5846 edit_ranges.push(edit_start..edit_end);
5847 }
5848
5849 self.transact(cx, |this, cx| {
5850 let buffer = this.buffer.update(cx, |buffer, cx| {
5851 let empty_str: Arc<str> = Arc::default();
5852 buffer.edit(
5853 edit_ranges
5854 .into_iter()
5855 .map(|range| (range, empty_str.clone())),
5856 None,
5857 cx,
5858 );
5859 buffer.snapshot(cx)
5860 });
5861 let new_selections = new_cursors
5862 .into_iter()
5863 .map(|(id, cursor)| {
5864 let cursor = cursor.to_point(&buffer);
5865 Selection {
5866 id,
5867 start: cursor,
5868 end: cursor,
5869 reversed: false,
5870 goal: SelectionGoal::None,
5871 }
5872 })
5873 .collect();
5874
5875 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5876 s.select(new_selections);
5877 });
5878 });
5879 }
5880
5881 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5882 if self.read_only(cx) {
5883 return;
5884 }
5885 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5886 for selection in self.selections.all::<Point>(cx) {
5887 let start = MultiBufferRow(selection.start.row);
5888 let end = if selection.start.row == selection.end.row {
5889 MultiBufferRow(selection.start.row + 1)
5890 } else {
5891 MultiBufferRow(selection.end.row)
5892 };
5893
5894 if let Some(last_row_range) = row_ranges.last_mut() {
5895 if start <= last_row_range.end {
5896 last_row_range.end = end;
5897 continue;
5898 }
5899 }
5900 row_ranges.push(start..end);
5901 }
5902
5903 let snapshot = self.buffer.read(cx).snapshot(cx);
5904 let mut cursor_positions = Vec::new();
5905 for row_range in &row_ranges {
5906 let anchor = snapshot.anchor_before(Point::new(
5907 row_range.end.previous_row().0,
5908 snapshot.line_len(row_range.end.previous_row()),
5909 ));
5910 cursor_positions.push(anchor..anchor);
5911 }
5912
5913 self.transact(cx, |this, cx| {
5914 for row_range in row_ranges.into_iter().rev() {
5915 for row in row_range.iter_rows().rev() {
5916 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5917 let next_line_row = row.next_row();
5918 let indent = snapshot.indent_size_for_line(next_line_row);
5919 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5920
5921 let replace = if snapshot.line_len(next_line_row) > indent.len {
5922 " "
5923 } else {
5924 ""
5925 };
5926
5927 this.buffer.update(cx, |buffer, cx| {
5928 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5929 });
5930 }
5931 }
5932
5933 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5934 s.select_anchor_ranges(cursor_positions)
5935 });
5936 });
5937 }
5938
5939 pub fn sort_lines_case_sensitive(
5940 &mut self,
5941 _: &SortLinesCaseSensitive,
5942 cx: &mut ViewContext<Self>,
5943 ) {
5944 self.manipulate_lines(cx, |lines| lines.sort())
5945 }
5946
5947 pub fn sort_lines_case_insensitive(
5948 &mut self,
5949 _: &SortLinesCaseInsensitive,
5950 cx: &mut ViewContext<Self>,
5951 ) {
5952 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5953 }
5954
5955 pub fn unique_lines_case_insensitive(
5956 &mut self,
5957 _: &UniqueLinesCaseInsensitive,
5958 cx: &mut ViewContext<Self>,
5959 ) {
5960 self.manipulate_lines(cx, |lines| {
5961 let mut seen = HashSet::default();
5962 lines.retain(|line| seen.insert(line.to_lowercase()));
5963 })
5964 }
5965
5966 pub fn unique_lines_case_sensitive(
5967 &mut self,
5968 _: &UniqueLinesCaseSensitive,
5969 cx: &mut ViewContext<Self>,
5970 ) {
5971 self.manipulate_lines(cx, |lines| {
5972 let mut seen = HashSet::default();
5973 lines.retain(|line| seen.insert(*line));
5974 })
5975 }
5976
5977 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5978 let mut revert_changes = HashMap::default();
5979 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
5980 for hunk in hunks_for_rows(
5981 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
5982 &multi_buffer_snapshot,
5983 ) {
5984 Self::prepare_revert_change(&mut revert_changes, &self.buffer(), &hunk, cx);
5985 }
5986 if !revert_changes.is_empty() {
5987 self.transact(cx, |editor, cx| {
5988 editor.revert(revert_changes, cx);
5989 });
5990 }
5991 }
5992
5993 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5994 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
5995 if !revert_changes.is_empty() {
5996 self.transact(cx, |editor, cx| {
5997 editor.revert(revert_changes, cx);
5998 });
5999 }
6000 }
6001
6002 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6003 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6004 let project_path = buffer.read(cx).project_path(cx)?;
6005 let project = self.project.as_ref()?.read(cx);
6006 let entry = project.entry_for_path(&project_path, cx)?;
6007 let abs_path = project.absolute_path(&project_path, cx)?;
6008 let parent = if entry.is_symlink {
6009 abs_path.canonicalize().ok()?
6010 } else {
6011 abs_path
6012 }
6013 .parent()?
6014 .to_path_buf();
6015 Some(parent)
6016 }) {
6017 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6018 }
6019 }
6020
6021 fn gather_revert_changes(
6022 &mut self,
6023 selections: &[Selection<Anchor>],
6024 cx: &mut ViewContext<'_, Editor>,
6025 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6026 let mut revert_changes = HashMap::default();
6027 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6028 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6029 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6030 }
6031 revert_changes
6032 }
6033
6034 pub fn prepare_revert_change(
6035 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6036 multi_buffer: &Model<MultiBuffer>,
6037 hunk: &DiffHunk<MultiBufferRow>,
6038 cx: &AppContext,
6039 ) -> Option<()> {
6040 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6041 let buffer = buffer.read(cx);
6042 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6043 let buffer_snapshot = buffer.snapshot();
6044 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6045 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6046 probe
6047 .0
6048 .start
6049 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6050 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6051 }) {
6052 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6053 Some(())
6054 } else {
6055 None
6056 }
6057 }
6058
6059 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6060 self.manipulate_lines(cx, |lines| lines.reverse())
6061 }
6062
6063 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6064 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6065 }
6066
6067 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6068 where
6069 Fn: FnMut(&mut Vec<&str>),
6070 {
6071 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6072 let buffer = self.buffer.read(cx).snapshot(cx);
6073
6074 let mut edits = Vec::new();
6075
6076 let selections = self.selections.all::<Point>(cx);
6077 let mut selections = selections.iter().peekable();
6078 let mut contiguous_row_selections = Vec::new();
6079 let mut new_selections = Vec::new();
6080 let mut added_lines = 0;
6081 let mut removed_lines = 0;
6082
6083 while let Some(selection) = selections.next() {
6084 let (start_row, end_row) = consume_contiguous_rows(
6085 &mut contiguous_row_selections,
6086 selection,
6087 &display_map,
6088 &mut selections,
6089 );
6090
6091 let start_point = Point::new(start_row.0, 0);
6092 let end_point = Point::new(
6093 end_row.previous_row().0,
6094 buffer.line_len(end_row.previous_row()),
6095 );
6096 let text = buffer
6097 .text_for_range(start_point..end_point)
6098 .collect::<String>();
6099
6100 let mut lines = text.split('\n').collect_vec();
6101
6102 let lines_before = lines.len();
6103 callback(&mut lines);
6104 let lines_after = lines.len();
6105
6106 edits.push((start_point..end_point, lines.join("\n")));
6107
6108 // Selections must change based on added and removed line count
6109 let start_row =
6110 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6111 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6112 new_selections.push(Selection {
6113 id: selection.id,
6114 start: start_row,
6115 end: end_row,
6116 goal: SelectionGoal::None,
6117 reversed: selection.reversed,
6118 });
6119
6120 if lines_after > lines_before {
6121 added_lines += lines_after - lines_before;
6122 } else if lines_before > lines_after {
6123 removed_lines += lines_before - lines_after;
6124 }
6125 }
6126
6127 self.transact(cx, |this, cx| {
6128 let buffer = this.buffer.update(cx, |buffer, cx| {
6129 buffer.edit(edits, None, cx);
6130 buffer.snapshot(cx)
6131 });
6132
6133 // Recalculate offsets on newly edited buffer
6134 let new_selections = new_selections
6135 .iter()
6136 .map(|s| {
6137 let start_point = Point::new(s.start.0, 0);
6138 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6139 Selection {
6140 id: s.id,
6141 start: buffer.point_to_offset(start_point),
6142 end: buffer.point_to_offset(end_point),
6143 goal: s.goal,
6144 reversed: s.reversed,
6145 }
6146 })
6147 .collect();
6148
6149 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6150 s.select(new_selections);
6151 });
6152
6153 this.request_autoscroll(Autoscroll::fit(), cx);
6154 });
6155 }
6156
6157 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6158 self.manipulate_text(cx, |text| text.to_uppercase())
6159 }
6160
6161 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6162 self.manipulate_text(cx, |text| text.to_lowercase())
6163 }
6164
6165 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6166 self.manipulate_text(cx, |text| {
6167 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6168 // https://github.com/rutrum/convert-case/issues/16
6169 text.split('\n')
6170 .map(|line| line.to_case(Case::Title))
6171 .join("\n")
6172 })
6173 }
6174
6175 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6176 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6177 }
6178
6179 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6180 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6181 }
6182
6183 pub fn convert_to_upper_camel_case(
6184 &mut self,
6185 _: &ConvertToUpperCamelCase,
6186 cx: &mut ViewContext<Self>,
6187 ) {
6188 self.manipulate_text(cx, |text| {
6189 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6190 // https://github.com/rutrum/convert-case/issues/16
6191 text.split('\n')
6192 .map(|line| line.to_case(Case::UpperCamel))
6193 .join("\n")
6194 })
6195 }
6196
6197 pub fn convert_to_lower_camel_case(
6198 &mut self,
6199 _: &ConvertToLowerCamelCase,
6200 cx: &mut ViewContext<Self>,
6201 ) {
6202 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6203 }
6204
6205 pub fn convert_to_opposite_case(
6206 &mut self,
6207 _: &ConvertToOppositeCase,
6208 cx: &mut ViewContext<Self>,
6209 ) {
6210 self.manipulate_text(cx, |text| {
6211 text.chars()
6212 .fold(String::with_capacity(text.len()), |mut t, c| {
6213 if c.is_uppercase() {
6214 t.extend(c.to_lowercase());
6215 } else {
6216 t.extend(c.to_uppercase());
6217 }
6218 t
6219 })
6220 })
6221 }
6222
6223 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6224 where
6225 Fn: FnMut(&str) -> String,
6226 {
6227 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6228 let buffer = self.buffer.read(cx).snapshot(cx);
6229
6230 let mut new_selections = Vec::new();
6231 let mut edits = Vec::new();
6232 let mut selection_adjustment = 0i32;
6233
6234 for selection in self.selections.all::<usize>(cx) {
6235 let selection_is_empty = selection.is_empty();
6236
6237 let (start, end) = if selection_is_empty {
6238 let word_range = movement::surrounding_word(
6239 &display_map,
6240 selection.start.to_display_point(&display_map),
6241 );
6242 let start = word_range.start.to_offset(&display_map, Bias::Left);
6243 let end = word_range.end.to_offset(&display_map, Bias::Left);
6244 (start, end)
6245 } else {
6246 (selection.start, selection.end)
6247 };
6248
6249 let text = buffer.text_for_range(start..end).collect::<String>();
6250 let old_length = text.len() as i32;
6251 let text = callback(&text);
6252
6253 new_selections.push(Selection {
6254 start: (start as i32 - selection_adjustment) as usize,
6255 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6256 goal: SelectionGoal::None,
6257 ..selection
6258 });
6259
6260 selection_adjustment += old_length - text.len() as i32;
6261
6262 edits.push((start..end, text));
6263 }
6264
6265 self.transact(cx, |this, cx| {
6266 this.buffer.update(cx, |buffer, cx| {
6267 buffer.edit(edits, None, cx);
6268 });
6269
6270 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6271 s.select(new_selections);
6272 });
6273
6274 this.request_autoscroll(Autoscroll::fit(), cx);
6275 });
6276 }
6277
6278 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6279 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6280 let buffer = &display_map.buffer_snapshot;
6281 let selections = self.selections.all::<Point>(cx);
6282
6283 let mut edits = Vec::new();
6284 let mut selections_iter = selections.iter().peekable();
6285 while let Some(selection) = selections_iter.next() {
6286 // Avoid duplicating the same lines twice.
6287 let mut rows = selection.spanned_rows(false, &display_map);
6288
6289 while let Some(next_selection) = selections_iter.peek() {
6290 let next_rows = next_selection.spanned_rows(false, &display_map);
6291 if next_rows.start < rows.end {
6292 rows.end = next_rows.end;
6293 selections_iter.next().unwrap();
6294 } else {
6295 break;
6296 }
6297 }
6298
6299 // Copy the text from the selected row region and splice it either at the start
6300 // or end of the region.
6301 let start = Point::new(rows.start.0, 0);
6302 let end = Point::new(
6303 rows.end.previous_row().0,
6304 buffer.line_len(rows.end.previous_row()),
6305 );
6306 let text = buffer
6307 .text_for_range(start..end)
6308 .chain(Some("\n"))
6309 .collect::<String>();
6310 let insert_location = if upwards {
6311 Point::new(rows.end.0, 0)
6312 } else {
6313 start
6314 };
6315 edits.push((insert_location..insert_location, text));
6316 }
6317
6318 self.transact(cx, |this, cx| {
6319 this.buffer.update(cx, |buffer, cx| {
6320 buffer.edit(edits, None, cx);
6321 });
6322
6323 this.request_autoscroll(Autoscroll::fit(), cx);
6324 });
6325 }
6326
6327 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6328 self.duplicate_line(true, cx);
6329 }
6330
6331 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6332 self.duplicate_line(false, cx);
6333 }
6334
6335 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6336 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6337 let buffer = self.buffer.read(cx).snapshot(cx);
6338
6339 let mut edits = Vec::new();
6340 let mut unfold_ranges = Vec::new();
6341 let mut refold_ranges = Vec::new();
6342
6343 let selections = self.selections.all::<Point>(cx);
6344 let mut selections = selections.iter().peekable();
6345 let mut contiguous_row_selections = Vec::new();
6346 let mut new_selections = Vec::new();
6347
6348 while let Some(selection) = selections.next() {
6349 // Find all the selections that span a contiguous row range
6350 let (start_row, end_row) = consume_contiguous_rows(
6351 &mut contiguous_row_selections,
6352 selection,
6353 &display_map,
6354 &mut selections,
6355 );
6356
6357 // Move the text spanned by the row range to be before the line preceding the row range
6358 if start_row.0 > 0 {
6359 let range_to_move = Point::new(
6360 start_row.previous_row().0,
6361 buffer.line_len(start_row.previous_row()),
6362 )
6363 ..Point::new(
6364 end_row.previous_row().0,
6365 buffer.line_len(end_row.previous_row()),
6366 );
6367 let insertion_point = display_map
6368 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6369 .0;
6370
6371 // Don't move lines across excerpts
6372 if buffer
6373 .excerpt_boundaries_in_range((
6374 Bound::Excluded(insertion_point),
6375 Bound::Included(range_to_move.end),
6376 ))
6377 .next()
6378 .is_none()
6379 {
6380 let text = buffer
6381 .text_for_range(range_to_move.clone())
6382 .flat_map(|s| s.chars())
6383 .skip(1)
6384 .chain(['\n'])
6385 .collect::<String>();
6386
6387 edits.push((
6388 buffer.anchor_after(range_to_move.start)
6389 ..buffer.anchor_before(range_to_move.end),
6390 String::new(),
6391 ));
6392 let insertion_anchor = buffer.anchor_after(insertion_point);
6393 edits.push((insertion_anchor..insertion_anchor, text));
6394
6395 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6396
6397 // Move selections up
6398 new_selections.extend(contiguous_row_selections.drain(..).map(
6399 |mut selection| {
6400 selection.start.row -= row_delta;
6401 selection.end.row -= row_delta;
6402 selection
6403 },
6404 ));
6405
6406 // Move folds up
6407 unfold_ranges.push(range_to_move.clone());
6408 for fold in display_map.folds_in_range(
6409 buffer.anchor_before(range_to_move.start)
6410 ..buffer.anchor_after(range_to_move.end),
6411 ) {
6412 let mut start = fold.range.start.to_point(&buffer);
6413 let mut end = fold.range.end.to_point(&buffer);
6414 start.row -= row_delta;
6415 end.row -= row_delta;
6416 refold_ranges.push((start..end, fold.placeholder.clone()));
6417 }
6418 }
6419 }
6420
6421 // If we didn't move line(s), preserve the existing selections
6422 new_selections.append(&mut contiguous_row_selections);
6423 }
6424
6425 self.transact(cx, |this, cx| {
6426 this.unfold_ranges(unfold_ranges, true, true, cx);
6427 this.buffer.update(cx, |buffer, cx| {
6428 for (range, text) in edits {
6429 buffer.edit([(range, text)], None, cx);
6430 }
6431 });
6432 this.fold_ranges(refold_ranges, true, cx);
6433 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6434 s.select(new_selections);
6435 })
6436 });
6437 }
6438
6439 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6440 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6441 let buffer = self.buffer.read(cx).snapshot(cx);
6442
6443 let mut edits = Vec::new();
6444 let mut unfold_ranges = Vec::new();
6445 let mut refold_ranges = Vec::new();
6446
6447 let selections = self.selections.all::<Point>(cx);
6448 let mut selections = selections.iter().peekable();
6449 let mut contiguous_row_selections = Vec::new();
6450 let mut new_selections = Vec::new();
6451
6452 while let Some(selection) = selections.next() {
6453 // Find all the selections that span a contiguous row range
6454 let (start_row, end_row) = consume_contiguous_rows(
6455 &mut contiguous_row_selections,
6456 selection,
6457 &display_map,
6458 &mut selections,
6459 );
6460
6461 // Move the text spanned by the row range to be after the last line of the row range
6462 if end_row.0 <= buffer.max_point().row {
6463 let range_to_move =
6464 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6465 let insertion_point = display_map
6466 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6467 .0;
6468
6469 // Don't move lines across excerpt boundaries
6470 if buffer
6471 .excerpt_boundaries_in_range((
6472 Bound::Excluded(range_to_move.start),
6473 Bound::Included(insertion_point),
6474 ))
6475 .next()
6476 .is_none()
6477 {
6478 let mut text = String::from("\n");
6479 text.extend(buffer.text_for_range(range_to_move.clone()));
6480 text.pop(); // Drop trailing newline
6481 edits.push((
6482 buffer.anchor_after(range_to_move.start)
6483 ..buffer.anchor_before(range_to_move.end),
6484 String::new(),
6485 ));
6486 let insertion_anchor = buffer.anchor_after(insertion_point);
6487 edits.push((insertion_anchor..insertion_anchor, text));
6488
6489 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6490
6491 // Move selections down
6492 new_selections.extend(contiguous_row_selections.drain(..).map(
6493 |mut selection| {
6494 selection.start.row += row_delta;
6495 selection.end.row += row_delta;
6496 selection
6497 },
6498 ));
6499
6500 // Move folds down
6501 unfold_ranges.push(range_to_move.clone());
6502 for fold in display_map.folds_in_range(
6503 buffer.anchor_before(range_to_move.start)
6504 ..buffer.anchor_after(range_to_move.end),
6505 ) {
6506 let mut start = fold.range.start.to_point(&buffer);
6507 let mut end = fold.range.end.to_point(&buffer);
6508 start.row += row_delta;
6509 end.row += row_delta;
6510 refold_ranges.push((start..end, fold.placeholder.clone()));
6511 }
6512 }
6513 }
6514
6515 // If we didn't move line(s), preserve the existing selections
6516 new_selections.append(&mut contiguous_row_selections);
6517 }
6518
6519 self.transact(cx, |this, cx| {
6520 this.unfold_ranges(unfold_ranges, true, true, cx);
6521 this.buffer.update(cx, |buffer, cx| {
6522 for (range, text) in edits {
6523 buffer.edit([(range, text)], None, cx);
6524 }
6525 });
6526 this.fold_ranges(refold_ranges, true, cx);
6527 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6528 });
6529 }
6530
6531 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6532 let text_layout_details = &self.text_layout_details(cx);
6533 self.transact(cx, |this, cx| {
6534 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6535 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6536 let line_mode = s.line_mode;
6537 s.move_with(|display_map, selection| {
6538 if !selection.is_empty() || line_mode {
6539 return;
6540 }
6541
6542 let mut head = selection.head();
6543 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6544 if head.column() == display_map.line_len(head.row()) {
6545 transpose_offset = display_map
6546 .buffer_snapshot
6547 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6548 }
6549
6550 if transpose_offset == 0 {
6551 return;
6552 }
6553
6554 *head.column_mut() += 1;
6555 head = display_map.clip_point(head, Bias::Right);
6556 let goal = SelectionGoal::HorizontalPosition(
6557 display_map
6558 .x_for_display_point(head, &text_layout_details)
6559 .into(),
6560 );
6561 selection.collapse_to(head, goal);
6562
6563 let transpose_start = display_map
6564 .buffer_snapshot
6565 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6566 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6567 let transpose_end = display_map
6568 .buffer_snapshot
6569 .clip_offset(transpose_offset + 1, Bias::Right);
6570 if let Some(ch) =
6571 display_map.buffer_snapshot.chars_at(transpose_start).next()
6572 {
6573 edits.push((transpose_start..transpose_offset, String::new()));
6574 edits.push((transpose_end..transpose_end, ch.to_string()));
6575 }
6576 }
6577 });
6578 edits
6579 });
6580 this.buffer
6581 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6582 let selections = this.selections.all::<usize>(cx);
6583 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6584 s.select(selections);
6585 });
6586 });
6587 }
6588
6589 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6590 let mut text = String::new();
6591 let buffer = self.buffer.read(cx).snapshot(cx);
6592 let mut selections = self.selections.all::<Point>(cx);
6593 let mut clipboard_selections = Vec::with_capacity(selections.len());
6594 {
6595 let max_point = buffer.max_point();
6596 let mut is_first = true;
6597 for selection in &mut selections {
6598 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6599 if is_entire_line {
6600 selection.start = Point::new(selection.start.row, 0);
6601 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6602 selection.goal = SelectionGoal::None;
6603 }
6604 if is_first {
6605 is_first = false;
6606 } else {
6607 text += "\n";
6608 }
6609 let mut len = 0;
6610 for chunk in buffer.text_for_range(selection.start..selection.end) {
6611 text.push_str(chunk);
6612 len += chunk.len();
6613 }
6614 clipboard_selections.push(ClipboardSelection {
6615 len,
6616 is_entire_line,
6617 first_line_indent: buffer
6618 .indent_size_for_line(MultiBufferRow(selection.start.row))
6619 .len,
6620 });
6621 }
6622 }
6623
6624 self.transact(cx, |this, cx| {
6625 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6626 s.select(selections);
6627 });
6628 this.insert("", cx);
6629 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6630 text,
6631 clipboard_selections,
6632 ));
6633 });
6634 }
6635
6636 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6637 let selections = self.selections.all::<Point>(cx);
6638 let buffer = self.buffer.read(cx).read(cx);
6639 let mut text = String::new();
6640
6641 let mut clipboard_selections = Vec::with_capacity(selections.len());
6642 {
6643 let max_point = buffer.max_point();
6644 let mut is_first = true;
6645 for selection in selections.iter() {
6646 let mut start = selection.start;
6647 let mut end = selection.end;
6648 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6649 if is_entire_line {
6650 start = Point::new(start.row, 0);
6651 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6652 }
6653 if is_first {
6654 is_first = false;
6655 } else {
6656 text += "\n";
6657 }
6658 let mut len = 0;
6659 for chunk in buffer.text_for_range(start..end) {
6660 text.push_str(chunk);
6661 len += chunk.len();
6662 }
6663 clipboard_selections.push(ClipboardSelection {
6664 len,
6665 is_entire_line,
6666 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6667 });
6668 }
6669 }
6670
6671 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6672 text,
6673 clipboard_selections,
6674 ));
6675 }
6676
6677 pub fn do_paste(
6678 &mut self,
6679 text: &String,
6680 clipboard_selections: Option<Vec<ClipboardSelection>>,
6681 handle_entire_lines: bool,
6682 cx: &mut ViewContext<Self>,
6683 ) {
6684 if self.read_only(cx) {
6685 return;
6686 }
6687
6688 let clipboard_text = Cow::Borrowed(text);
6689
6690 self.transact(cx, |this, cx| {
6691 if let Some(mut clipboard_selections) = clipboard_selections {
6692 let old_selections = this.selections.all::<usize>(cx);
6693 let all_selections_were_entire_line =
6694 clipboard_selections.iter().all(|s| s.is_entire_line);
6695 let first_selection_indent_column =
6696 clipboard_selections.first().map(|s| s.first_line_indent);
6697 if clipboard_selections.len() != old_selections.len() {
6698 clipboard_selections.drain(..);
6699 }
6700
6701 this.buffer.update(cx, |buffer, cx| {
6702 let snapshot = buffer.read(cx);
6703 let mut start_offset = 0;
6704 let mut edits = Vec::new();
6705 let mut original_indent_columns = Vec::new();
6706 for (ix, selection) in old_selections.iter().enumerate() {
6707 let to_insert;
6708 let entire_line;
6709 let original_indent_column;
6710 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6711 let end_offset = start_offset + clipboard_selection.len;
6712 to_insert = &clipboard_text[start_offset..end_offset];
6713 entire_line = clipboard_selection.is_entire_line;
6714 start_offset = end_offset + 1;
6715 original_indent_column = Some(clipboard_selection.first_line_indent);
6716 } else {
6717 to_insert = clipboard_text.as_str();
6718 entire_line = all_selections_were_entire_line;
6719 original_indent_column = first_selection_indent_column
6720 }
6721
6722 // If the corresponding selection was empty when this slice of the
6723 // clipboard text was written, then the entire line containing the
6724 // selection was copied. If this selection is also currently empty,
6725 // then paste the line before the current line of the buffer.
6726 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6727 let column = selection.start.to_point(&snapshot).column as usize;
6728 let line_start = selection.start - column;
6729 line_start..line_start
6730 } else {
6731 selection.range()
6732 };
6733
6734 edits.push((range, to_insert));
6735 original_indent_columns.extend(original_indent_column);
6736 }
6737 drop(snapshot);
6738
6739 buffer.edit(
6740 edits,
6741 Some(AutoindentMode::Block {
6742 original_indent_columns,
6743 }),
6744 cx,
6745 );
6746 });
6747
6748 let selections = this.selections.all::<usize>(cx);
6749 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6750 } else {
6751 this.insert(&clipboard_text, cx);
6752 }
6753 });
6754 }
6755
6756 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6757 if let Some(item) = cx.read_from_clipboard() {
6758 let entries = item.entries();
6759
6760 match entries.first() {
6761 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6762 // of all the pasted entries.
6763 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6764 .do_paste(
6765 clipboard_string.text(),
6766 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6767 true,
6768 cx,
6769 ),
6770 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6771 }
6772 }
6773 }
6774
6775 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6776 if self.read_only(cx) {
6777 return;
6778 }
6779
6780 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6781 if let Some((selections, _)) =
6782 self.selection_history.transaction(transaction_id).cloned()
6783 {
6784 self.change_selections(None, cx, |s| {
6785 s.select_anchors(selections.to_vec());
6786 });
6787 }
6788 self.request_autoscroll(Autoscroll::fit(), cx);
6789 self.unmark_text(cx);
6790 self.refresh_inline_completion(true, false, cx);
6791 cx.emit(EditorEvent::Edited { transaction_id });
6792 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6793 }
6794 }
6795
6796 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6797 if self.read_only(cx) {
6798 return;
6799 }
6800
6801 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6802 if let Some((_, Some(selections))) =
6803 self.selection_history.transaction(transaction_id).cloned()
6804 {
6805 self.change_selections(None, cx, |s| {
6806 s.select_anchors(selections.to_vec());
6807 });
6808 }
6809 self.request_autoscroll(Autoscroll::fit(), cx);
6810 self.unmark_text(cx);
6811 self.refresh_inline_completion(true, false, cx);
6812 cx.emit(EditorEvent::Edited { transaction_id });
6813 }
6814 }
6815
6816 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6817 self.buffer
6818 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6819 }
6820
6821 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6822 self.buffer
6823 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6824 }
6825
6826 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6827 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6828 let line_mode = s.line_mode;
6829 s.move_with(|map, selection| {
6830 let cursor = if selection.is_empty() && !line_mode {
6831 movement::left(map, selection.start)
6832 } else {
6833 selection.start
6834 };
6835 selection.collapse_to(cursor, SelectionGoal::None);
6836 });
6837 })
6838 }
6839
6840 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6841 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6842 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6843 })
6844 }
6845
6846 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6847 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6848 let line_mode = s.line_mode;
6849 s.move_with(|map, selection| {
6850 let cursor = if selection.is_empty() && !line_mode {
6851 movement::right(map, selection.end)
6852 } else {
6853 selection.end
6854 };
6855 selection.collapse_to(cursor, SelectionGoal::None)
6856 });
6857 })
6858 }
6859
6860 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6861 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6862 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6863 })
6864 }
6865
6866 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6867 if self.take_rename(true, cx).is_some() {
6868 return;
6869 }
6870
6871 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6872 cx.propagate();
6873 return;
6874 }
6875
6876 let text_layout_details = &self.text_layout_details(cx);
6877 let selection_count = self.selections.count();
6878 let first_selection = self.selections.first_anchor();
6879
6880 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6881 let line_mode = s.line_mode;
6882 s.move_with(|map, selection| {
6883 if !selection.is_empty() && !line_mode {
6884 selection.goal = SelectionGoal::None;
6885 }
6886 let (cursor, goal) = movement::up(
6887 map,
6888 selection.start,
6889 selection.goal,
6890 false,
6891 &text_layout_details,
6892 );
6893 selection.collapse_to(cursor, goal);
6894 });
6895 });
6896
6897 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6898 {
6899 cx.propagate();
6900 }
6901 }
6902
6903 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6904 if self.take_rename(true, cx).is_some() {
6905 return;
6906 }
6907
6908 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6909 cx.propagate();
6910 return;
6911 }
6912
6913 let text_layout_details = &self.text_layout_details(cx);
6914
6915 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6916 let line_mode = s.line_mode;
6917 s.move_with(|map, selection| {
6918 if !selection.is_empty() && !line_mode {
6919 selection.goal = SelectionGoal::None;
6920 }
6921 let (cursor, goal) = movement::up_by_rows(
6922 map,
6923 selection.start,
6924 action.lines,
6925 selection.goal,
6926 false,
6927 &text_layout_details,
6928 );
6929 selection.collapse_to(cursor, goal);
6930 });
6931 })
6932 }
6933
6934 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
6935 if self.take_rename(true, cx).is_some() {
6936 return;
6937 }
6938
6939 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6940 cx.propagate();
6941 return;
6942 }
6943
6944 let text_layout_details = &self.text_layout_details(cx);
6945
6946 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6947 let line_mode = s.line_mode;
6948 s.move_with(|map, selection| {
6949 if !selection.is_empty() && !line_mode {
6950 selection.goal = SelectionGoal::None;
6951 }
6952 let (cursor, goal) = movement::down_by_rows(
6953 map,
6954 selection.start,
6955 action.lines,
6956 selection.goal,
6957 false,
6958 &text_layout_details,
6959 );
6960 selection.collapse_to(cursor, goal);
6961 });
6962 })
6963 }
6964
6965 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
6966 let text_layout_details = &self.text_layout_details(cx);
6967 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6968 s.move_heads_with(|map, head, goal| {
6969 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6970 })
6971 })
6972 }
6973
6974 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
6975 let text_layout_details = &self.text_layout_details(cx);
6976 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6977 s.move_heads_with(|map, head, goal| {
6978 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6979 })
6980 })
6981 }
6982
6983 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
6984 let Some(row_count) = self.visible_row_count() else {
6985 return;
6986 };
6987
6988 let text_layout_details = &self.text_layout_details(cx);
6989
6990 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6991 s.move_heads_with(|map, head, goal| {
6992 movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
6993 })
6994 })
6995 }
6996
6997 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
6998 if self.take_rename(true, cx).is_some() {
6999 return;
7000 }
7001
7002 if self
7003 .context_menu
7004 .write()
7005 .as_mut()
7006 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7007 .unwrap_or(false)
7008 {
7009 return;
7010 }
7011
7012 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7013 cx.propagate();
7014 return;
7015 }
7016
7017 let Some(row_count) = self.visible_row_count() else {
7018 return;
7019 };
7020
7021 let autoscroll = if action.center_cursor {
7022 Autoscroll::center()
7023 } else {
7024 Autoscroll::fit()
7025 };
7026
7027 let text_layout_details = &self.text_layout_details(cx);
7028
7029 self.change_selections(Some(autoscroll), cx, |s| {
7030 let line_mode = s.line_mode;
7031 s.move_with(|map, selection| {
7032 if !selection.is_empty() && !line_mode {
7033 selection.goal = SelectionGoal::None;
7034 }
7035 let (cursor, goal) = movement::up_by_rows(
7036 map,
7037 selection.end,
7038 row_count,
7039 selection.goal,
7040 false,
7041 &text_layout_details,
7042 );
7043 selection.collapse_to(cursor, goal);
7044 });
7045 });
7046 }
7047
7048 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7049 let text_layout_details = &self.text_layout_details(cx);
7050 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7051 s.move_heads_with(|map, head, goal| {
7052 movement::up(map, head, goal, false, &text_layout_details)
7053 })
7054 })
7055 }
7056
7057 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7058 self.take_rename(true, cx);
7059
7060 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7061 cx.propagate();
7062 return;
7063 }
7064
7065 let text_layout_details = &self.text_layout_details(cx);
7066 let selection_count = self.selections.count();
7067 let first_selection = self.selections.first_anchor();
7068
7069 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7070 let line_mode = s.line_mode;
7071 s.move_with(|map, selection| {
7072 if !selection.is_empty() && !line_mode {
7073 selection.goal = SelectionGoal::None;
7074 }
7075 let (cursor, goal) = movement::down(
7076 map,
7077 selection.end,
7078 selection.goal,
7079 false,
7080 &text_layout_details,
7081 );
7082 selection.collapse_to(cursor, goal);
7083 });
7084 });
7085
7086 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7087 {
7088 cx.propagate();
7089 }
7090 }
7091
7092 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7093 let Some(row_count) = self.visible_row_count() else {
7094 return;
7095 };
7096
7097 let text_layout_details = &self.text_layout_details(cx);
7098
7099 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7100 s.move_heads_with(|map, head, goal| {
7101 movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
7102 })
7103 })
7104 }
7105
7106 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7107 if self.take_rename(true, cx).is_some() {
7108 return;
7109 }
7110
7111 if self
7112 .context_menu
7113 .write()
7114 .as_mut()
7115 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7116 .unwrap_or(false)
7117 {
7118 return;
7119 }
7120
7121 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7122 cx.propagate();
7123 return;
7124 }
7125
7126 let Some(row_count) = self.visible_row_count() else {
7127 return;
7128 };
7129
7130 let autoscroll = if action.center_cursor {
7131 Autoscroll::center()
7132 } else {
7133 Autoscroll::fit()
7134 };
7135
7136 let text_layout_details = &self.text_layout_details(cx);
7137 self.change_selections(Some(autoscroll), cx, |s| {
7138 let line_mode = s.line_mode;
7139 s.move_with(|map, selection| {
7140 if !selection.is_empty() && !line_mode {
7141 selection.goal = SelectionGoal::None;
7142 }
7143 let (cursor, goal) = movement::down_by_rows(
7144 map,
7145 selection.end,
7146 row_count,
7147 selection.goal,
7148 false,
7149 &text_layout_details,
7150 );
7151 selection.collapse_to(cursor, goal);
7152 });
7153 });
7154 }
7155
7156 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7157 let text_layout_details = &self.text_layout_details(cx);
7158 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7159 s.move_heads_with(|map, head, goal| {
7160 movement::down(map, head, goal, false, &text_layout_details)
7161 })
7162 });
7163 }
7164
7165 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7166 if let Some(context_menu) = self.context_menu.write().as_mut() {
7167 context_menu.select_first(self.project.as_ref(), cx);
7168 }
7169 }
7170
7171 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7172 if let Some(context_menu) = self.context_menu.write().as_mut() {
7173 context_menu.select_prev(self.project.as_ref(), cx);
7174 }
7175 }
7176
7177 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7178 if let Some(context_menu) = self.context_menu.write().as_mut() {
7179 context_menu.select_next(self.project.as_ref(), cx);
7180 }
7181 }
7182
7183 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7184 if let Some(context_menu) = self.context_menu.write().as_mut() {
7185 context_menu.select_last(self.project.as_ref(), cx);
7186 }
7187 }
7188
7189 pub fn move_to_previous_word_start(
7190 &mut self,
7191 _: &MoveToPreviousWordStart,
7192 cx: &mut ViewContext<Self>,
7193 ) {
7194 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7195 s.move_cursors_with(|map, head, _| {
7196 (
7197 movement::previous_word_start(map, head),
7198 SelectionGoal::None,
7199 )
7200 });
7201 })
7202 }
7203
7204 pub fn move_to_previous_subword_start(
7205 &mut self,
7206 _: &MoveToPreviousSubwordStart,
7207 cx: &mut ViewContext<Self>,
7208 ) {
7209 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7210 s.move_cursors_with(|map, head, _| {
7211 (
7212 movement::previous_subword_start(map, head),
7213 SelectionGoal::None,
7214 )
7215 });
7216 })
7217 }
7218
7219 pub fn select_to_previous_word_start(
7220 &mut self,
7221 _: &SelectToPreviousWordStart,
7222 cx: &mut ViewContext<Self>,
7223 ) {
7224 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7225 s.move_heads_with(|map, head, _| {
7226 (
7227 movement::previous_word_start(map, head),
7228 SelectionGoal::None,
7229 )
7230 });
7231 })
7232 }
7233
7234 pub fn select_to_previous_subword_start(
7235 &mut self,
7236 _: &SelectToPreviousSubwordStart,
7237 cx: &mut ViewContext<Self>,
7238 ) {
7239 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7240 s.move_heads_with(|map, head, _| {
7241 (
7242 movement::previous_subword_start(map, head),
7243 SelectionGoal::None,
7244 )
7245 });
7246 })
7247 }
7248
7249 pub fn delete_to_previous_word_start(
7250 &mut self,
7251 _: &DeleteToPreviousWordStart,
7252 cx: &mut ViewContext<Self>,
7253 ) {
7254 self.transact(cx, |this, cx| {
7255 this.select_autoclose_pair(cx);
7256 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7257 let line_mode = s.line_mode;
7258 s.move_with(|map, selection| {
7259 if selection.is_empty() && !line_mode {
7260 let cursor = movement::previous_word_start(map, selection.head());
7261 selection.set_head(cursor, SelectionGoal::None);
7262 }
7263 });
7264 });
7265 this.insert("", cx);
7266 });
7267 }
7268
7269 pub fn delete_to_previous_subword_start(
7270 &mut self,
7271 _: &DeleteToPreviousSubwordStart,
7272 cx: &mut ViewContext<Self>,
7273 ) {
7274 self.transact(cx, |this, cx| {
7275 this.select_autoclose_pair(cx);
7276 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7277 let line_mode = s.line_mode;
7278 s.move_with(|map, selection| {
7279 if selection.is_empty() && !line_mode {
7280 let cursor = movement::previous_subword_start(map, selection.head());
7281 selection.set_head(cursor, SelectionGoal::None);
7282 }
7283 });
7284 });
7285 this.insert("", cx);
7286 });
7287 }
7288
7289 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7290 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7291 s.move_cursors_with(|map, head, _| {
7292 (movement::next_word_end(map, head), SelectionGoal::None)
7293 });
7294 })
7295 }
7296
7297 pub fn move_to_next_subword_end(
7298 &mut self,
7299 _: &MoveToNextSubwordEnd,
7300 cx: &mut ViewContext<Self>,
7301 ) {
7302 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7303 s.move_cursors_with(|map, head, _| {
7304 (movement::next_subword_end(map, head), SelectionGoal::None)
7305 });
7306 })
7307 }
7308
7309 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7310 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7311 s.move_heads_with(|map, head, _| {
7312 (movement::next_word_end(map, head), SelectionGoal::None)
7313 });
7314 })
7315 }
7316
7317 pub fn select_to_next_subword_end(
7318 &mut self,
7319 _: &SelectToNextSubwordEnd,
7320 cx: &mut ViewContext<Self>,
7321 ) {
7322 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7323 s.move_heads_with(|map, head, _| {
7324 (movement::next_subword_end(map, head), SelectionGoal::None)
7325 });
7326 })
7327 }
7328
7329 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
7330 self.transact(cx, |this, cx| {
7331 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7332 let line_mode = s.line_mode;
7333 s.move_with(|map, selection| {
7334 if selection.is_empty() && !line_mode {
7335 let cursor = movement::next_word_end(map, selection.head());
7336 selection.set_head(cursor, SelectionGoal::None);
7337 }
7338 });
7339 });
7340 this.insert("", cx);
7341 });
7342 }
7343
7344 pub fn delete_to_next_subword_end(
7345 &mut self,
7346 _: &DeleteToNextSubwordEnd,
7347 cx: &mut ViewContext<Self>,
7348 ) {
7349 self.transact(cx, |this, cx| {
7350 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7351 s.move_with(|map, selection| {
7352 if selection.is_empty() {
7353 let cursor = movement::next_subword_end(map, selection.head());
7354 selection.set_head(cursor, SelectionGoal::None);
7355 }
7356 });
7357 });
7358 this.insert("", cx);
7359 });
7360 }
7361
7362 pub fn move_to_beginning_of_line(
7363 &mut self,
7364 action: &MoveToBeginningOfLine,
7365 cx: &mut ViewContext<Self>,
7366 ) {
7367 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7368 s.move_cursors_with(|map, head, _| {
7369 (
7370 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7371 SelectionGoal::None,
7372 )
7373 });
7374 })
7375 }
7376
7377 pub fn select_to_beginning_of_line(
7378 &mut self,
7379 action: &SelectToBeginningOfLine,
7380 cx: &mut ViewContext<Self>,
7381 ) {
7382 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7383 s.move_heads_with(|map, head, _| {
7384 (
7385 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7386 SelectionGoal::None,
7387 )
7388 });
7389 });
7390 }
7391
7392 pub fn delete_to_beginning_of_line(
7393 &mut self,
7394 _: &DeleteToBeginningOfLine,
7395 cx: &mut ViewContext<Self>,
7396 ) {
7397 self.transact(cx, |this, cx| {
7398 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7399 s.move_with(|_, selection| {
7400 selection.reversed = true;
7401 });
7402 });
7403
7404 this.select_to_beginning_of_line(
7405 &SelectToBeginningOfLine {
7406 stop_at_soft_wraps: false,
7407 },
7408 cx,
7409 );
7410 this.backspace(&Backspace, cx);
7411 });
7412 }
7413
7414 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7415 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7416 s.move_cursors_with(|map, head, _| {
7417 (
7418 movement::line_end(map, head, action.stop_at_soft_wraps),
7419 SelectionGoal::None,
7420 )
7421 });
7422 })
7423 }
7424
7425 pub fn select_to_end_of_line(
7426 &mut self,
7427 action: &SelectToEndOfLine,
7428 cx: &mut ViewContext<Self>,
7429 ) {
7430 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7431 s.move_heads_with(|map, head, _| {
7432 (
7433 movement::line_end(map, head, action.stop_at_soft_wraps),
7434 SelectionGoal::None,
7435 )
7436 });
7437 })
7438 }
7439
7440 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7441 self.transact(cx, |this, cx| {
7442 this.select_to_end_of_line(
7443 &SelectToEndOfLine {
7444 stop_at_soft_wraps: false,
7445 },
7446 cx,
7447 );
7448 this.delete(&Delete, cx);
7449 });
7450 }
7451
7452 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7453 self.transact(cx, |this, cx| {
7454 this.select_to_end_of_line(
7455 &SelectToEndOfLine {
7456 stop_at_soft_wraps: false,
7457 },
7458 cx,
7459 );
7460 this.cut(&Cut, cx);
7461 });
7462 }
7463
7464 pub fn move_to_start_of_paragraph(
7465 &mut self,
7466 _: &MoveToStartOfParagraph,
7467 cx: &mut ViewContext<Self>,
7468 ) {
7469 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7470 cx.propagate();
7471 return;
7472 }
7473
7474 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7475 s.move_with(|map, selection| {
7476 selection.collapse_to(
7477 movement::start_of_paragraph(map, selection.head(), 1),
7478 SelectionGoal::None,
7479 )
7480 });
7481 })
7482 }
7483
7484 pub fn move_to_end_of_paragraph(
7485 &mut self,
7486 _: &MoveToEndOfParagraph,
7487 cx: &mut ViewContext<Self>,
7488 ) {
7489 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7490 cx.propagate();
7491 return;
7492 }
7493
7494 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7495 s.move_with(|map, selection| {
7496 selection.collapse_to(
7497 movement::end_of_paragraph(map, selection.head(), 1),
7498 SelectionGoal::None,
7499 )
7500 });
7501 })
7502 }
7503
7504 pub fn select_to_start_of_paragraph(
7505 &mut self,
7506 _: &SelectToStartOfParagraph,
7507 cx: &mut ViewContext<Self>,
7508 ) {
7509 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7510 cx.propagate();
7511 return;
7512 }
7513
7514 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7515 s.move_heads_with(|map, head, _| {
7516 (
7517 movement::start_of_paragraph(map, head, 1),
7518 SelectionGoal::None,
7519 )
7520 });
7521 })
7522 }
7523
7524 pub fn select_to_end_of_paragraph(
7525 &mut self,
7526 _: &SelectToEndOfParagraph,
7527 cx: &mut ViewContext<Self>,
7528 ) {
7529 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7530 cx.propagate();
7531 return;
7532 }
7533
7534 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7535 s.move_heads_with(|map, head, _| {
7536 (
7537 movement::end_of_paragraph(map, head, 1),
7538 SelectionGoal::None,
7539 )
7540 });
7541 })
7542 }
7543
7544 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7545 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7546 cx.propagate();
7547 return;
7548 }
7549
7550 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7551 s.select_ranges(vec![0..0]);
7552 });
7553 }
7554
7555 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7556 let mut selection = self.selections.last::<Point>(cx);
7557 selection.set_head(Point::zero(), SelectionGoal::None);
7558
7559 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7560 s.select(vec![selection]);
7561 });
7562 }
7563
7564 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7565 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7566 cx.propagate();
7567 return;
7568 }
7569
7570 let cursor = self.buffer.read(cx).read(cx).len();
7571 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7572 s.select_ranges(vec![cursor..cursor])
7573 });
7574 }
7575
7576 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7577 self.nav_history = nav_history;
7578 }
7579
7580 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7581 self.nav_history.as_ref()
7582 }
7583
7584 fn push_to_nav_history(
7585 &mut self,
7586 cursor_anchor: Anchor,
7587 new_position: Option<Point>,
7588 cx: &mut ViewContext<Self>,
7589 ) {
7590 if let Some(nav_history) = self.nav_history.as_mut() {
7591 let buffer = self.buffer.read(cx).read(cx);
7592 let cursor_position = cursor_anchor.to_point(&buffer);
7593 let scroll_state = self.scroll_manager.anchor();
7594 let scroll_top_row = scroll_state.top_row(&buffer);
7595 drop(buffer);
7596
7597 if let Some(new_position) = new_position {
7598 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7599 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7600 return;
7601 }
7602 }
7603
7604 nav_history.push(
7605 Some(NavigationData {
7606 cursor_anchor,
7607 cursor_position,
7608 scroll_anchor: scroll_state,
7609 scroll_top_row,
7610 }),
7611 cx,
7612 );
7613 }
7614 }
7615
7616 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7617 let buffer = self.buffer.read(cx).snapshot(cx);
7618 let mut selection = self.selections.first::<usize>(cx);
7619 selection.set_head(buffer.len(), SelectionGoal::None);
7620 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7621 s.select(vec![selection]);
7622 });
7623 }
7624
7625 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7626 let end = self.buffer.read(cx).read(cx).len();
7627 self.change_selections(None, cx, |s| {
7628 s.select_ranges(vec![0..end]);
7629 });
7630 }
7631
7632 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7633 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7634 let mut selections = self.selections.all::<Point>(cx);
7635 let max_point = display_map.buffer_snapshot.max_point();
7636 for selection in &mut selections {
7637 let rows = selection.spanned_rows(true, &display_map);
7638 selection.start = Point::new(rows.start.0, 0);
7639 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7640 selection.reversed = false;
7641 }
7642 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7643 s.select(selections);
7644 });
7645 }
7646
7647 pub fn split_selection_into_lines(
7648 &mut self,
7649 _: &SplitSelectionIntoLines,
7650 cx: &mut ViewContext<Self>,
7651 ) {
7652 let mut to_unfold = Vec::new();
7653 let mut new_selection_ranges = Vec::new();
7654 {
7655 let selections = self.selections.all::<Point>(cx);
7656 let buffer = self.buffer.read(cx).read(cx);
7657 for selection in selections {
7658 for row in selection.start.row..selection.end.row {
7659 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7660 new_selection_ranges.push(cursor..cursor);
7661 }
7662 new_selection_ranges.push(selection.end..selection.end);
7663 to_unfold.push(selection.start..selection.end);
7664 }
7665 }
7666 self.unfold_ranges(to_unfold, true, true, cx);
7667 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7668 s.select_ranges(new_selection_ranges);
7669 });
7670 }
7671
7672 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7673 self.add_selection(true, cx);
7674 }
7675
7676 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7677 self.add_selection(false, cx);
7678 }
7679
7680 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7681 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7682 let mut selections = self.selections.all::<Point>(cx);
7683 let text_layout_details = self.text_layout_details(cx);
7684 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7685 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7686 let range = oldest_selection.display_range(&display_map).sorted();
7687
7688 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7689 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7690 let positions = start_x.min(end_x)..start_x.max(end_x);
7691
7692 selections.clear();
7693 let mut stack = Vec::new();
7694 for row in range.start.row().0..=range.end.row().0 {
7695 if let Some(selection) = self.selections.build_columnar_selection(
7696 &display_map,
7697 DisplayRow(row),
7698 &positions,
7699 oldest_selection.reversed,
7700 &text_layout_details,
7701 ) {
7702 stack.push(selection.id);
7703 selections.push(selection);
7704 }
7705 }
7706
7707 if above {
7708 stack.reverse();
7709 }
7710
7711 AddSelectionsState { above, stack }
7712 });
7713
7714 let last_added_selection = *state.stack.last().unwrap();
7715 let mut new_selections = Vec::new();
7716 if above == state.above {
7717 let end_row = if above {
7718 DisplayRow(0)
7719 } else {
7720 display_map.max_point().row()
7721 };
7722
7723 'outer: for selection in selections {
7724 if selection.id == last_added_selection {
7725 let range = selection.display_range(&display_map).sorted();
7726 debug_assert_eq!(range.start.row(), range.end.row());
7727 let mut row = range.start.row();
7728 let positions =
7729 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7730 px(start)..px(end)
7731 } else {
7732 let start_x =
7733 display_map.x_for_display_point(range.start, &text_layout_details);
7734 let end_x =
7735 display_map.x_for_display_point(range.end, &text_layout_details);
7736 start_x.min(end_x)..start_x.max(end_x)
7737 };
7738
7739 while row != end_row {
7740 if above {
7741 row.0 -= 1;
7742 } else {
7743 row.0 += 1;
7744 }
7745
7746 if let Some(new_selection) = self.selections.build_columnar_selection(
7747 &display_map,
7748 row,
7749 &positions,
7750 selection.reversed,
7751 &text_layout_details,
7752 ) {
7753 state.stack.push(new_selection.id);
7754 if above {
7755 new_selections.push(new_selection);
7756 new_selections.push(selection);
7757 } else {
7758 new_selections.push(selection);
7759 new_selections.push(new_selection);
7760 }
7761
7762 continue 'outer;
7763 }
7764 }
7765 }
7766
7767 new_selections.push(selection);
7768 }
7769 } else {
7770 new_selections = selections;
7771 new_selections.retain(|s| s.id != last_added_selection);
7772 state.stack.pop();
7773 }
7774
7775 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7776 s.select(new_selections);
7777 });
7778 if state.stack.len() > 1 {
7779 self.add_selections_state = Some(state);
7780 }
7781 }
7782
7783 pub fn select_next_match_internal(
7784 &mut self,
7785 display_map: &DisplaySnapshot,
7786 replace_newest: bool,
7787 autoscroll: Option<Autoscroll>,
7788 cx: &mut ViewContext<Self>,
7789 ) -> Result<()> {
7790 fn select_next_match_ranges(
7791 this: &mut Editor,
7792 range: Range<usize>,
7793 replace_newest: bool,
7794 auto_scroll: Option<Autoscroll>,
7795 cx: &mut ViewContext<Editor>,
7796 ) {
7797 this.unfold_ranges([range.clone()], false, true, cx);
7798 this.change_selections(auto_scroll, cx, |s| {
7799 if replace_newest {
7800 s.delete(s.newest_anchor().id);
7801 }
7802 s.insert_range(range.clone());
7803 });
7804 }
7805
7806 let buffer = &display_map.buffer_snapshot;
7807 let mut selections = self.selections.all::<usize>(cx);
7808 if let Some(mut select_next_state) = self.select_next_state.take() {
7809 let query = &select_next_state.query;
7810 if !select_next_state.done {
7811 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7812 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7813 let mut next_selected_range = None;
7814
7815 let bytes_after_last_selection =
7816 buffer.bytes_in_range(last_selection.end..buffer.len());
7817 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7818 let query_matches = query
7819 .stream_find_iter(bytes_after_last_selection)
7820 .map(|result| (last_selection.end, result))
7821 .chain(
7822 query
7823 .stream_find_iter(bytes_before_first_selection)
7824 .map(|result| (0, result)),
7825 );
7826
7827 for (start_offset, query_match) in query_matches {
7828 let query_match = query_match.unwrap(); // can only fail due to I/O
7829 let offset_range =
7830 start_offset + query_match.start()..start_offset + query_match.end();
7831 let display_range = offset_range.start.to_display_point(&display_map)
7832 ..offset_range.end.to_display_point(&display_map);
7833
7834 if !select_next_state.wordwise
7835 || (!movement::is_inside_word(&display_map, display_range.start)
7836 && !movement::is_inside_word(&display_map, display_range.end))
7837 {
7838 // TODO: This is n^2, because we might check all the selections
7839 if !selections
7840 .iter()
7841 .any(|selection| selection.range().overlaps(&offset_range))
7842 {
7843 next_selected_range = Some(offset_range);
7844 break;
7845 }
7846 }
7847 }
7848
7849 if let Some(next_selected_range) = next_selected_range {
7850 select_next_match_ranges(
7851 self,
7852 next_selected_range,
7853 replace_newest,
7854 autoscroll,
7855 cx,
7856 );
7857 } else {
7858 select_next_state.done = true;
7859 }
7860 }
7861
7862 self.select_next_state = Some(select_next_state);
7863 } else {
7864 let mut only_carets = true;
7865 let mut same_text_selected = true;
7866 let mut selected_text = None;
7867
7868 let mut selections_iter = selections.iter().peekable();
7869 while let Some(selection) = selections_iter.next() {
7870 if selection.start != selection.end {
7871 only_carets = false;
7872 }
7873
7874 if same_text_selected {
7875 if selected_text.is_none() {
7876 selected_text =
7877 Some(buffer.text_for_range(selection.range()).collect::<String>());
7878 }
7879
7880 if let Some(next_selection) = selections_iter.peek() {
7881 if next_selection.range().len() == selection.range().len() {
7882 let next_selected_text = buffer
7883 .text_for_range(next_selection.range())
7884 .collect::<String>();
7885 if Some(next_selected_text) != selected_text {
7886 same_text_selected = false;
7887 selected_text = None;
7888 }
7889 } else {
7890 same_text_selected = false;
7891 selected_text = None;
7892 }
7893 }
7894 }
7895 }
7896
7897 if only_carets {
7898 for selection in &mut selections {
7899 let word_range = movement::surrounding_word(
7900 &display_map,
7901 selection.start.to_display_point(&display_map),
7902 );
7903 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7904 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7905 selection.goal = SelectionGoal::None;
7906 selection.reversed = false;
7907 select_next_match_ranges(
7908 self,
7909 selection.start..selection.end,
7910 replace_newest,
7911 autoscroll,
7912 cx,
7913 );
7914 }
7915
7916 if selections.len() == 1 {
7917 let selection = selections
7918 .last()
7919 .expect("ensured that there's only one selection");
7920 let query = buffer
7921 .text_for_range(selection.start..selection.end)
7922 .collect::<String>();
7923 let is_empty = query.is_empty();
7924 let select_state = SelectNextState {
7925 query: AhoCorasick::new(&[query])?,
7926 wordwise: true,
7927 done: is_empty,
7928 };
7929 self.select_next_state = Some(select_state);
7930 } else {
7931 self.select_next_state = None;
7932 }
7933 } else if let Some(selected_text) = selected_text {
7934 self.select_next_state = Some(SelectNextState {
7935 query: AhoCorasick::new(&[selected_text])?,
7936 wordwise: false,
7937 done: false,
7938 });
7939 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
7940 }
7941 }
7942 Ok(())
7943 }
7944
7945 pub fn select_all_matches(
7946 &mut self,
7947 _action: &SelectAllMatches,
7948 cx: &mut ViewContext<Self>,
7949 ) -> Result<()> {
7950 self.push_to_selection_history();
7951 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7952
7953 self.select_next_match_internal(&display_map, false, None, cx)?;
7954 let Some(select_next_state) = self.select_next_state.as_mut() else {
7955 return Ok(());
7956 };
7957 if select_next_state.done {
7958 return Ok(());
7959 }
7960
7961 let mut new_selections = self.selections.all::<usize>(cx);
7962
7963 let buffer = &display_map.buffer_snapshot;
7964 let query_matches = select_next_state
7965 .query
7966 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
7967
7968 for query_match in query_matches {
7969 let query_match = query_match.unwrap(); // can only fail due to I/O
7970 let offset_range = query_match.start()..query_match.end();
7971 let display_range = offset_range.start.to_display_point(&display_map)
7972 ..offset_range.end.to_display_point(&display_map);
7973
7974 if !select_next_state.wordwise
7975 || (!movement::is_inside_word(&display_map, display_range.start)
7976 && !movement::is_inside_word(&display_map, display_range.end))
7977 {
7978 self.selections.change_with(cx, |selections| {
7979 new_selections.push(Selection {
7980 id: selections.new_selection_id(),
7981 start: offset_range.start,
7982 end: offset_range.end,
7983 reversed: false,
7984 goal: SelectionGoal::None,
7985 });
7986 });
7987 }
7988 }
7989
7990 new_selections.sort_by_key(|selection| selection.start);
7991 let mut ix = 0;
7992 while ix + 1 < new_selections.len() {
7993 let current_selection = &new_selections[ix];
7994 let next_selection = &new_selections[ix + 1];
7995 if current_selection.range().overlaps(&next_selection.range()) {
7996 if current_selection.id < next_selection.id {
7997 new_selections.remove(ix + 1);
7998 } else {
7999 new_selections.remove(ix);
8000 }
8001 } else {
8002 ix += 1;
8003 }
8004 }
8005
8006 select_next_state.done = true;
8007 self.unfold_ranges(
8008 new_selections.iter().map(|selection| selection.range()),
8009 false,
8010 false,
8011 cx,
8012 );
8013 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8014 selections.select(new_selections)
8015 });
8016
8017 Ok(())
8018 }
8019
8020 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8021 self.push_to_selection_history();
8022 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8023 self.select_next_match_internal(
8024 &display_map,
8025 action.replace_newest,
8026 Some(Autoscroll::newest()),
8027 cx,
8028 )?;
8029 Ok(())
8030 }
8031
8032 pub fn select_previous(
8033 &mut self,
8034 action: &SelectPrevious,
8035 cx: &mut ViewContext<Self>,
8036 ) -> Result<()> {
8037 self.push_to_selection_history();
8038 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8039 let buffer = &display_map.buffer_snapshot;
8040 let mut selections = self.selections.all::<usize>(cx);
8041 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8042 let query = &select_prev_state.query;
8043 if !select_prev_state.done {
8044 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8045 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8046 let mut next_selected_range = None;
8047 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8048 let bytes_before_last_selection =
8049 buffer.reversed_bytes_in_range(0..last_selection.start);
8050 let bytes_after_first_selection =
8051 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8052 let query_matches = query
8053 .stream_find_iter(bytes_before_last_selection)
8054 .map(|result| (last_selection.start, result))
8055 .chain(
8056 query
8057 .stream_find_iter(bytes_after_first_selection)
8058 .map(|result| (buffer.len(), result)),
8059 );
8060 for (end_offset, query_match) in query_matches {
8061 let query_match = query_match.unwrap(); // can only fail due to I/O
8062 let offset_range =
8063 end_offset - query_match.end()..end_offset - query_match.start();
8064 let display_range = offset_range.start.to_display_point(&display_map)
8065 ..offset_range.end.to_display_point(&display_map);
8066
8067 if !select_prev_state.wordwise
8068 || (!movement::is_inside_word(&display_map, display_range.start)
8069 && !movement::is_inside_word(&display_map, display_range.end))
8070 {
8071 next_selected_range = Some(offset_range);
8072 break;
8073 }
8074 }
8075
8076 if let Some(next_selected_range) = next_selected_range {
8077 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8078 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8079 if action.replace_newest {
8080 s.delete(s.newest_anchor().id);
8081 }
8082 s.insert_range(next_selected_range);
8083 });
8084 } else {
8085 select_prev_state.done = true;
8086 }
8087 }
8088
8089 self.select_prev_state = Some(select_prev_state);
8090 } else {
8091 let mut only_carets = true;
8092 let mut same_text_selected = true;
8093 let mut selected_text = None;
8094
8095 let mut selections_iter = selections.iter().peekable();
8096 while let Some(selection) = selections_iter.next() {
8097 if selection.start != selection.end {
8098 only_carets = false;
8099 }
8100
8101 if same_text_selected {
8102 if selected_text.is_none() {
8103 selected_text =
8104 Some(buffer.text_for_range(selection.range()).collect::<String>());
8105 }
8106
8107 if let Some(next_selection) = selections_iter.peek() {
8108 if next_selection.range().len() == selection.range().len() {
8109 let next_selected_text = buffer
8110 .text_for_range(next_selection.range())
8111 .collect::<String>();
8112 if Some(next_selected_text) != selected_text {
8113 same_text_selected = false;
8114 selected_text = None;
8115 }
8116 } else {
8117 same_text_selected = false;
8118 selected_text = None;
8119 }
8120 }
8121 }
8122 }
8123
8124 if only_carets {
8125 for selection in &mut selections {
8126 let word_range = movement::surrounding_word(
8127 &display_map,
8128 selection.start.to_display_point(&display_map),
8129 );
8130 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8131 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8132 selection.goal = SelectionGoal::None;
8133 selection.reversed = false;
8134 }
8135 if selections.len() == 1 {
8136 let selection = selections
8137 .last()
8138 .expect("ensured that there's only one selection");
8139 let query = buffer
8140 .text_for_range(selection.start..selection.end)
8141 .collect::<String>();
8142 let is_empty = query.is_empty();
8143 let select_state = SelectNextState {
8144 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8145 wordwise: true,
8146 done: is_empty,
8147 };
8148 self.select_prev_state = Some(select_state);
8149 } else {
8150 self.select_prev_state = None;
8151 }
8152
8153 self.unfold_ranges(
8154 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8155 false,
8156 true,
8157 cx,
8158 );
8159 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8160 s.select(selections);
8161 });
8162 } else if let Some(selected_text) = selected_text {
8163 self.select_prev_state = Some(SelectNextState {
8164 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8165 wordwise: false,
8166 done: false,
8167 });
8168 self.select_previous(action, cx)?;
8169 }
8170 }
8171 Ok(())
8172 }
8173
8174 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8175 let text_layout_details = &self.text_layout_details(cx);
8176 self.transact(cx, |this, cx| {
8177 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8178 let mut edits = Vec::new();
8179 let mut selection_edit_ranges = Vec::new();
8180 let mut last_toggled_row = None;
8181 let snapshot = this.buffer.read(cx).read(cx);
8182 let empty_str: Arc<str> = Arc::default();
8183 let mut suffixes_inserted = Vec::new();
8184
8185 fn comment_prefix_range(
8186 snapshot: &MultiBufferSnapshot,
8187 row: MultiBufferRow,
8188 comment_prefix: &str,
8189 comment_prefix_whitespace: &str,
8190 ) -> Range<Point> {
8191 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8192
8193 let mut line_bytes = snapshot
8194 .bytes_in_range(start..snapshot.max_point())
8195 .flatten()
8196 .copied();
8197
8198 // If this line currently begins with the line comment prefix, then record
8199 // the range containing the prefix.
8200 if line_bytes
8201 .by_ref()
8202 .take(comment_prefix.len())
8203 .eq(comment_prefix.bytes())
8204 {
8205 // Include any whitespace that matches the comment prefix.
8206 let matching_whitespace_len = line_bytes
8207 .zip(comment_prefix_whitespace.bytes())
8208 .take_while(|(a, b)| a == b)
8209 .count() as u32;
8210 let end = Point::new(
8211 start.row,
8212 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8213 );
8214 start..end
8215 } else {
8216 start..start
8217 }
8218 }
8219
8220 fn comment_suffix_range(
8221 snapshot: &MultiBufferSnapshot,
8222 row: MultiBufferRow,
8223 comment_suffix: &str,
8224 comment_suffix_has_leading_space: bool,
8225 ) -> Range<Point> {
8226 let end = Point::new(row.0, snapshot.line_len(row));
8227 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8228
8229 let mut line_end_bytes = snapshot
8230 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8231 .flatten()
8232 .copied();
8233
8234 let leading_space_len = if suffix_start_column > 0
8235 && line_end_bytes.next() == Some(b' ')
8236 && comment_suffix_has_leading_space
8237 {
8238 1
8239 } else {
8240 0
8241 };
8242
8243 // If this line currently begins with the line comment prefix, then record
8244 // the range containing the prefix.
8245 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8246 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8247 start..end
8248 } else {
8249 end..end
8250 }
8251 }
8252
8253 // TODO: Handle selections that cross excerpts
8254 for selection in &mut selections {
8255 let start_column = snapshot
8256 .indent_size_for_line(MultiBufferRow(selection.start.row))
8257 .len;
8258 let language = if let Some(language) =
8259 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8260 {
8261 language
8262 } else {
8263 continue;
8264 };
8265
8266 selection_edit_ranges.clear();
8267
8268 // If multiple selections contain a given row, avoid processing that
8269 // row more than once.
8270 let mut start_row = MultiBufferRow(selection.start.row);
8271 if last_toggled_row == Some(start_row) {
8272 start_row = start_row.next_row();
8273 }
8274 let end_row =
8275 if selection.end.row > selection.start.row && selection.end.column == 0 {
8276 MultiBufferRow(selection.end.row - 1)
8277 } else {
8278 MultiBufferRow(selection.end.row)
8279 };
8280 last_toggled_row = Some(end_row);
8281
8282 if start_row > end_row {
8283 continue;
8284 }
8285
8286 // If the language has line comments, toggle those.
8287 let full_comment_prefixes = language.line_comment_prefixes();
8288 if !full_comment_prefixes.is_empty() {
8289 let first_prefix = full_comment_prefixes
8290 .first()
8291 .expect("prefixes is non-empty");
8292 let prefix_trimmed_lengths = full_comment_prefixes
8293 .iter()
8294 .map(|p| p.trim_end_matches(' ').len())
8295 .collect::<SmallVec<[usize; 4]>>();
8296
8297 let mut all_selection_lines_are_comments = true;
8298
8299 for row in start_row.0..=end_row.0 {
8300 let row = MultiBufferRow(row);
8301 if start_row < end_row && snapshot.is_line_blank(row) {
8302 continue;
8303 }
8304
8305 let prefix_range = full_comment_prefixes
8306 .iter()
8307 .zip(prefix_trimmed_lengths.iter().copied())
8308 .map(|(prefix, trimmed_prefix_len)| {
8309 comment_prefix_range(
8310 snapshot.deref(),
8311 row,
8312 &prefix[..trimmed_prefix_len],
8313 &prefix[trimmed_prefix_len..],
8314 )
8315 })
8316 .max_by_key(|range| range.end.column - range.start.column)
8317 .expect("prefixes is non-empty");
8318
8319 if prefix_range.is_empty() {
8320 all_selection_lines_are_comments = false;
8321 }
8322
8323 selection_edit_ranges.push(prefix_range);
8324 }
8325
8326 if all_selection_lines_are_comments {
8327 edits.extend(
8328 selection_edit_ranges
8329 .iter()
8330 .cloned()
8331 .map(|range| (range, empty_str.clone())),
8332 );
8333 } else {
8334 let min_column = selection_edit_ranges
8335 .iter()
8336 .map(|range| range.start.column)
8337 .min()
8338 .unwrap_or(0);
8339 edits.extend(selection_edit_ranges.iter().map(|range| {
8340 let position = Point::new(range.start.row, min_column);
8341 (position..position, first_prefix.clone())
8342 }));
8343 }
8344 } else if let Some((full_comment_prefix, comment_suffix)) =
8345 language.block_comment_delimiters()
8346 {
8347 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8348 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8349 let prefix_range = comment_prefix_range(
8350 snapshot.deref(),
8351 start_row,
8352 comment_prefix,
8353 comment_prefix_whitespace,
8354 );
8355 let suffix_range = comment_suffix_range(
8356 snapshot.deref(),
8357 end_row,
8358 comment_suffix.trim_start_matches(' '),
8359 comment_suffix.starts_with(' '),
8360 );
8361
8362 if prefix_range.is_empty() || suffix_range.is_empty() {
8363 edits.push((
8364 prefix_range.start..prefix_range.start,
8365 full_comment_prefix.clone(),
8366 ));
8367 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8368 suffixes_inserted.push((end_row, comment_suffix.len()));
8369 } else {
8370 edits.push((prefix_range, empty_str.clone()));
8371 edits.push((suffix_range, empty_str.clone()));
8372 }
8373 } else {
8374 continue;
8375 }
8376 }
8377
8378 drop(snapshot);
8379 this.buffer.update(cx, |buffer, cx| {
8380 buffer.edit(edits, None, cx);
8381 });
8382
8383 // Adjust selections so that they end before any comment suffixes that
8384 // were inserted.
8385 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8386 let mut selections = this.selections.all::<Point>(cx);
8387 let snapshot = this.buffer.read(cx).read(cx);
8388 for selection in &mut selections {
8389 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8390 match row.cmp(&MultiBufferRow(selection.end.row)) {
8391 Ordering::Less => {
8392 suffixes_inserted.next();
8393 continue;
8394 }
8395 Ordering::Greater => break,
8396 Ordering::Equal => {
8397 if selection.end.column == snapshot.line_len(row) {
8398 if selection.is_empty() {
8399 selection.start.column -= suffix_len as u32;
8400 }
8401 selection.end.column -= suffix_len as u32;
8402 }
8403 break;
8404 }
8405 }
8406 }
8407 }
8408
8409 drop(snapshot);
8410 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8411
8412 let selections = this.selections.all::<Point>(cx);
8413 let selections_on_single_row = selections.windows(2).all(|selections| {
8414 selections[0].start.row == selections[1].start.row
8415 && selections[0].end.row == selections[1].end.row
8416 && selections[0].start.row == selections[0].end.row
8417 });
8418 let selections_selecting = selections
8419 .iter()
8420 .any(|selection| selection.start != selection.end);
8421 let advance_downwards = action.advance_downwards
8422 && selections_on_single_row
8423 && !selections_selecting
8424 && !matches!(this.mode, EditorMode::SingleLine { .. });
8425
8426 if advance_downwards {
8427 let snapshot = this.buffer.read(cx).snapshot(cx);
8428
8429 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8430 s.move_cursors_with(|display_snapshot, display_point, _| {
8431 let mut point = display_point.to_point(display_snapshot);
8432 point.row += 1;
8433 point = snapshot.clip_point(point, Bias::Left);
8434 let display_point = point.to_display_point(display_snapshot);
8435 let goal = SelectionGoal::HorizontalPosition(
8436 display_snapshot
8437 .x_for_display_point(display_point, &text_layout_details)
8438 .into(),
8439 );
8440 (display_point, goal)
8441 })
8442 });
8443 }
8444 });
8445 }
8446
8447 pub fn select_enclosing_symbol(
8448 &mut self,
8449 _: &SelectEnclosingSymbol,
8450 cx: &mut ViewContext<Self>,
8451 ) {
8452 let buffer = self.buffer.read(cx).snapshot(cx);
8453 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8454
8455 fn update_selection(
8456 selection: &Selection<usize>,
8457 buffer_snap: &MultiBufferSnapshot,
8458 ) -> Option<Selection<usize>> {
8459 let cursor = selection.head();
8460 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8461 for symbol in symbols.iter().rev() {
8462 let start = symbol.range.start.to_offset(&buffer_snap);
8463 let end = symbol.range.end.to_offset(&buffer_snap);
8464 let new_range = start..end;
8465 if start < selection.start || end > selection.end {
8466 return Some(Selection {
8467 id: selection.id,
8468 start: new_range.start,
8469 end: new_range.end,
8470 goal: SelectionGoal::None,
8471 reversed: selection.reversed,
8472 });
8473 }
8474 }
8475 None
8476 }
8477
8478 let mut selected_larger_symbol = false;
8479 let new_selections = old_selections
8480 .iter()
8481 .map(|selection| match update_selection(selection, &buffer) {
8482 Some(new_selection) => {
8483 if new_selection.range() != selection.range() {
8484 selected_larger_symbol = true;
8485 }
8486 new_selection
8487 }
8488 None => selection.clone(),
8489 })
8490 .collect::<Vec<_>>();
8491
8492 if selected_larger_symbol {
8493 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8494 s.select(new_selections);
8495 });
8496 }
8497 }
8498
8499 pub fn select_larger_syntax_node(
8500 &mut self,
8501 _: &SelectLargerSyntaxNode,
8502 cx: &mut ViewContext<Self>,
8503 ) {
8504 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8505 let buffer = self.buffer.read(cx).snapshot(cx);
8506 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8507
8508 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8509 let mut selected_larger_node = false;
8510 let new_selections = old_selections
8511 .iter()
8512 .map(|selection| {
8513 let old_range = selection.start..selection.end;
8514 let mut new_range = old_range.clone();
8515 while let Some(containing_range) =
8516 buffer.range_for_syntax_ancestor(new_range.clone())
8517 {
8518 new_range = containing_range;
8519 if !display_map.intersects_fold(new_range.start)
8520 && !display_map.intersects_fold(new_range.end)
8521 {
8522 break;
8523 }
8524 }
8525
8526 selected_larger_node |= new_range != old_range;
8527 Selection {
8528 id: selection.id,
8529 start: new_range.start,
8530 end: new_range.end,
8531 goal: SelectionGoal::None,
8532 reversed: selection.reversed,
8533 }
8534 })
8535 .collect::<Vec<_>>();
8536
8537 if selected_larger_node {
8538 stack.push(old_selections);
8539 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8540 s.select(new_selections);
8541 });
8542 }
8543 self.select_larger_syntax_node_stack = stack;
8544 }
8545
8546 pub fn select_smaller_syntax_node(
8547 &mut self,
8548 _: &SelectSmallerSyntaxNode,
8549 cx: &mut ViewContext<Self>,
8550 ) {
8551 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8552 if let Some(selections) = stack.pop() {
8553 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8554 s.select(selections.to_vec());
8555 });
8556 }
8557 self.select_larger_syntax_node_stack = stack;
8558 }
8559
8560 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8561 if !EditorSettings::get_global(cx).gutter.runnables {
8562 self.clear_tasks();
8563 return Task::ready(());
8564 }
8565 let project = self.project.clone();
8566 cx.spawn(|this, mut cx| async move {
8567 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8568 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8569 }) else {
8570 return;
8571 };
8572
8573 let Some(project) = project else {
8574 return;
8575 };
8576
8577 let hide_runnables = project
8578 .update(&mut cx, |project, cx| {
8579 // Do not display any test indicators in non-dev server remote projects.
8580 project.is_remote() && project.ssh_connection_string(cx).is_none()
8581 })
8582 .unwrap_or(true);
8583 if hide_runnables {
8584 return;
8585 }
8586 let new_rows =
8587 cx.background_executor()
8588 .spawn({
8589 let snapshot = display_snapshot.clone();
8590 async move {
8591 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8592 }
8593 })
8594 .await;
8595 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8596
8597 this.update(&mut cx, |this, _| {
8598 this.clear_tasks();
8599 for (key, value) in rows {
8600 this.insert_tasks(key, value);
8601 }
8602 })
8603 .ok();
8604 })
8605 }
8606 fn fetch_runnable_ranges(
8607 snapshot: &DisplaySnapshot,
8608 range: Range<Anchor>,
8609 ) -> Vec<language::RunnableRange> {
8610 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8611 }
8612
8613 fn runnable_rows(
8614 project: Model<Project>,
8615 snapshot: DisplaySnapshot,
8616 runnable_ranges: Vec<RunnableRange>,
8617 mut cx: AsyncWindowContext,
8618 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8619 runnable_ranges
8620 .into_iter()
8621 .filter_map(|mut runnable| {
8622 let tasks = cx
8623 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8624 .ok()?;
8625 if tasks.is_empty() {
8626 return None;
8627 }
8628
8629 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8630
8631 let row = snapshot
8632 .buffer_snapshot
8633 .buffer_line_for_row(MultiBufferRow(point.row))?
8634 .1
8635 .start
8636 .row;
8637
8638 let context_range =
8639 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8640 Some((
8641 (runnable.buffer_id, row),
8642 RunnableTasks {
8643 templates: tasks,
8644 offset: MultiBufferOffset(runnable.run_range.start),
8645 context_range,
8646 column: point.column,
8647 extra_variables: runnable.extra_captures,
8648 },
8649 ))
8650 })
8651 .collect()
8652 }
8653
8654 fn templates_with_tags(
8655 project: &Model<Project>,
8656 runnable: &mut Runnable,
8657 cx: &WindowContext<'_>,
8658 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8659 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8660 let (worktree_id, file) = project
8661 .buffer_for_id(runnable.buffer, cx)
8662 .and_then(|buffer| buffer.read(cx).file())
8663 .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
8664 .unzip();
8665
8666 (project.task_inventory().clone(), worktree_id, file)
8667 });
8668
8669 let inventory = inventory.read(cx);
8670 let tags = mem::take(&mut runnable.tags);
8671 let mut tags: Vec<_> = tags
8672 .into_iter()
8673 .flat_map(|tag| {
8674 let tag = tag.0.clone();
8675 inventory
8676 .list_tasks(
8677 file.clone(),
8678 Some(runnable.language.clone()),
8679 worktree_id,
8680 cx,
8681 )
8682 .into_iter()
8683 .filter(move |(_, template)| {
8684 template.tags.iter().any(|source_tag| source_tag == &tag)
8685 })
8686 })
8687 .sorted_by_key(|(kind, _)| kind.to_owned())
8688 .collect();
8689 if let Some((leading_tag_source, _)) = tags.first() {
8690 // Strongest source wins; if we have worktree tag binding, prefer that to
8691 // global and language bindings;
8692 // if we have a global binding, prefer that to language binding.
8693 let first_mismatch = tags
8694 .iter()
8695 .position(|(tag_source, _)| tag_source != leading_tag_source);
8696 if let Some(index) = first_mismatch {
8697 tags.truncate(index);
8698 }
8699 }
8700
8701 tags
8702 }
8703
8704 pub fn move_to_enclosing_bracket(
8705 &mut self,
8706 _: &MoveToEnclosingBracket,
8707 cx: &mut ViewContext<Self>,
8708 ) {
8709 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8710 s.move_offsets_with(|snapshot, selection| {
8711 let Some(enclosing_bracket_ranges) =
8712 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8713 else {
8714 return;
8715 };
8716
8717 let mut best_length = usize::MAX;
8718 let mut best_inside = false;
8719 let mut best_in_bracket_range = false;
8720 let mut best_destination = None;
8721 for (open, close) in enclosing_bracket_ranges {
8722 let close = close.to_inclusive();
8723 let length = close.end() - open.start;
8724 let inside = selection.start >= open.end && selection.end <= *close.start();
8725 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8726 || close.contains(&selection.head());
8727
8728 // If best is next to a bracket and current isn't, skip
8729 if !in_bracket_range && best_in_bracket_range {
8730 continue;
8731 }
8732
8733 // Prefer smaller lengths unless best is inside and current isn't
8734 if length > best_length && (best_inside || !inside) {
8735 continue;
8736 }
8737
8738 best_length = length;
8739 best_inside = inside;
8740 best_in_bracket_range = in_bracket_range;
8741 best_destination = Some(
8742 if close.contains(&selection.start) && close.contains(&selection.end) {
8743 if inside {
8744 open.end
8745 } else {
8746 open.start
8747 }
8748 } else {
8749 if inside {
8750 *close.start()
8751 } else {
8752 *close.end()
8753 }
8754 },
8755 );
8756 }
8757
8758 if let Some(destination) = best_destination {
8759 selection.collapse_to(destination, SelectionGoal::None);
8760 }
8761 })
8762 });
8763 }
8764
8765 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8766 self.end_selection(cx);
8767 self.selection_history.mode = SelectionHistoryMode::Undoing;
8768 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8769 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8770 self.select_next_state = entry.select_next_state;
8771 self.select_prev_state = entry.select_prev_state;
8772 self.add_selections_state = entry.add_selections_state;
8773 self.request_autoscroll(Autoscroll::newest(), cx);
8774 }
8775 self.selection_history.mode = SelectionHistoryMode::Normal;
8776 }
8777
8778 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8779 self.end_selection(cx);
8780 self.selection_history.mode = SelectionHistoryMode::Redoing;
8781 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8782 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8783 self.select_next_state = entry.select_next_state;
8784 self.select_prev_state = entry.select_prev_state;
8785 self.add_selections_state = entry.add_selections_state;
8786 self.request_autoscroll(Autoscroll::newest(), cx);
8787 }
8788 self.selection_history.mode = SelectionHistoryMode::Normal;
8789 }
8790
8791 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8792 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8793 }
8794
8795 pub fn expand_excerpts_down(
8796 &mut self,
8797 action: &ExpandExcerptsDown,
8798 cx: &mut ViewContext<Self>,
8799 ) {
8800 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8801 }
8802
8803 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8804 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8805 }
8806
8807 pub fn expand_excerpts_for_direction(
8808 &mut self,
8809 lines: u32,
8810 direction: ExpandExcerptDirection,
8811 cx: &mut ViewContext<Self>,
8812 ) {
8813 let selections = self.selections.disjoint_anchors();
8814
8815 let lines = if lines == 0 {
8816 EditorSettings::get_global(cx).expand_excerpt_lines
8817 } else {
8818 lines
8819 };
8820
8821 self.buffer.update(cx, |buffer, cx| {
8822 buffer.expand_excerpts(
8823 selections
8824 .into_iter()
8825 .map(|selection| selection.head().excerpt_id)
8826 .dedup(),
8827 lines,
8828 direction,
8829 cx,
8830 )
8831 })
8832 }
8833
8834 pub fn expand_excerpt(
8835 &mut self,
8836 excerpt: ExcerptId,
8837 direction: ExpandExcerptDirection,
8838 cx: &mut ViewContext<Self>,
8839 ) {
8840 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8841 self.buffer.update(cx, |buffer, cx| {
8842 buffer.expand_excerpts([excerpt], lines, direction, cx)
8843 })
8844 }
8845
8846 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8847 self.go_to_diagnostic_impl(Direction::Next, cx)
8848 }
8849
8850 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8851 self.go_to_diagnostic_impl(Direction::Prev, cx)
8852 }
8853
8854 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8855 let buffer = self.buffer.read(cx).snapshot(cx);
8856 let selection = self.selections.newest::<usize>(cx);
8857
8858 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8859 if direction == Direction::Next {
8860 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8861 let (group_id, jump_to) = popover.activation_info();
8862 if self.activate_diagnostics(group_id, cx) {
8863 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8864 let mut new_selection = s.newest_anchor().clone();
8865 new_selection.collapse_to(jump_to, SelectionGoal::None);
8866 s.select_anchors(vec![new_selection.clone()]);
8867 });
8868 }
8869 return;
8870 }
8871 }
8872
8873 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8874 active_diagnostics
8875 .primary_range
8876 .to_offset(&buffer)
8877 .to_inclusive()
8878 });
8879 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8880 if active_primary_range.contains(&selection.head()) {
8881 *active_primary_range.start()
8882 } else {
8883 selection.head()
8884 }
8885 } else {
8886 selection.head()
8887 };
8888 let snapshot = self.snapshot(cx);
8889 loop {
8890 let diagnostics = if direction == Direction::Prev {
8891 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8892 } else {
8893 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8894 }
8895 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8896 let group = diagnostics
8897 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8898 // be sorted in a stable way
8899 // skip until we are at current active diagnostic, if it exists
8900 .skip_while(|entry| {
8901 (match direction {
8902 Direction::Prev => entry.range.start >= search_start,
8903 Direction::Next => entry.range.start <= search_start,
8904 }) && self
8905 .active_diagnostics
8906 .as_ref()
8907 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8908 })
8909 .find_map(|entry| {
8910 if entry.diagnostic.is_primary
8911 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8912 && !entry.range.is_empty()
8913 // if we match with the active diagnostic, skip it
8914 && Some(entry.diagnostic.group_id)
8915 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8916 {
8917 Some((entry.range, entry.diagnostic.group_id))
8918 } else {
8919 None
8920 }
8921 });
8922
8923 if let Some((primary_range, group_id)) = group {
8924 if self.activate_diagnostics(group_id, cx) {
8925 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8926 s.select(vec![Selection {
8927 id: selection.id,
8928 start: primary_range.start,
8929 end: primary_range.start,
8930 reversed: false,
8931 goal: SelectionGoal::None,
8932 }]);
8933 });
8934 }
8935 break;
8936 } else {
8937 // Cycle around to the start of the buffer, potentially moving back to the start of
8938 // the currently active diagnostic.
8939 active_primary_range.take();
8940 if direction == Direction::Prev {
8941 if search_start == buffer.len() {
8942 break;
8943 } else {
8944 search_start = buffer.len();
8945 }
8946 } else if search_start == 0 {
8947 break;
8948 } else {
8949 search_start = 0;
8950 }
8951 }
8952 }
8953 }
8954
8955 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
8956 let snapshot = self
8957 .display_map
8958 .update(cx, |display_map, cx| display_map.snapshot(cx));
8959 let selection = self.selections.newest::<Point>(cx);
8960
8961 if !self.seek_in_direction(
8962 &snapshot,
8963 selection.head(),
8964 false,
8965 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8966 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
8967 ),
8968 cx,
8969 ) {
8970 let wrapped_point = Point::zero();
8971 self.seek_in_direction(
8972 &snapshot,
8973 wrapped_point,
8974 true,
8975 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8976 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
8977 ),
8978 cx,
8979 );
8980 }
8981 }
8982
8983 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
8984 let snapshot = self
8985 .display_map
8986 .update(cx, |display_map, cx| display_map.snapshot(cx));
8987 let selection = self.selections.newest::<Point>(cx);
8988
8989 if !self.seek_in_direction(
8990 &snapshot,
8991 selection.head(),
8992 false,
8993 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8994 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
8995 ),
8996 cx,
8997 ) {
8998 let wrapped_point = snapshot.buffer_snapshot.max_point();
8999 self.seek_in_direction(
9000 &snapshot,
9001 wrapped_point,
9002 true,
9003 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9004 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9005 ),
9006 cx,
9007 );
9008 }
9009 }
9010
9011 fn seek_in_direction(
9012 &mut self,
9013 snapshot: &DisplaySnapshot,
9014 initial_point: Point,
9015 is_wrapped: bool,
9016 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
9017 cx: &mut ViewContext<Editor>,
9018 ) -> bool {
9019 let display_point = initial_point.to_display_point(snapshot);
9020 let mut hunks = hunks
9021 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
9022 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9023 .dedup();
9024
9025 if let Some(hunk) = hunks.next() {
9026 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9027 let row = hunk.start_display_row();
9028 let point = DisplayPoint::new(row, 0);
9029 s.select_display_ranges([point..point]);
9030 });
9031
9032 true
9033 } else {
9034 false
9035 }
9036 }
9037
9038 pub fn go_to_definition(
9039 &mut self,
9040 _: &GoToDefinition,
9041 cx: &mut ViewContext<Self>,
9042 ) -> Task<Result<Navigated>> {
9043 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9044 let references = self.find_all_references(&FindAllReferences, cx);
9045 cx.background_executor().spawn(async move {
9046 if definition.await? == Navigated::Yes {
9047 return Ok(Navigated::Yes);
9048 }
9049 if let Some(references) = references {
9050 if references.await? == Navigated::Yes {
9051 return Ok(Navigated::Yes);
9052 }
9053 }
9054
9055 Ok(Navigated::No)
9056 })
9057 }
9058
9059 pub fn go_to_declaration(
9060 &mut self,
9061 _: &GoToDeclaration,
9062 cx: &mut ViewContext<Self>,
9063 ) -> Task<Result<Navigated>> {
9064 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9065 }
9066
9067 pub fn go_to_declaration_split(
9068 &mut self,
9069 _: &GoToDeclaration,
9070 cx: &mut ViewContext<Self>,
9071 ) -> Task<Result<Navigated>> {
9072 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9073 }
9074
9075 pub fn go_to_implementation(
9076 &mut self,
9077 _: &GoToImplementation,
9078 cx: &mut ViewContext<Self>,
9079 ) -> Task<Result<Navigated>> {
9080 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9081 }
9082
9083 pub fn go_to_implementation_split(
9084 &mut self,
9085 _: &GoToImplementationSplit,
9086 cx: &mut ViewContext<Self>,
9087 ) -> Task<Result<Navigated>> {
9088 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9089 }
9090
9091 pub fn go_to_type_definition(
9092 &mut self,
9093 _: &GoToTypeDefinition,
9094 cx: &mut ViewContext<Self>,
9095 ) -> Task<Result<Navigated>> {
9096 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9097 }
9098
9099 pub fn go_to_definition_split(
9100 &mut self,
9101 _: &GoToDefinitionSplit,
9102 cx: &mut ViewContext<Self>,
9103 ) -> Task<Result<Navigated>> {
9104 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9105 }
9106
9107 pub fn go_to_type_definition_split(
9108 &mut self,
9109 _: &GoToTypeDefinitionSplit,
9110 cx: &mut ViewContext<Self>,
9111 ) -> Task<Result<Navigated>> {
9112 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9113 }
9114
9115 fn go_to_definition_of_kind(
9116 &mut self,
9117 kind: GotoDefinitionKind,
9118 split: bool,
9119 cx: &mut ViewContext<Self>,
9120 ) -> Task<Result<Navigated>> {
9121 let Some(workspace) = self.workspace() else {
9122 return Task::ready(Ok(Navigated::No));
9123 };
9124 let buffer = self.buffer.read(cx);
9125 let head = self.selections.newest::<usize>(cx).head();
9126 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9127 text_anchor
9128 } else {
9129 return Task::ready(Ok(Navigated::No));
9130 };
9131
9132 let project = workspace.read(cx).project().clone();
9133 let definitions = project.update(cx, |project, cx| match kind {
9134 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9135 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9136 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9137 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9138 });
9139
9140 cx.spawn(|editor, mut cx| async move {
9141 let definitions = definitions.await?;
9142 let navigated = editor
9143 .update(&mut cx, |editor, cx| {
9144 editor.navigate_to_hover_links(
9145 Some(kind),
9146 definitions
9147 .into_iter()
9148 .filter(|location| {
9149 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9150 })
9151 .map(HoverLink::Text)
9152 .collect::<Vec<_>>(),
9153 split,
9154 cx,
9155 )
9156 })?
9157 .await?;
9158 anyhow::Ok(navigated)
9159 })
9160 }
9161
9162 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9163 let position = self.selections.newest_anchor().head();
9164 let Some((buffer, buffer_position)) =
9165 self.buffer.read(cx).text_anchor_for_position(position, cx)
9166 else {
9167 return;
9168 };
9169
9170 cx.spawn(|editor, mut cx| async move {
9171 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9172 editor.update(&mut cx, |_, cx| {
9173 cx.open_url(&url);
9174 })
9175 } else {
9176 Ok(())
9177 }
9178 })
9179 .detach();
9180 }
9181
9182 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9183 let Some(workspace) = self.workspace() else {
9184 return;
9185 };
9186
9187 let position = self.selections.newest_anchor().head();
9188
9189 let Some((buffer, buffer_position)) =
9190 self.buffer.read(cx).text_anchor_for_position(position, cx)
9191 else {
9192 return;
9193 };
9194
9195 let Some(project) = self.project.clone() else {
9196 return;
9197 };
9198
9199 cx.spawn(|_, mut cx| async move {
9200 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9201
9202 if let Some((_, path)) = result {
9203 workspace
9204 .update(&mut cx, |workspace, cx| {
9205 workspace.open_resolved_path(path, cx)
9206 })?
9207 .await?;
9208 }
9209 anyhow::Ok(())
9210 })
9211 .detach();
9212 }
9213
9214 pub(crate) fn navigate_to_hover_links(
9215 &mut self,
9216 kind: Option<GotoDefinitionKind>,
9217 mut definitions: Vec<HoverLink>,
9218 split: bool,
9219 cx: &mut ViewContext<Editor>,
9220 ) -> Task<Result<Navigated>> {
9221 // If there is one definition, just open it directly
9222 if definitions.len() == 1 {
9223 let definition = definitions.pop().unwrap();
9224
9225 enum TargetTaskResult {
9226 Location(Option<Location>),
9227 AlreadyNavigated,
9228 }
9229
9230 let target_task = match definition {
9231 HoverLink::Text(link) => {
9232 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9233 }
9234 HoverLink::InlayHint(lsp_location, server_id) => {
9235 let computation = self.compute_target_location(lsp_location, server_id, cx);
9236 cx.background_executor().spawn(async move {
9237 let location = computation.await?;
9238 Ok(TargetTaskResult::Location(location))
9239 })
9240 }
9241 HoverLink::Url(url) => {
9242 cx.open_url(&url);
9243 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9244 }
9245 HoverLink::File(path) => {
9246 if let Some(workspace) = self.workspace() {
9247 cx.spawn(|_, mut cx| async move {
9248 workspace
9249 .update(&mut cx, |workspace, cx| {
9250 workspace.open_resolved_path(path, cx)
9251 })?
9252 .await
9253 .map(|_| TargetTaskResult::AlreadyNavigated)
9254 })
9255 } else {
9256 Task::ready(Ok(TargetTaskResult::Location(None)))
9257 }
9258 }
9259 };
9260 cx.spawn(|editor, mut cx| async move {
9261 let target = match target_task.await.context("target resolution task")? {
9262 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9263 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9264 TargetTaskResult::Location(Some(target)) => target,
9265 };
9266
9267 editor.update(&mut cx, |editor, cx| {
9268 let Some(workspace) = editor.workspace() else {
9269 return Navigated::No;
9270 };
9271 let pane = workspace.read(cx).active_pane().clone();
9272
9273 let range = target.range.to_offset(target.buffer.read(cx));
9274 let range = editor.range_for_match(&range);
9275
9276 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9277 let buffer = target.buffer.read(cx);
9278 let range = check_multiline_range(buffer, range);
9279 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9280 s.select_ranges([range]);
9281 });
9282 } else {
9283 cx.window_context().defer(move |cx| {
9284 let target_editor: View<Self> =
9285 workspace.update(cx, |workspace, cx| {
9286 let pane = if split {
9287 workspace.adjacent_pane(cx)
9288 } else {
9289 workspace.active_pane().clone()
9290 };
9291
9292 workspace.open_project_item(
9293 pane,
9294 target.buffer.clone(),
9295 true,
9296 true,
9297 cx,
9298 )
9299 });
9300 target_editor.update(cx, |target_editor, cx| {
9301 // When selecting a definition in a different buffer, disable the nav history
9302 // to avoid creating a history entry at the previous cursor location.
9303 pane.update(cx, |pane, _| pane.disable_history());
9304 let buffer = target.buffer.read(cx);
9305 let range = check_multiline_range(buffer, range);
9306 target_editor.change_selections(
9307 Some(Autoscroll::focused()),
9308 cx,
9309 |s| {
9310 s.select_ranges([range]);
9311 },
9312 );
9313 pane.update(cx, |pane, _| pane.enable_history());
9314 });
9315 });
9316 }
9317 Navigated::Yes
9318 })
9319 })
9320 } else if !definitions.is_empty() {
9321 let replica_id = self.replica_id(cx);
9322 cx.spawn(|editor, mut cx| async move {
9323 let (title, location_tasks, workspace) = editor
9324 .update(&mut cx, |editor, cx| {
9325 let tab_kind = match kind {
9326 Some(GotoDefinitionKind::Implementation) => "Implementations",
9327 _ => "Definitions",
9328 };
9329 let title = definitions
9330 .iter()
9331 .find_map(|definition| match definition {
9332 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9333 let buffer = origin.buffer.read(cx);
9334 format!(
9335 "{} for {}",
9336 tab_kind,
9337 buffer
9338 .text_for_range(origin.range.clone())
9339 .collect::<String>()
9340 )
9341 }),
9342 HoverLink::InlayHint(_, _) => None,
9343 HoverLink::Url(_) => None,
9344 HoverLink::File(_) => None,
9345 })
9346 .unwrap_or(tab_kind.to_string());
9347 let location_tasks = definitions
9348 .into_iter()
9349 .map(|definition| match definition {
9350 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9351 HoverLink::InlayHint(lsp_location, server_id) => {
9352 editor.compute_target_location(lsp_location, server_id, cx)
9353 }
9354 HoverLink::Url(_) => Task::ready(Ok(None)),
9355 HoverLink::File(_) => Task::ready(Ok(None)),
9356 })
9357 .collect::<Vec<_>>();
9358 (title, location_tasks, editor.workspace().clone())
9359 })
9360 .context("location tasks preparation")?;
9361
9362 let locations = futures::future::join_all(location_tasks)
9363 .await
9364 .into_iter()
9365 .filter_map(|location| location.transpose())
9366 .collect::<Result<_>>()
9367 .context("location tasks")?;
9368
9369 let Some(workspace) = workspace else {
9370 return Ok(Navigated::No);
9371 };
9372 let opened = workspace
9373 .update(&mut cx, |workspace, cx| {
9374 Self::open_locations_in_multibuffer(
9375 workspace, locations, replica_id, title, split, cx,
9376 )
9377 })
9378 .ok();
9379
9380 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9381 })
9382 } else {
9383 Task::ready(Ok(Navigated::No))
9384 }
9385 }
9386
9387 fn compute_target_location(
9388 &self,
9389 lsp_location: lsp::Location,
9390 server_id: LanguageServerId,
9391 cx: &mut ViewContext<Editor>,
9392 ) -> Task<anyhow::Result<Option<Location>>> {
9393 let Some(project) = self.project.clone() else {
9394 return Task::Ready(Some(Ok(None)));
9395 };
9396
9397 cx.spawn(move |editor, mut cx| async move {
9398 let location_task = editor.update(&mut cx, |editor, cx| {
9399 project.update(cx, |project, cx| {
9400 let language_server_name =
9401 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9402 project
9403 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9404 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9405 });
9406 language_server_name.map(|language_server_name| {
9407 project.open_local_buffer_via_lsp(
9408 lsp_location.uri.clone(),
9409 server_id,
9410 language_server_name,
9411 cx,
9412 )
9413 })
9414 })
9415 })?;
9416 let location = match location_task {
9417 Some(task) => Some({
9418 let target_buffer_handle = task.await.context("open local buffer")?;
9419 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9420 let target_start = target_buffer
9421 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9422 let target_end = target_buffer
9423 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9424 target_buffer.anchor_after(target_start)
9425 ..target_buffer.anchor_before(target_end)
9426 })?;
9427 Location {
9428 buffer: target_buffer_handle,
9429 range,
9430 }
9431 }),
9432 None => None,
9433 };
9434 Ok(location)
9435 })
9436 }
9437
9438 pub fn find_all_references(
9439 &mut self,
9440 _: &FindAllReferences,
9441 cx: &mut ViewContext<Self>,
9442 ) -> Option<Task<Result<Navigated>>> {
9443 let multi_buffer = self.buffer.read(cx);
9444 let selection = self.selections.newest::<usize>(cx);
9445 let head = selection.head();
9446
9447 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9448 let head_anchor = multi_buffer_snapshot.anchor_at(
9449 head,
9450 if head < selection.tail() {
9451 Bias::Right
9452 } else {
9453 Bias::Left
9454 },
9455 );
9456
9457 match self
9458 .find_all_references_task_sources
9459 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9460 {
9461 Ok(_) => {
9462 log::info!(
9463 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9464 );
9465 return None;
9466 }
9467 Err(i) => {
9468 self.find_all_references_task_sources.insert(i, head_anchor);
9469 }
9470 }
9471
9472 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9473 let replica_id = self.replica_id(cx);
9474 let workspace = self.workspace()?;
9475 let project = workspace.read(cx).project().clone();
9476 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9477 Some(cx.spawn(|editor, mut cx| async move {
9478 let _cleanup = defer({
9479 let mut cx = cx.clone();
9480 move || {
9481 let _ = editor.update(&mut cx, |editor, _| {
9482 if let Ok(i) =
9483 editor
9484 .find_all_references_task_sources
9485 .binary_search_by(|anchor| {
9486 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9487 })
9488 {
9489 editor.find_all_references_task_sources.remove(i);
9490 }
9491 });
9492 }
9493 });
9494
9495 let locations = references.await?;
9496 if locations.is_empty() {
9497 return anyhow::Ok(Navigated::No);
9498 }
9499
9500 workspace.update(&mut cx, |workspace, cx| {
9501 let title = locations
9502 .first()
9503 .as_ref()
9504 .map(|location| {
9505 let buffer = location.buffer.read(cx);
9506 format!(
9507 "References to `{}`",
9508 buffer
9509 .text_for_range(location.range.clone())
9510 .collect::<String>()
9511 )
9512 })
9513 .unwrap();
9514 Self::open_locations_in_multibuffer(
9515 workspace, locations, replica_id, title, false, cx,
9516 );
9517 Navigated::Yes
9518 })
9519 }))
9520 }
9521
9522 /// Opens a multibuffer with the given project locations in it
9523 pub fn open_locations_in_multibuffer(
9524 workspace: &mut Workspace,
9525 mut locations: Vec<Location>,
9526 replica_id: ReplicaId,
9527 title: String,
9528 split: bool,
9529 cx: &mut ViewContext<Workspace>,
9530 ) {
9531 // If there are multiple definitions, open them in a multibuffer
9532 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9533 let mut locations = locations.into_iter().peekable();
9534 let mut ranges_to_highlight = Vec::new();
9535 let capability = workspace.project().read(cx).capability();
9536
9537 let excerpt_buffer = cx.new_model(|cx| {
9538 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9539 while let Some(location) = locations.next() {
9540 let buffer = location.buffer.read(cx);
9541 let mut ranges_for_buffer = Vec::new();
9542 let range = location.range.to_offset(buffer);
9543 ranges_for_buffer.push(range.clone());
9544
9545 while let Some(next_location) = locations.peek() {
9546 if next_location.buffer == location.buffer {
9547 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9548 locations.next();
9549 } else {
9550 break;
9551 }
9552 }
9553
9554 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9555 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9556 location.buffer.clone(),
9557 ranges_for_buffer,
9558 DEFAULT_MULTIBUFFER_CONTEXT,
9559 cx,
9560 ))
9561 }
9562
9563 multibuffer.with_title(title)
9564 });
9565
9566 let editor = cx.new_view(|cx| {
9567 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9568 });
9569 editor.update(cx, |editor, cx| {
9570 if let Some(first_range) = ranges_to_highlight.first() {
9571 editor.change_selections(None, cx, |selections| {
9572 selections.clear_disjoint();
9573 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9574 });
9575 }
9576 editor.highlight_background::<Self>(
9577 &ranges_to_highlight,
9578 |theme| theme.editor_highlighted_line_background,
9579 cx,
9580 );
9581 });
9582
9583 let item = Box::new(editor);
9584 let item_id = item.item_id();
9585
9586 if split {
9587 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9588 } else {
9589 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9590 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9591 pane.close_current_preview_item(cx)
9592 } else {
9593 None
9594 }
9595 });
9596 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9597 }
9598 workspace.active_pane().update(cx, |pane, cx| {
9599 pane.set_preview_item_id(Some(item_id), cx);
9600 });
9601 }
9602
9603 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9604 use language::ToOffset as _;
9605
9606 let project = self.project.clone()?;
9607 let selection = self.selections.newest_anchor().clone();
9608 let (cursor_buffer, cursor_buffer_position) = self
9609 .buffer
9610 .read(cx)
9611 .text_anchor_for_position(selection.head(), cx)?;
9612 let (tail_buffer, cursor_buffer_position_end) = self
9613 .buffer
9614 .read(cx)
9615 .text_anchor_for_position(selection.tail(), cx)?;
9616 if tail_buffer != cursor_buffer {
9617 return None;
9618 }
9619
9620 let snapshot = cursor_buffer.read(cx).snapshot();
9621 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9622 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9623 let prepare_rename = project.update(cx, |project, cx| {
9624 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9625 });
9626 drop(snapshot);
9627
9628 Some(cx.spawn(|this, mut cx| async move {
9629 let rename_range = if let Some(range) = prepare_rename.await? {
9630 Some(range)
9631 } else {
9632 this.update(&mut cx, |this, cx| {
9633 let buffer = this.buffer.read(cx).snapshot(cx);
9634 let mut buffer_highlights = this
9635 .document_highlights_for_position(selection.head(), &buffer)
9636 .filter(|highlight| {
9637 highlight.start.excerpt_id == selection.head().excerpt_id
9638 && highlight.end.excerpt_id == selection.head().excerpt_id
9639 });
9640 buffer_highlights
9641 .next()
9642 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9643 })?
9644 };
9645 if let Some(rename_range) = rename_range {
9646 this.update(&mut cx, |this, cx| {
9647 let snapshot = cursor_buffer.read(cx).snapshot();
9648 let rename_buffer_range = rename_range.to_offset(&snapshot);
9649 let cursor_offset_in_rename_range =
9650 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9651 let cursor_offset_in_rename_range_end =
9652 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9653
9654 this.take_rename(false, cx);
9655 let buffer = this.buffer.read(cx).read(cx);
9656 let cursor_offset = selection.head().to_offset(&buffer);
9657 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9658 let rename_end = rename_start + rename_buffer_range.len();
9659 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9660 let mut old_highlight_id = None;
9661 let old_name: Arc<str> = buffer
9662 .chunks(rename_start..rename_end, true)
9663 .map(|chunk| {
9664 if old_highlight_id.is_none() {
9665 old_highlight_id = chunk.syntax_highlight_id;
9666 }
9667 chunk.text
9668 })
9669 .collect::<String>()
9670 .into();
9671
9672 drop(buffer);
9673
9674 // Position the selection in the rename editor so that it matches the current selection.
9675 this.show_local_selections = false;
9676 let rename_editor = cx.new_view(|cx| {
9677 let mut editor = Editor::single_line(cx);
9678 editor.buffer.update(cx, |buffer, cx| {
9679 buffer.edit([(0..0, old_name.clone())], None, cx)
9680 });
9681 let rename_selection_range = match cursor_offset_in_rename_range
9682 .cmp(&cursor_offset_in_rename_range_end)
9683 {
9684 Ordering::Equal => {
9685 editor.select_all(&SelectAll, cx);
9686 return editor;
9687 }
9688 Ordering::Less => {
9689 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9690 }
9691 Ordering::Greater => {
9692 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9693 }
9694 };
9695 if rename_selection_range.end > old_name.len() {
9696 editor.select_all(&SelectAll, cx);
9697 } else {
9698 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9699 s.select_ranges([rename_selection_range]);
9700 });
9701 }
9702 editor
9703 });
9704 cx.subscribe(&rename_editor, |_, _, e, cx| match e {
9705 EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
9706 _ => {}
9707 })
9708 .detach();
9709
9710 let write_highlights =
9711 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9712 let read_highlights =
9713 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9714 let ranges = write_highlights
9715 .iter()
9716 .flat_map(|(_, ranges)| ranges.iter())
9717 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9718 .cloned()
9719 .collect();
9720
9721 this.highlight_text::<Rename>(
9722 ranges,
9723 HighlightStyle {
9724 fade_out: Some(0.6),
9725 ..Default::default()
9726 },
9727 cx,
9728 );
9729 let rename_focus_handle = rename_editor.focus_handle(cx);
9730 cx.focus(&rename_focus_handle);
9731 let block_id = this.insert_blocks(
9732 [BlockProperties {
9733 style: BlockStyle::Flex,
9734 position: range.start,
9735 height: 1,
9736 render: Box::new({
9737 let rename_editor = rename_editor.clone();
9738 move |cx: &mut BlockContext| {
9739 let mut text_style = cx.editor_style.text.clone();
9740 if let Some(highlight_style) = old_highlight_id
9741 .and_then(|h| h.style(&cx.editor_style.syntax))
9742 {
9743 text_style = text_style.highlight(highlight_style);
9744 }
9745 div()
9746 .pl(cx.anchor_x)
9747 .child(EditorElement::new(
9748 &rename_editor,
9749 EditorStyle {
9750 background: cx.theme().system().transparent,
9751 local_player: cx.editor_style.local_player,
9752 text: text_style,
9753 scrollbar_width: cx.editor_style.scrollbar_width,
9754 syntax: cx.editor_style.syntax.clone(),
9755 status: cx.editor_style.status.clone(),
9756 inlay_hints_style: HighlightStyle {
9757 color: Some(cx.theme().status().hint),
9758 font_weight: Some(FontWeight::BOLD),
9759 ..HighlightStyle::default()
9760 },
9761 suggestions_style: HighlightStyle {
9762 color: Some(cx.theme().status().predictive),
9763 ..HighlightStyle::default()
9764 },
9765 ..EditorStyle::default()
9766 },
9767 ))
9768 .into_any_element()
9769 }
9770 }),
9771 disposition: BlockDisposition::Below,
9772 priority: 0,
9773 }],
9774 Some(Autoscroll::fit()),
9775 cx,
9776 )[0];
9777 this.pending_rename = Some(RenameState {
9778 range,
9779 old_name,
9780 editor: rename_editor,
9781 block_id,
9782 });
9783 })?;
9784 }
9785
9786 Ok(())
9787 }))
9788 }
9789
9790 pub fn confirm_rename(
9791 &mut self,
9792 _: &ConfirmRename,
9793 cx: &mut ViewContext<Self>,
9794 ) -> Option<Task<Result<()>>> {
9795 let rename = self.take_rename(false, cx)?;
9796 let workspace = self.workspace()?;
9797 let (start_buffer, start) = self
9798 .buffer
9799 .read(cx)
9800 .text_anchor_for_position(rename.range.start, cx)?;
9801 let (end_buffer, end) = self
9802 .buffer
9803 .read(cx)
9804 .text_anchor_for_position(rename.range.end, cx)?;
9805 if start_buffer != end_buffer {
9806 return None;
9807 }
9808
9809 let buffer = start_buffer;
9810 let range = start..end;
9811 let old_name = rename.old_name;
9812 let new_name = rename.editor.read(cx).text(cx);
9813
9814 let rename = workspace
9815 .read(cx)
9816 .project()
9817 .clone()
9818 .update(cx, |project, cx| {
9819 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9820 });
9821 let workspace = workspace.downgrade();
9822
9823 Some(cx.spawn(|editor, mut cx| async move {
9824 let project_transaction = rename.await?;
9825 Self::open_project_transaction(
9826 &editor,
9827 workspace,
9828 project_transaction,
9829 format!("Rename: {} → {}", old_name, new_name),
9830 cx.clone(),
9831 )
9832 .await?;
9833
9834 editor.update(&mut cx, |editor, cx| {
9835 editor.refresh_document_highlights(cx);
9836 })?;
9837 Ok(())
9838 }))
9839 }
9840
9841 fn take_rename(
9842 &mut self,
9843 moving_cursor: bool,
9844 cx: &mut ViewContext<Self>,
9845 ) -> Option<RenameState> {
9846 let rename = self.pending_rename.take()?;
9847 if rename.editor.focus_handle(cx).is_focused(cx) {
9848 cx.focus(&self.focus_handle);
9849 }
9850
9851 self.remove_blocks(
9852 [rename.block_id].into_iter().collect(),
9853 Some(Autoscroll::fit()),
9854 cx,
9855 );
9856 self.clear_highlights::<Rename>(cx);
9857 self.show_local_selections = true;
9858
9859 if moving_cursor {
9860 let rename_editor = rename.editor.read(cx);
9861 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9862
9863 // Update the selection to match the position of the selection inside
9864 // the rename editor.
9865 let snapshot = self.buffer.read(cx).read(cx);
9866 let rename_range = rename.range.to_offset(&snapshot);
9867 let cursor_in_editor = snapshot
9868 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9869 .min(rename_range.end);
9870 drop(snapshot);
9871
9872 self.change_selections(None, cx, |s| {
9873 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9874 });
9875 } else {
9876 self.refresh_document_highlights(cx);
9877 }
9878
9879 Some(rename)
9880 }
9881
9882 pub fn pending_rename(&self) -> Option<&RenameState> {
9883 self.pending_rename.as_ref()
9884 }
9885
9886 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9887 let project = match &self.project {
9888 Some(project) => project.clone(),
9889 None => return None,
9890 };
9891
9892 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9893 }
9894
9895 fn perform_format(
9896 &mut self,
9897 project: Model<Project>,
9898 trigger: FormatTrigger,
9899 cx: &mut ViewContext<Self>,
9900 ) -> Task<Result<()>> {
9901 let buffer = self.buffer().clone();
9902 let mut buffers = buffer.read(cx).all_buffers();
9903 if trigger == FormatTrigger::Save {
9904 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9905 }
9906
9907 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9908 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9909
9910 cx.spawn(|_, mut cx| async move {
9911 let transaction = futures::select_biased! {
9912 () = timeout => {
9913 log::warn!("timed out waiting for formatting");
9914 None
9915 }
9916 transaction = format.log_err().fuse() => transaction,
9917 };
9918
9919 buffer
9920 .update(&mut cx, |buffer, cx| {
9921 if let Some(transaction) = transaction {
9922 if !buffer.is_singleton() {
9923 buffer.push_transaction(&transaction.0, cx);
9924 }
9925 }
9926
9927 cx.notify();
9928 })
9929 .ok();
9930
9931 Ok(())
9932 })
9933 }
9934
9935 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
9936 if let Some(project) = self.project.clone() {
9937 self.buffer.update(cx, |multi_buffer, cx| {
9938 project.update(cx, |project, cx| {
9939 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
9940 });
9941 })
9942 }
9943 }
9944
9945 fn cancel_language_server_work(
9946 &mut self,
9947 _: &CancelLanguageServerWork,
9948 cx: &mut ViewContext<Self>,
9949 ) {
9950 if let Some(project) = self.project.clone() {
9951 self.buffer.update(cx, |multi_buffer, cx| {
9952 project.update(cx, |project, cx| {
9953 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
9954 });
9955 })
9956 }
9957 }
9958
9959 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
9960 cx.show_character_palette();
9961 }
9962
9963 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
9964 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
9965 let buffer = self.buffer.read(cx).snapshot(cx);
9966 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
9967 let is_valid = buffer
9968 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
9969 .any(|entry| {
9970 entry.diagnostic.is_primary
9971 && !entry.range.is_empty()
9972 && entry.range.start == primary_range_start
9973 && entry.diagnostic.message == active_diagnostics.primary_message
9974 });
9975
9976 if is_valid != active_diagnostics.is_valid {
9977 active_diagnostics.is_valid = is_valid;
9978 let mut new_styles = HashMap::default();
9979 for (block_id, diagnostic) in &active_diagnostics.blocks {
9980 new_styles.insert(
9981 *block_id,
9982 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
9983 );
9984 }
9985 self.display_map.update(cx, |display_map, _cx| {
9986 display_map.replace_blocks(new_styles)
9987 });
9988 }
9989 }
9990 }
9991
9992 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
9993 self.dismiss_diagnostics(cx);
9994 let snapshot = self.snapshot(cx);
9995 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
9996 let buffer = self.buffer.read(cx).snapshot(cx);
9997
9998 let mut primary_range = None;
9999 let mut primary_message = None;
10000 let mut group_end = Point::zero();
10001 let diagnostic_group = buffer
10002 .diagnostic_group::<MultiBufferPoint>(group_id)
10003 .filter_map(|entry| {
10004 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10005 && (entry.range.start.row == entry.range.end.row
10006 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10007 {
10008 return None;
10009 }
10010 if entry.range.end > group_end {
10011 group_end = entry.range.end;
10012 }
10013 if entry.diagnostic.is_primary {
10014 primary_range = Some(entry.range.clone());
10015 primary_message = Some(entry.diagnostic.message.clone());
10016 }
10017 Some(entry)
10018 })
10019 .collect::<Vec<_>>();
10020 let primary_range = primary_range?;
10021 let primary_message = primary_message?;
10022 let primary_range =
10023 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10024
10025 let blocks = display_map
10026 .insert_blocks(
10027 diagnostic_group.iter().map(|entry| {
10028 let diagnostic = entry.diagnostic.clone();
10029 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10030 BlockProperties {
10031 style: BlockStyle::Fixed,
10032 position: buffer.anchor_after(entry.range.start),
10033 height: message_height,
10034 render: diagnostic_block_renderer(diagnostic, None, true, true),
10035 disposition: BlockDisposition::Below,
10036 priority: 0,
10037 }
10038 }),
10039 cx,
10040 )
10041 .into_iter()
10042 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10043 .collect();
10044
10045 Some(ActiveDiagnosticGroup {
10046 primary_range,
10047 primary_message,
10048 group_id,
10049 blocks,
10050 is_valid: true,
10051 })
10052 });
10053 self.active_diagnostics.is_some()
10054 }
10055
10056 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10057 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10058 self.display_map.update(cx, |display_map, cx| {
10059 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10060 });
10061 cx.notify();
10062 }
10063 }
10064
10065 pub fn set_selections_from_remote(
10066 &mut self,
10067 selections: Vec<Selection<Anchor>>,
10068 pending_selection: Option<Selection<Anchor>>,
10069 cx: &mut ViewContext<Self>,
10070 ) {
10071 let old_cursor_position = self.selections.newest_anchor().head();
10072 self.selections.change_with(cx, |s| {
10073 s.select_anchors(selections);
10074 if let Some(pending_selection) = pending_selection {
10075 s.set_pending(pending_selection, SelectMode::Character);
10076 } else {
10077 s.clear_pending();
10078 }
10079 });
10080 self.selections_did_change(false, &old_cursor_position, true, cx);
10081 }
10082
10083 fn push_to_selection_history(&mut self) {
10084 self.selection_history.push(SelectionHistoryEntry {
10085 selections: self.selections.disjoint_anchors(),
10086 select_next_state: self.select_next_state.clone(),
10087 select_prev_state: self.select_prev_state.clone(),
10088 add_selections_state: self.add_selections_state.clone(),
10089 });
10090 }
10091
10092 pub fn transact(
10093 &mut self,
10094 cx: &mut ViewContext<Self>,
10095 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10096 ) -> Option<TransactionId> {
10097 self.start_transaction_at(Instant::now(), cx);
10098 update(self, cx);
10099 self.end_transaction_at(Instant::now(), cx)
10100 }
10101
10102 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10103 self.end_selection(cx);
10104 if let Some(tx_id) = self
10105 .buffer
10106 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10107 {
10108 self.selection_history
10109 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10110 cx.emit(EditorEvent::TransactionBegun {
10111 transaction_id: tx_id,
10112 })
10113 }
10114 }
10115
10116 fn end_transaction_at(
10117 &mut self,
10118 now: Instant,
10119 cx: &mut ViewContext<Self>,
10120 ) -> Option<TransactionId> {
10121 if let Some(transaction_id) = self
10122 .buffer
10123 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10124 {
10125 if let Some((_, end_selections)) =
10126 self.selection_history.transaction_mut(transaction_id)
10127 {
10128 *end_selections = Some(self.selections.disjoint_anchors());
10129 } else {
10130 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10131 }
10132
10133 cx.emit(EditorEvent::Edited { transaction_id });
10134 Some(transaction_id)
10135 } else {
10136 None
10137 }
10138 }
10139
10140 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10141 let mut fold_ranges = Vec::new();
10142
10143 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10144
10145 let selections = self.selections.all_adjusted(cx);
10146 for selection in selections {
10147 let range = selection.range().sorted();
10148 let buffer_start_row = range.start.row;
10149
10150 for row in (0..=range.end.row).rev() {
10151 if let Some((foldable_range, fold_text)) =
10152 display_map.foldable_range(MultiBufferRow(row))
10153 {
10154 if foldable_range.end.row >= buffer_start_row {
10155 fold_ranges.push((foldable_range, fold_text));
10156 if row <= range.start.row {
10157 break;
10158 }
10159 }
10160 }
10161 }
10162 }
10163
10164 self.fold_ranges(fold_ranges, true, cx);
10165 }
10166
10167 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10168 let buffer_row = fold_at.buffer_row;
10169 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10170
10171 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10172 let autoscroll = self
10173 .selections
10174 .all::<Point>(cx)
10175 .iter()
10176 .any(|selection| fold_range.overlaps(&selection.range()));
10177
10178 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10179 }
10180 }
10181
10182 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10183 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10184 let buffer = &display_map.buffer_snapshot;
10185 let selections = self.selections.all::<Point>(cx);
10186 let ranges = selections
10187 .iter()
10188 .map(|s| {
10189 let range = s.display_range(&display_map).sorted();
10190 let mut start = range.start.to_point(&display_map);
10191 let mut end = range.end.to_point(&display_map);
10192 start.column = 0;
10193 end.column = buffer.line_len(MultiBufferRow(end.row));
10194 start..end
10195 })
10196 .collect::<Vec<_>>();
10197
10198 self.unfold_ranges(ranges, true, true, cx);
10199 }
10200
10201 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10202 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10203
10204 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10205 ..Point::new(
10206 unfold_at.buffer_row.0,
10207 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10208 );
10209
10210 let autoscroll = self
10211 .selections
10212 .all::<Point>(cx)
10213 .iter()
10214 .any(|selection| selection.range().overlaps(&intersection_range));
10215
10216 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10217 }
10218
10219 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10220 let selections = self.selections.all::<Point>(cx);
10221 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10222 let line_mode = self.selections.line_mode;
10223 let ranges = selections.into_iter().map(|s| {
10224 if line_mode {
10225 let start = Point::new(s.start.row, 0);
10226 let end = Point::new(
10227 s.end.row,
10228 display_map
10229 .buffer_snapshot
10230 .line_len(MultiBufferRow(s.end.row)),
10231 );
10232 (start..end, display_map.fold_placeholder.clone())
10233 } else {
10234 (s.start..s.end, display_map.fold_placeholder.clone())
10235 }
10236 });
10237 self.fold_ranges(ranges, true, cx);
10238 }
10239
10240 pub fn fold_ranges<T: ToOffset + Clone>(
10241 &mut self,
10242 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10243 auto_scroll: bool,
10244 cx: &mut ViewContext<Self>,
10245 ) {
10246 let mut fold_ranges = Vec::new();
10247 let mut buffers_affected = HashMap::default();
10248 let multi_buffer = self.buffer().read(cx);
10249 for (fold_range, fold_text) in ranges {
10250 if let Some((_, buffer, _)) =
10251 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10252 {
10253 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10254 };
10255 fold_ranges.push((fold_range, fold_text));
10256 }
10257
10258 let mut ranges = fold_ranges.into_iter().peekable();
10259 if ranges.peek().is_some() {
10260 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10261
10262 if auto_scroll {
10263 self.request_autoscroll(Autoscroll::fit(), cx);
10264 }
10265
10266 for buffer in buffers_affected.into_values() {
10267 self.sync_expanded_diff_hunks(buffer, cx);
10268 }
10269
10270 cx.notify();
10271
10272 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10273 // Clear diagnostics block when folding a range that contains it.
10274 let snapshot = self.snapshot(cx);
10275 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10276 drop(snapshot);
10277 self.active_diagnostics = Some(active_diagnostics);
10278 self.dismiss_diagnostics(cx);
10279 } else {
10280 self.active_diagnostics = Some(active_diagnostics);
10281 }
10282 }
10283
10284 self.scrollbar_marker_state.dirty = true;
10285 }
10286 }
10287
10288 pub fn unfold_ranges<T: ToOffset + Clone>(
10289 &mut self,
10290 ranges: impl IntoIterator<Item = Range<T>>,
10291 inclusive: bool,
10292 auto_scroll: bool,
10293 cx: &mut ViewContext<Self>,
10294 ) {
10295 let mut unfold_ranges = Vec::new();
10296 let mut buffers_affected = HashMap::default();
10297 let multi_buffer = self.buffer().read(cx);
10298 for range in ranges {
10299 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10300 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10301 };
10302 unfold_ranges.push(range);
10303 }
10304
10305 let mut ranges = unfold_ranges.into_iter().peekable();
10306 if ranges.peek().is_some() {
10307 self.display_map
10308 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10309 if auto_scroll {
10310 self.request_autoscroll(Autoscroll::fit(), cx);
10311 }
10312
10313 for buffer in buffers_affected.into_values() {
10314 self.sync_expanded_diff_hunks(buffer, cx);
10315 }
10316
10317 cx.notify();
10318 self.scrollbar_marker_state.dirty = true;
10319 self.active_indent_guides_state.dirty = true;
10320 }
10321 }
10322
10323 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10324 if hovered != self.gutter_hovered {
10325 self.gutter_hovered = hovered;
10326 cx.notify();
10327 }
10328 }
10329
10330 pub fn insert_blocks(
10331 &mut self,
10332 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10333 autoscroll: Option<Autoscroll>,
10334 cx: &mut ViewContext<Self>,
10335 ) -> Vec<CustomBlockId> {
10336 let blocks = self
10337 .display_map
10338 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10339 if let Some(autoscroll) = autoscroll {
10340 self.request_autoscroll(autoscroll, cx);
10341 }
10342 cx.notify();
10343 blocks
10344 }
10345
10346 pub fn resize_blocks(
10347 &mut self,
10348 heights: HashMap<CustomBlockId, u32>,
10349 autoscroll: Option<Autoscroll>,
10350 cx: &mut ViewContext<Self>,
10351 ) {
10352 self.display_map
10353 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10354 if let Some(autoscroll) = autoscroll {
10355 self.request_autoscroll(autoscroll, cx);
10356 }
10357 cx.notify();
10358 }
10359
10360 pub fn replace_blocks(
10361 &mut self,
10362 renderers: HashMap<CustomBlockId, RenderBlock>,
10363 autoscroll: Option<Autoscroll>,
10364 cx: &mut ViewContext<Self>,
10365 ) {
10366 self.display_map
10367 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10368 if let Some(autoscroll) = autoscroll {
10369 self.request_autoscroll(autoscroll, cx);
10370 }
10371 cx.notify();
10372 }
10373
10374 pub fn remove_blocks(
10375 &mut self,
10376 block_ids: HashSet<CustomBlockId>,
10377 autoscroll: Option<Autoscroll>,
10378 cx: &mut ViewContext<Self>,
10379 ) {
10380 self.display_map.update(cx, |display_map, cx| {
10381 display_map.remove_blocks(block_ids, cx)
10382 });
10383 if let Some(autoscroll) = autoscroll {
10384 self.request_autoscroll(autoscroll, cx);
10385 }
10386 cx.notify();
10387 }
10388
10389 pub fn row_for_block(
10390 &self,
10391 block_id: CustomBlockId,
10392 cx: &mut ViewContext<Self>,
10393 ) -> Option<DisplayRow> {
10394 self.display_map
10395 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10396 }
10397
10398 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10399 self.focused_block = Some(focused_block);
10400 }
10401
10402 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10403 self.focused_block.take()
10404 }
10405
10406 pub fn insert_creases(
10407 &mut self,
10408 creases: impl IntoIterator<Item = Crease>,
10409 cx: &mut ViewContext<Self>,
10410 ) -> Vec<CreaseId> {
10411 self.display_map
10412 .update(cx, |map, cx| map.insert_creases(creases, cx))
10413 }
10414
10415 pub fn remove_creases(
10416 &mut self,
10417 ids: impl IntoIterator<Item = CreaseId>,
10418 cx: &mut ViewContext<Self>,
10419 ) {
10420 self.display_map
10421 .update(cx, |map, cx| map.remove_creases(ids, cx));
10422 }
10423
10424 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10425 self.display_map
10426 .update(cx, |map, cx| map.snapshot(cx))
10427 .longest_row()
10428 }
10429
10430 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10431 self.display_map
10432 .update(cx, |map, cx| map.snapshot(cx))
10433 .max_point()
10434 }
10435
10436 pub fn text(&self, cx: &AppContext) -> String {
10437 self.buffer.read(cx).read(cx).text()
10438 }
10439
10440 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10441 let text = self.text(cx);
10442 let text = text.trim();
10443
10444 if text.is_empty() {
10445 return None;
10446 }
10447
10448 Some(text.to_string())
10449 }
10450
10451 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10452 self.transact(cx, |this, cx| {
10453 this.buffer
10454 .read(cx)
10455 .as_singleton()
10456 .expect("you can only call set_text on editors for singleton buffers")
10457 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10458 });
10459 }
10460
10461 pub fn display_text(&self, cx: &mut AppContext) -> String {
10462 self.display_map
10463 .update(cx, |map, cx| map.snapshot(cx))
10464 .text()
10465 }
10466
10467 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10468 let mut wrap_guides = smallvec::smallvec![];
10469
10470 if self.show_wrap_guides == Some(false) {
10471 return wrap_guides;
10472 }
10473
10474 let settings = self.buffer.read(cx).settings_at(0, cx);
10475 if settings.show_wrap_guides {
10476 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10477 wrap_guides.push((soft_wrap as usize, true));
10478 }
10479 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10480 }
10481
10482 wrap_guides
10483 }
10484
10485 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10486 let settings = self.buffer.read(cx).settings_at(0, cx);
10487 let mode = self
10488 .soft_wrap_mode_override
10489 .unwrap_or_else(|| settings.soft_wrap);
10490 match mode {
10491 language_settings::SoftWrap::None => SoftWrap::None,
10492 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10493 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10494 language_settings::SoftWrap::PreferredLineLength => {
10495 SoftWrap::Column(settings.preferred_line_length)
10496 }
10497 }
10498 }
10499
10500 pub fn set_soft_wrap_mode(
10501 &mut self,
10502 mode: language_settings::SoftWrap,
10503 cx: &mut ViewContext<Self>,
10504 ) {
10505 self.soft_wrap_mode_override = Some(mode);
10506 cx.notify();
10507 }
10508
10509 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10510 let rem_size = cx.rem_size();
10511 self.display_map.update(cx, |map, cx| {
10512 map.set_font(
10513 style.text.font(),
10514 style.text.font_size.to_pixels(rem_size),
10515 cx,
10516 )
10517 });
10518 self.style = Some(style);
10519 }
10520
10521 pub fn style(&self) -> Option<&EditorStyle> {
10522 self.style.as_ref()
10523 }
10524
10525 // Called by the element. This method is not designed to be called outside of the editor
10526 // element's layout code because it does not notify when rewrapping is computed synchronously.
10527 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10528 self.display_map
10529 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10530 }
10531
10532 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10533 if self.soft_wrap_mode_override.is_some() {
10534 self.soft_wrap_mode_override.take();
10535 } else {
10536 let soft_wrap = match self.soft_wrap_mode(cx) {
10537 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10538 SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10539 language_settings::SoftWrap::PreferLine
10540 }
10541 };
10542 self.soft_wrap_mode_override = Some(soft_wrap);
10543 }
10544 cx.notify();
10545 }
10546
10547 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10548 let Some(workspace) = self.workspace() else {
10549 return;
10550 };
10551 let fs = workspace.read(cx).app_state().fs.clone();
10552 let current_show = TabBarSettings::get_global(cx).show;
10553 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10554 setting.show = Some(!current_show);
10555 });
10556 }
10557
10558 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10559 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10560 self.buffer
10561 .read(cx)
10562 .settings_at(0, cx)
10563 .indent_guides
10564 .enabled
10565 });
10566 self.show_indent_guides = Some(!currently_enabled);
10567 cx.notify();
10568 }
10569
10570 fn should_show_indent_guides(&self) -> Option<bool> {
10571 self.show_indent_guides
10572 }
10573
10574 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10575 let mut editor_settings = EditorSettings::get_global(cx).clone();
10576 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10577 EditorSettings::override_global(editor_settings, cx);
10578 }
10579
10580 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10581 self.show_gutter = show_gutter;
10582 cx.notify();
10583 }
10584
10585 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10586 self.show_line_numbers = Some(show_line_numbers);
10587 cx.notify();
10588 }
10589
10590 pub fn set_show_git_diff_gutter(
10591 &mut self,
10592 show_git_diff_gutter: bool,
10593 cx: &mut ViewContext<Self>,
10594 ) {
10595 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10596 cx.notify();
10597 }
10598
10599 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10600 self.show_code_actions = Some(show_code_actions);
10601 cx.notify();
10602 }
10603
10604 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10605 self.show_runnables = Some(show_runnables);
10606 cx.notify();
10607 }
10608
10609 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10610 if self.display_map.read(cx).masked != masked {
10611 self.display_map.update(cx, |map, _| map.masked = masked);
10612 }
10613 cx.notify()
10614 }
10615
10616 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10617 self.show_wrap_guides = Some(show_wrap_guides);
10618 cx.notify();
10619 }
10620
10621 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10622 self.show_indent_guides = Some(show_indent_guides);
10623 cx.notify();
10624 }
10625
10626 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10627 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10628 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10629 if let Some(dir) = file.abs_path(cx).parent() {
10630 return Some(dir.to_owned());
10631 }
10632 }
10633
10634 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10635 return Some(project_path.path.to_path_buf());
10636 }
10637 }
10638
10639 None
10640 }
10641
10642 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10643 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10644 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10645 cx.reveal_path(&file.abs_path(cx));
10646 }
10647 }
10648 }
10649
10650 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10651 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10652 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10653 if let Some(path) = file.abs_path(cx).to_str() {
10654 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10655 }
10656 }
10657 }
10658 }
10659
10660 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10661 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10662 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10663 if let Some(path) = file.path().to_str() {
10664 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10665 }
10666 }
10667 }
10668 }
10669
10670 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10671 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10672
10673 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10674 self.start_git_blame(true, cx);
10675 }
10676
10677 cx.notify();
10678 }
10679
10680 pub fn toggle_git_blame_inline(
10681 &mut self,
10682 _: &ToggleGitBlameInline,
10683 cx: &mut ViewContext<Self>,
10684 ) {
10685 self.toggle_git_blame_inline_internal(true, cx);
10686 cx.notify();
10687 }
10688
10689 pub fn git_blame_inline_enabled(&self) -> bool {
10690 self.git_blame_inline_enabled
10691 }
10692
10693 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10694 self.show_selection_menu = self
10695 .show_selection_menu
10696 .map(|show_selections_menu| !show_selections_menu)
10697 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10698
10699 cx.notify();
10700 }
10701
10702 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10703 self.show_selection_menu
10704 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10705 }
10706
10707 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10708 if let Some(project) = self.project.as_ref() {
10709 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10710 return;
10711 };
10712
10713 if buffer.read(cx).file().is_none() {
10714 return;
10715 }
10716
10717 let focused = self.focus_handle(cx).contains_focused(cx);
10718
10719 let project = project.clone();
10720 let blame =
10721 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10722 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10723 self.blame = Some(blame);
10724 }
10725 }
10726
10727 fn toggle_git_blame_inline_internal(
10728 &mut self,
10729 user_triggered: bool,
10730 cx: &mut ViewContext<Self>,
10731 ) {
10732 if self.git_blame_inline_enabled {
10733 self.git_blame_inline_enabled = false;
10734 self.show_git_blame_inline = false;
10735 self.show_git_blame_inline_delay_task.take();
10736 } else {
10737 self.git_blame_inline_enabled = true;
10738 self.start_git_blame_inline(user_triggered, cx);
10739 }
10740
10741 cx.notify();
10742 }
10743
10744 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10745 self.start_git_blame(user_triggered, cx);
10746
10747 if ProjectSettings::get_global(cx)
10748 .git
10749 .inline_blame_delay()
10750 .is_some()
10751 {
10752 self.start_inline_blame_timer(cx);
10753 } else {
10754 self.show_git_blame_inline = true
10755 }
10756 }
10757
10758 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10759 self.blame.as_ref()
10760 }
10761
10762 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10763 self.show_git_blame_gutter && self.has_blame_entries(cx)
10764 }
10765
10766 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10767 self.show_git_blame_inline
10768 && self.focus_handle.is_focused(cx)
10769 && !self.newest_selection_head_on_empty_line(cx)
10770 && self.has_blame_entries(cx)
10771 }
10772
10773 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10774 self.blame()
10775 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10776 }
10777
10778 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10779 let cursor_anchor = self.selections.newest_anchor().head();
10780
10781 let snapshot = self.buffer.read(cx).snapshot(cx);
10782 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10783
10784 snapshot.line_len(buffer_row) == 0
10785 }
10786
10787 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10788 let (path, selection, repo) = maybe!({
10789 let project_handle = self.project.as_ref()?.clone();
10790 let project = project_handle.read(cx);
10791
10792 let selection = self.selections.newest::<Point>(cx);
10793 let selection_range = selection.range();
10794
10795 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10796 (buffer, selection_range.start.row..selection_range.end.row)
10797 } else {
10798 let buffer_ranges = self
10799 .buffer()
10800 .read(cx)
10801 .range_to_buffer_ranges(selection_range, cx);
10802
10803 let (buffer, range, _) = if selection.reversed {
10804 buffer_ranges.first()
10805 } else {
10806 buffer_ranges.last()
10807 }?;
10808
10809 let snapshot = buffer.read(cx).snapshot();
10810 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10811 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10812 (buffer.clone(), selection)
10813 };
10814
10815 let path = buffer
10816 .read(cx)
10817 .file()?
10818 .as_local()?
10819 .path()
10820 .to_str()?
10821 .to_string();
10822 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10823 Some((path, selection, repo))
10824 })
10825 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10826
10827 const REMOTE_NAME: &str = "origin";
10828 let origin_url = repo
10829 .remote_url(REMOTE_NAME)
10830 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10831 let sha = repo
10832 .head_sha()
10833 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10834
10835 let (provider, remote) =
10836 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10837 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10838
10839 Ok(provider.build_permalink(
10840 remote,
10841 BuildPermalinkParams {
10842 sha: &sha,
10843 path: &path,
10844 selection: Some(selection),
10845 },
10846 ))
10847 }
10848
10849 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10850 let permalink = self.get_permalink_to_line(cx);
10851
10852 match permalink {
10853 Ok(permalink) => {
10854 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
10855 }
10856 Err(err) => {
10857 let message = format!("Failed to copy permalink: {err}");
10858
10859 Err::<(), anyhow::Error>(err).log_err();
10860
10861 if let Some(workspace) = self.workspace() {
10862 workspace.update(cx, |workspace, cx| {
10863 struct CopyPermalinkToLine;
10864
10865 workspace.show_toast(
10866 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10867 cx,
10868 )
10869 })
10870 }
10871 }
10872 }
10873 }
10874
10875 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10876 let permalink = self.get_permalink_to_line(cx);
10877
10878 match permalink {
10879 Ok(permalink) => {
10880 cx.open_url(permalink.as_ref());
10881 }
10882 Err(err) => {
10883 let message = format!("Failed to open permalink: {err}");
10884
10885 Err::<(), anyhow::Error>(err).log_err();
10886
10887 if let Some(workspace) = self.workspace() {
10888 workspace.update(cx, |workspace, cx| {
10889 struct OpenPermalinkToLine;
10890
10891 workspace.show_toast(
10892 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10893 cx,
10894 )
10895 })
10896 }
10897 }
10898 }
10899 }
10900
10901 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10902 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10903 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10904 pub fn highlight_rows<T: 'static>(
10905 &mut self,
10906 rows: RangeInclusive<Anchor>,
10907 color: Option<Hsla>,
10908 should_autoscroll: bool,
10909 cx: &mut ViewContext<Self>,
10910 ) {
10911 let snapshot = self.buffer().read(cx).snapshot(cx);
10912 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10913 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10914 highlight
10915 .range
10916 .start()
10917 .cmp(&rows.start(), &snapshot)
10918 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10919 });
10920 match (color, existing_highlight_index) {
10921 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10922 ix,
10923 RowHighlight {
10924 index: post_inc(&mut self.highlight_order),
10925 range: rows,
10926 should_autoscroll,
10927 color,
10928 },
10929 ),
10930 (None, Ok(i)) => {
10931 row_highlights.remove(i);
10932 }
10933 }
10934 }
10935
10936 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10937 pub fn clear_row_highlights<T: 'static>(&mut self) {
10938 self.highlighted_rows.remove(&TypeId::of::<T>());
10939 }
10940
10941 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10942 pub fn highlighted_rows<T: 'static>(
10943 &self,
10944 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10945 Some(
10946 self.highlighted_rows
10947 .get(&TypeId::of::<T>())?
10948 .iter()
10949 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10950 )
10951 }
10952
10953 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10954 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10955 /// Allows to ignore certain kinds of highlights.
10956 pub fn highlighted_display_rows(
10957 &mut self,
10958 cx: &mut WindowContext,
10959 ) -> BTreeMap<DisplayRow, Hsla> {
10960 let snapshot = self.snapshot(cx);
10961 let mut used_highlight_orders = HashMap::default();
10962 self.highlighted_rows
10963 .iter()
10964 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10965 .fold(
10966 BTreeMap::<DisplayRow, Hsla>::new(),
10967 |mut unique_rows, highlight| {
10968 let start_row = highlight.range.start().to_display_point(&snapshot).row();
10969 let end_row = highlight.range.end().to_display_point(&snapshot).row();
10970 for row in start_row.0..=end_row.0 {
10971 let used_index =
10972 used_highlight_orders.entry(row).or_insert(highlight.index);
10973 if highlight.index >= *used_index {
10974 *used_index = highlight.index;
10975 match highlight.color {
10976 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10977 None => unique_rows.remove(&DisplayRow(row)),
10978 };
10979 }
10980 }
10981 unique_rows
10982 },
10983 )
10984 }
10985
10986 pub fn highlighted_display_row_for_autoscroll(
10987 &self,
10988 snapshot: &DisplaySnapshot,
10989 ) -> Option<DisplayRow> {
10990 self.highlighted_rows
10991 .values()
10992 .flat_map(|highlighted_rows| highlighted_rows.iter())
10993 .filter_map(|highlight| {
10994 if highlight.color.is_none() || !highlight.should_autoscroll {
10995 return None;
10996 }
10997 Some(highlight.range.start().to_display_point(&snapshot).row())
10998 })
10999 .min()
11000 }
11001
11002 pub fn set_search_within_ranges(
11003 &mut self,
11004 ranges: &[Range<Anchor>],
11005 cx: &mut ViewContext<Self>,
11006 ) {
11007 self.highlight_background::<SearchWithinRange>(
11008 ranges,
11009 |colors| colors.editor_document_highlight_read_background,
11010 cx,
11011 )
11012 }
11013
11014 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11015 self.breadcrumb_header = Some(new_header);
11016 }
11017
11018 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11019 self.clear_background_highlights::<SearchWithinRange>(cx);
11020 }
11021
11022 pub fn highlight_background<T: 'static>(
11023 &mut self,
11024 ranges: &[Range<Anchor>],
11025 color_fetcher: fn(&ThemeColors) -> Hsla,
11026 cx: &mut ViewContext<Self>,
11027 ) {
11028 self.background_highlights
11029 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11030 self.scrollbar_marker_state.dirty = true;
11031 cx.notify();
11032 }
11033
11034 pub fn clear_background_highlights<T: 'static>(
11035 &mut self,
11036 cx: &mut ViewContext<Self>,
11037 ) -> Option<BackgroundHighlight> {
11038 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11039 if !text_highlights.1.is_empty() {
11040 self.scrollbar_marker_state.dirty = true;
11041 cx.notify();
11042 }
11043 Some(text_highlights)
11044 }
11045
11046 pub fn highlight_gutter<T: 'static>(
11047 &mut self,
11048 ranges: &[Range<Anchor>],
11049 color_fetcher: fn(&AppContext) -> Hsla,
11050 cx: &mut ViewContext<Self>,
11051 ) {
11052 self.gutter_highlights
11053 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11054 cx.notify();
11055 }
11056
11057 pub fn clear_gutter_highlights<T: 'static>(
11058 &mut self,
11059 cx: &mut ViewContext<Self>,
11060 ) -> Option<GutterHighlight> {
11061 cx.notify();
11062 self.gutter_highlights.remove(&TypeId::of::<T>())
11063 }
11064
11065 #[cfg(feature = "test-support")]
11066 pub fn all_text_background_highlights(
11067 &mut self,
11068 cx: &mut ViewContext<Self>,
11069 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11070 let snapshot = self.snapshot(cx);
11071 let buffer = &snapshot.buffer_snapshot;
11072 let start = buffer.anchor_before(0);
11073 let end = buffer.anchor_after(buffer.len());
11074 let theme = cx.theme().colors();
11075 self.background_highlights_in_range(start..end, &snapshot, theme)
11076 }
11077
11078 #[cfg(feature = "test-support")]
11079 pub fn search_background_highlights(
11080 &mut self,
11081 cx: &mut ViewContext<Self>,
11082 ) -> Vec<Range<Point>> {
11083 let snapshot = self.buffer().read(cx).snapshot(cx);
11084
11085 let highlights = self
11086 .background_highlights
11087 .get(&TypeId::of::<items::BufferSearchHighlights>());
11088
11089 if let Some((_color, ranges)) = highlights {
11090 ranges
11091 .iter()
11092 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11093 .collect_vec()
11094 } else {
11095 vec![]
11096 }
11097 }
11098
11099 fn document_highlights_for_position<'a>(
11100 &'a self,
11101 position: Anchor,
11102 buffer: &'a MultiBufferSnapshot,
11103 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11104 let read_highlights = self
11105 .background_highlights
11106 .get(&TypeId::of::<DocumentHighlightRead>())
11107 .map(|h| &h.1);
11108 let write_highlights = self
11109 .background_highlights
11110 .get(&TypeId::of::<DocumentHighlightWrite>())
11111 .map(|h| &h.1);
11112 let left_position = position.bias_left(buffer);
11113 let right_position = position.bias_right(buffer);
11114 read_highlights
11115 .into_iter()
11116 .chain(write_highlights)
11117 .flat_map(move |ranges| {
11118 let start_ix = match ranges.binary_search_by(|probe| {
11119 let cmp = probe.end.cmp(&left_position, buffer);
11120 if cmp.is_ge() {
11121 Ordering::Greater
11122 } else {
11123 Ordering::Less
11124 }
11125 }) {
11126 Ok(i) | Err(i) => i,
11127 };
11128
11129 ranges[start_ix..]
11130 .iter()
11131 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11132 })
11133 }
11134
11135 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11136 self.background_highlights
11137 .get(&TypeId::of::<T>())
11138 .map_or(false, |(_, highlights)| !highlights.is_empty())
11139 }
11140
11141 pub fn background_highlights_in_range(
11142 &self,
11143 search_range: Range<Anchor>,
11144 display_snapshot: &DisplaySnapshot,
11145 theme: &ThemeColors,
11146 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11147 let mut results = Vec::new();
11148 for (color_fetcher, ranges) in self.background_highlights.values() {
11149 let color = color_fetcher(theme);
11150 let start_ix = match ranges.binary_search_by(|probe| {
11151 let cmp = probe
11152 .end
11153 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11154 if cmp.is_gt() {
11155 Ordering::Greater
11156 } else {
11157 Ordering::Less
11158 }
11159 }) {
11160 Ok(i) | Err(i) => i,
11161 };
11162 for range in &ranges[start_ix..] {
11163 if range
11164 .start
11165 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11166 .is_ge()
11167 {
11168 break;
11169 }
11170
11171 let start = range.start.to_display_point(&display_snapshot);
11172 let end = range.end.to_display_point(&display_snapshot);
11173 results.push((start..end, color))
11174 }
11175 }
11176 results
11177 }
11178
11179 pub fn background_highlight_row_ranges<T: 'static>(
11180 &self,
11181 search_range: Range<Anchor>,
11182 display_snapshot: &DisplaySnapshot,
11183 count: usize,
11184 ) -> Vec<RangeInclusive<DisplayPoint>> {
11185 let mut results = Vec::new();
11186 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11187 return vec![];
11188 };
11189
11190 let start_ix = match ranges.binary_search_by(|probe| {
11191 let cmp = probe
11192 .end
11193 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11194 if cmp.is_gt() {
11195 Ordering::Greater
11196 } else {
11197 Ordering::Less
11198 }
11199 }) {
11200 Ok(i) | Err(i) => i,
11201 };
11202 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11203 if let (Some(start_display), Some(end_display)) = (start, end) {
11204 results.push(
11205 start_display.to_display_point(display_snapshot)
11206 ..=end_display.to_display_point(display_snapshot),
11207 );
11208 }
11209 };
11210 let mut start_row: Option<Point> = None;
11211 let mut end_row: Option<Point> = None;
11212 if ranges.len() > count {
11213 return Vec::new();
11214 }
11215 for range in &ranges[start_ix..] {
11216 if range
11217 .start
11218 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11219 .is_ge()
11220 {
11221 break;
11222 }
11223 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11224 if let Some(current_row) = &end_row {
11225 if end.row == current_row.row {
11226 continue;
11227 }
11228 }
11229 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11230 if start_row.is_none() {
11231 assert_eq!(end_row, None);
11232 start_row = Some(start);
11233 end_row = Some(end);
11234 continue;
11235 }
11236 if let Some(current_end) = end_row.as_mut() {
11237 if start.row > current_end.row + 1 {
11238 push_region(start_row, end_row);
11239 start_row = Some(start);
11240 end_row = Some(end);
11241 } else {
11242 // Merge two hunks.
11243 *current_end = end;
11244 }
11245 } else {
11246 unreachable!();
11247 }
11248 }
11249 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11250 push_region(start_row, end_row);
11251 results
11252 }
11253
11254 pub fn gutter_highlights_in_range(
11255 &self,
11256 search_range: Range<Anchor>,
11257 display_snapshot: &DisplaySnapshot,
11258 cx: &AppContext,
11259 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11260 let mut results = Vec::new();
11261 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11262 let color = color_fetcher(cx);
11263 let start_ix = match ranges.binary_search_by(|probe| {
11264 let cmp = probe
11265 .end
11266 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11267 if cmp.is_gt() {
11268 Ordering::Greater
11269 } else {
11270 Ordering::Less
11271 }
11272 }) {
11273 Ok(i) | Err(i) => i,
11274 };
11275 for range in &ranges[start_ix..] {
11276 if range
11277 .start
11278 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11279 .is_ge()
11280 {
11281 break;
11282 }
11283
11284 let start = range.start.to_display_point(&display_snapshot);
11285 let end = range.end.to_display_point(&display_snapshot);
11286 results.push((start..end, color))
11287 }
11288 }
11289 results
11290 }
11291
11292 /// Get the text ranges corresponding to the redaction query
11293 pub fn redacted_ranges(
11294 &self,
11295 search_range: Range<Anchor>,
11296 display_snapshot: &DisplaySnapshot,
11297 cx: &WindowContext,
11298 ) -> Vec<Range<DisplayPoint>> {
11299 display_snapshot
11300 .buffer_snapshot
11301 .redacted_ranges(search_range, |file| {
11302 if let Some(file) = file {
11303 file.is_private()
11304 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11305 } else {
11306 false
11307 }
11308 })
11309 .map(|range| {
11310 range.start.to_display_point(display_snapshot)
11311 ..range.end.to_display_point(display_snapshot)
11312 })
11313 .collect()
11314 }
11315
11316 pub fn highlight_text<T: 'static>(
11317 &mut self,
11318 ranges: Vec<Range<Anchor>>,
11319 style: HighlightStyle,
11320 cx: &mut ViewContext<Self>,
11321 ) {
11322 self.display_map.update(cx, |map, _| {
11323 map.highlight_text(TypeId::of::<T>(), ranges, style)
11324 });
11325 cx.notify();
11326 }
11327
11328 pub(crate) fn highlight_inlays<T: 'static>(
11329 &mut self,
11330 highlights: Vec<InlayHighlight>,
11331 style: HighlightStyle,
11332 cx: &mut ViewContext<Self>,
11333 ) {
11334 self.display_map.update(cx, |map, _| {
11335 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11336 });
11337 cx.notify();
11338 }
11339
11340 pub fn text_highlights<'a, T: 'static>(
11341 &'a self,
11342 cx: &'a AppContext,
11343 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11344 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11345 }
11346
11347 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11348 let cleared = self
11349 .display_map
11350 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11351 if cleared {
11352 cx.notify();
11353 }
11354 }
11355
11356 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11357 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11358 && self.focus_handle.is_focused(cx)
11359 }
11360
11361 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11362 self.show_cursor_when_unfocused = is_enabled;
11363 cx.notify();
11364 }
11365
11366 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11367 cx.notify();
11368 }
11369
11370 fn on_buffer_event(
11371 &mut self,
11372 multibuffer: Model<MultiBuffer>,
11373 event: &multi_buffer::Event,
11374 cx: &mut ViewContext<Self>,
11375 ) {
11376 match event {
11377 multi_buffer::Event::Edited {
11378 singleton_buffer_edited,
11379 } => {
11380 self.scrollbar_marker_state.dirty = true;
11381 self.active_indent_guides_state.dirty = true;
11382 self.refresh_active_diagnostics(cx);
11383 self.refresh_code_actions(cx);
11384 if self.has_active_inline_completion(cx) {
11385 self.update_visible_inline_completion(cx);
11386 }
11387 cx.emit(EditorEvent::BufferEdited);
11388 cx.emit(SearchEvent::MatchesInvalidated);
11389 if *singleton_buffer_edited {
11390 if let Some(project) = &self.project {
11391 let project = project.read(cx);
11392 #[allow(clippy::mutable_key_type)]
11393 let languages_affected = multibuffer
11394 .read(cx)
11395 .all_buffers()
11396 .into_iter()
11397 .filter_map(|buffer| {
11398 let buffer = buffer.read(cx);
11399 let language = buffer.language()?;
11400 if project.is_local()
11401 && project.language_servers_for_buffer(buffer, cx).count() == 0
11402 {
11403 None
11404 } else {
11405 Some(language)
11406 }
11407 })
11408 .cloned()
11409 .collect::<HashSet<_>>();
11410 if !languages_affected.is_empty() {
11411 self.refresh_inlay_hints(
11412 InlayHintRefreshReason::BufferEdited(languages_affected),
11413 cx,
11414 );
11415 }
11416 }
11417 }
11418
11419 let Some(project) = &self.project else { return };
11420 let telemetry = project.read(cx).client().telemetry().clone();
11421 refresh_linked_ranges(self, cx);
11422 telemetry.log_edit_event("editor");
11423 }
11424 multi_buffer::Event::ExcerptsAdded {
11425 buffer,
11426 predecessor,
11427 excerpts,
11428 } => {
11429 self.tasks_update_task = Some(self.refresh_runnables(cx));
11430 cx.emit(EditorEvent::ExcerptsAdded {
11431 buffer: buffer.clone(),
11432 predecessor: *predecessor,
11433 excerpts: excerpts.clone(),
11434 });
11435 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11436 }
11437 multi_buffer::Event::ExcerptsRemoved { ids } => {
11438 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11439 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11440 }
11441 multi_buffer::Event::ExcerptsEdited { ids } => {
11442 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11443 }
11444 multi_buffer::Event::ExcerptsExpanded { ids } => {
11445 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11446 }
11447 multi_buffer::Event::Reparsed(buffer_id) => {
11448 self.tasks_update_task = Some(self.refresh_runnables(cx));
11449
11450 cx.emit(EditorEvent::Reparsed(*buffer_id));
11451 }
11452 multi_buffer::Event::LanguageChanged(buffer_id) => {
11453 linked_editing_ranges::refresh_linked_ranges(self, cx);
11454 cx.emit(EditorEvent::Reparsed(*buffer_id));
11455 cx.notify();
11456 }
11457 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11458 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11459 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11460 cx.emit(EditorEvent::TitleChanged)
11461 }
11462 multi_buffer::Event::DiffBaseChanged => {
11463 self.scrollbar_marker_state.dirty = true;
11464 cx.emit(EditorEvent::DiffBaseChanged);
11465 cx.notify();
11466 }
11467 multi_buffer::Event::DiffUpdated { buffer } => {
11468 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11469 cx.notify();
11470 }
11471 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11472 multi_buffer::Event::DiagnosticsUpdated => {
11473 self.refresh_active_diagnostics(cx);
11474 self.scrollbar_marker_state.dirty = true;
11475 cx.notify();
11476 }
11477 _ => {}
11478 };
11479 }
11480
11481 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11482 cx.notify();
11483 }
11484
11485 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11486 self.tasks_update_task = Some(self.refresh_runnables(cx));
11487 self.refresh_inline_completion(true, false, cx);
11488 self.refresh_inlay_hints(
11489 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11490 self.selections.newest_anchor().head(),
11491 &self.buffer.read(cx).snapshot(cx),
11492 cx,
11493 )),
11494 cx,
11495 );
11496 let editor_settings = EditorSettings::get_global(cx);
11497 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11498 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11499
11500 let project_settings = ProjectSettings::get_global(cx);
11501 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11502
11503 if self.mode == EditorMode::Full {
11504 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11505 if self.git_blame_inline_enabled != inline_blame_enabled {
11506 self.toggle_git_blame_inline_internal(false, cx);
11507 }
11508 }
11509
11510 cx.notify();
11511 }
11512
11513 pub fn set_searchable(&mut self, searchable: bool) {
11514 self.searchable = searchable;
11515 }
11516
11517 pub fn searchable(&self) -> bool {
11518 self.searchable
11519 }
11520
11521 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11522 self.open_excerpts_common(true, cx)
11523 }
11524
11525 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11526 self.open_excerpts_common(false, cx)
11527 }
11528
11529 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11530 let buffer = self.buffer.read(cx);
11531 if buffer.is_singleton() {
11532 cx.propagate();
11533 return;
11534 }
11535
11536 let Some(workspace) = self.workspace() else {
11537 cx.propagate();
11538 return;
11539 };
11540
11541 let mut new_selections_by_buffer = HashMap::default();
11542 for selection in self.selections.all::<usize>(cx) {
11543 for (buffer, mut range, _) in
11544 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11545 {
11546 if selection.reversed {
11547 mem::swap(&mut range.start, &mut range.end);
11548 }
11549 new_selections_by_buffer
11550 .entry(buffer)
11551 .or_insert(Vec::new())
11552 .push(range)
11553 }
11554 }
11555
11556 // We defer the pane interaction because we ourselves are a workspace item
11557 // and activating a new item causes the pane to call a method on us reentrantly,
11558 // which panics if we're on the stack.
11559 cx.window_context().defer(move |cx| {
11560 workspace.update(cx, |workspace, cx| {
11561 let pane = if split {
11562 workspace.adjacent_pane(cx)
11563 } else {
11564 workspace.active_pane().clone()
11565 };
11566
11567 for (buffer, ranges) in new_selections_by_buffer {
11568 let editor =
11569 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11570 editor.update(cx, |editor, cx| {
11571 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11572 s.select_ranges(ranges);
11573 });
11574 });
11575 }
11576 })
11577 });
11578 }
11579
11580 fn jump(
11581 &mut self,
11582 path: ProjectPath,
11583 position: Point,
11584 anchor: language::Anchor,
11585 offset_from_top: u32,
11586 cx: &mut ViewContext<Self>,
11587 ) {
11588 let workspace = self.workspace();
11589 cx.spawn(|_, mut cx| async move {
11590 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11591 let editor = workspace.update(&mut cx, |workspace, cx| {
11592 // Reset the preview item id before opening the new item
11593 workspace.active_pane().update(cx, |pane, cx| {
11594 pane.set_preview_item_id(None, cx);
11595 });
11596 workspace.open_path_preview(path, None, true, true, cx)
11597 })?;
11598 let editor = editor
11599 .await?
11600 .downcast::<Editor>()
11601 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11602 .downgrade();
11603 editor.update(&mut cx, |editor, cx| {
11604 let buffer = editor
11605 .buffer()
11606 .read(cx)
11607 .as_singleton()
11608 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11609 let buffer = buffer.read(cx);
11610 let cursor = if buffer.can_resolve(&anchor) {
11611 language::ToPoint::to_point(&anchor, buffer)
11612 } else {
11613 buffer.clip_point(position, Bias::Left)
11614 };
11615
11616 let nav_history = editor.nav_history.take();
11617 editor.change_selections(
11618 Some(Autoscroll::top_relative(offset_from_top as usize)),
11619 cx,
11620 |s| {
11621 s.select_ranges([cursor..cursor]);
11622 },
11623 );
11624 editor.nav_history = nav_history;
11625
11626 anyhow::Ok(())
11627 })??;
11628
11629 anyhow::Ok(())
11630 })
11631 .detach_and_log_err(cx);
11632 }
11633
11634 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11635 let snapshot = self.buffer.read(cx).read(cx);
11636 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11637 Some(
11638 ranges
11639 .iter()
11640 .map(move |range| {
11641 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11642 })
11643 .collect(),
11644 )
11645 }
11646
11647 fn selection_replacement_ranges(
11648 &self,
11649 range: Range<OffsetUtf16>,
11650 cx: &AppContext,
11651 ) -> Vec<Range<OffsetUtf16>> {
11652 let selections = self.selections.all::<OffsetUtf16>(cx);
11653 let newest_selection = selections
11654 .iter()
11655 .max_by_key(|selection| selection.id)
11656 .unwrap();
11657 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11658 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11659 let snapshot = self.buffer.read(cx).read(cx);
11660 selections
11661 .into_iter()
11662 .map(|mut selection| {
11663 selection.start.0 =
11664 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11665 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11666 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11667 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11668 })
11669 .collect()
11670 }
11671
11672 fn report_editor_event(
11673 &self,
11674 operation: &'static str,
11675 file_extension: Option<String>,
11676 cx: &AppContext,
11677 ) {
11678 if cfg!(any(test, feature = "test-support")) {
11679 return;
11680 }
11681
11682 let Some(project) = &self.project else { return };
11683
11684 // If None, we are in a file without an extension
11685 let file = self
11686 .buffer
11687 .read(cx)
11688 .as_singleton()
11689 .and_then(|b| b.read(cx).file());
11690 let file_extension = file_extension.or(file
11691 .as_ref()
11692 .and_then(|file| Path::new(file.file_name(cx)).extension())
11693 .and_then(|e| e.to_str())
11694 .map(|a| a.to_string()));
11695
11696 let vim_mode = cx
11697 .global::<SettingsStore>()
11698 .raw_user_settings()
11699 .get("vim_mode")
11700 == Some(&serde_json::Value::Bool(true));
11701
11702 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11703 == language::language_settings::InlineCompletionProvider::Copilot;
11704 let copilot_enabled_for_language = self
11705 .buffer
11706 .read(cx)
11707 .settings_at(0, cx)
11708 .show_inline_completions;
11709
11710 let telemetry = project.read(cx).client().telemetry().clone();
11711 telemetry.report_editor_event(
11712 file_extension,
11713 vim_mode,
11714 operation,
11715 copilot_enabled,
11716 copilot_enabled_for_language,
11717 )
11718 }
11719
11720 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11721 /// with each line being an array of {text, highlight} objects.
11722 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11723 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11724 return;
11725 };
11726
11727 #[derive(Serialize)]
11728 struct Chunk<'a> {
11729 text: String,
11730 highlight: Option<&'a str>,
11731 }
11732
11733 let snapshot = buffer.read(cx).snapshot();
11734 let range = self
11735 .selected_text_range(cx)
11736 .and_then(|selected_range| {
11737 if selected_range.is_empty() {
11738 None
11739 } else {
11740 Some(selected_range)
11741 }
11742 })
11743 .unwrap_or_else(|| 0..snapshot.len());
11744
11745 let chunks = snapshot.chunks(range, true);
11746 let mut lines = Vec::new();
11747 let mut line: VecDeque<Chunk> = VecDeque::new();
11748
11749 let Some(style) = self.style.as_ref() else {
11750 return;
11751 };
11752
11753 for chunk in chunks {
11754 let highlight = chunk
11755 .syntax_highlight_id
11756 .and_then(|id| id.name(&style.syntax));
11757 let mut chunk_lines = chunk.text.split('\n').peekable();
11758 while let Some(text) = chunk_lines.next() {
11759 let mut merged_with_last_token = false;
11760 if let Some(last_token) = line.back_mut() {
11761 if last_token.highlight == highlight {
11762 last_token.text.push_str(text);
11763 merged_with_last_token = true;
11764 }
11765 }
11766
11767 if !merged_with_last_token {
11768 line.push_back(Chunk {
11769 text: text.into(),
11770 highlight,
11771 });
11772 }
11773
11774 if chunk_lines.peek().is_some() {
11775 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11776 line.pop_front();
11777 }
11778 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11779 line.pop_back();
11780 }
11781
11782 lines.push(mem::take(&mut line));
11783 }
11784 }
11785 }
11786
11787 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11788 return;
11789 };
11790 cx.write_to_clipboard(ClipboardItem::new_string(lines));
11791 }
11792
11793 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11794 &self.inlay_hint_cache
11795 }
11796
11797 pub fn replay_insert_event(
11798 &mut self,
11799 text: &str,
11800 relative_utf16_range: Option<Range<isize>>,
11801 cx: &mut ViewContext<Self>,
11802 ) {
11803 if !self.input_enabled {
11804 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11805 return;
11806 }
11807 if let Some(relative_utf16_range) = relative_utf16_range {
11808 let selections = self.selections.all::<OffsetUtf16>(cx);
11809 self.change_selections(None, cx, |s| {
11810 let new_ranges = selections.into_iter().map(|range| {
11811 let start = OffsetUtf16(
11812 range
11813 .head()
11814 .0
11815 .saturating_add_signed(relative_utf16_range.start),
11816 );
11817 let end = OffsetUtf16(
11818 range
11819 .head()
11820 .0
11821 .saturating_add_signed(relative_utf16_range.end),
11822 );
11823 start..end
11824 });
11825 s.select_ranges(new_ranges);
11826 });
11827 }
11828
11829 self.handle_input(text, cx);
11830 }
11831
11832 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11833 let Some(project) = self.project.as_ref() else {
11834 return false;
11835 };
11836 let project = project.read(cx);
11837
11838 let mut supports = false;
11839 self.buffer().read(cx).for_each_buffer(|buffer| {
11840 if !supports {
11841 supports = project
11842 .language_servers_for_buffer(buffer.read(cx), cx)
11843 .any(
11844 |(_, server)| match server.capabilities().inlay_hint_provider {
11845 Some(lsp::OneOf::Left(enabled)) => enabled,
11846 Some(lsp::OneOf::Right(_)) => true,
11847 None => false,
11848 },
11849 )
11850 }
11851 });
11852 supports
11853 }
11854
11855 pub fn focus(&self, cx: &mut WindowContext) {
11856 cx.focus(&self.focus_handle)
11857 }
11858
11859 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11860 self.focus_handle.is_focused(cx)
11861 }
11862
11863 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11864 cx.emit(EditorEvent::Focused);
11865
11866 if let Some(descendant) = self
11867 .last_focused_descendant
11868 .take()
11869 .and_then(|descendant| descendant.upgrade())
11870 {
11871 cx.focus(&descendant);
11872 } else {
11873 if let Some(blame) = self.blame.as_ref() {
11874 blame.update(cx, GitBlame::focus)
11875 }
11876
11877 self.blink_manager.update(cx, BlinkManager::enable);
11878 self.show_cursor_names(cx);
11879 self.buffer.update(cx, |buffer, cx| {
11880 buffer.finalize_last_transaction(cx);
11881 if self.leader_peer_id.is_none() {
11882 buffer.set_active_selections(
11883 &self.selections.disjoint_anchors(),
11884 self.selections.line_mode,
11885 self.cursor_shape,
11886 cx,
11887 );
11888 }
11889 });
11890 }
11891 }
11892
11893 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11894 cx.emit(EditorEvent::FocusedIn)
11895 }
11896
11897 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11898 if event.blurred != self.focus_handle {
11899 self.last_focused_descendant = Some(event.blurred);
11900 }
11901 }
11902
11903 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11904 self.blink_manager.update(cx, BlinkManager::disable);
11905 self.buffer
11906 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11907
11908 if let Some(blame) = self.blame.as_ref() {
11909 blame.update(cx, GitBlame::blur)
11910 }
11911 if !self.hover_state.focused(cx) {
11912 hide_hover(self, cx);
11913 }
11914
11915 self.hide_context_menu(cx);
11916 cx.emit(EditorEvent::Blurred);
11917 cx.notify();
11918 }
11919
11920 pub fn register_action<A: Action>(
11921 &mut self,
11922 listener: impl Fn(&A, &mut WindowContext) + 'static,
11923 ) -> Subscription {
11924 let id = self.next_editor_action_id.post_inc();
11925 let listener = Arc::new(listener);
11926 self.editor_actions.borrow_mut().insert(
11927 id,
11928 Box::new(move |cx| {
11929 let cx = cx.window_context();
11930 let listener = listener.clone();
11931 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11932 let action = action.downcast_ref().unwrap();
11933 if phase == DispatchPhase::Bubble {
11934 listener(action, cx)
11935 }
11936 })
11937 }),
11938 );
11939
11940 let editor_actions = self.editor_actions.clone();
11941 Subscription::new(move || {
11942 editor_actions.borrow_mut().remove(&id);
11943 })
11944 }
11945
11946 pub fn file_header_size(&self) -> u32 {
11947 self.file_header_size
11948 }
11949
11950 pub fn revert(
11951 &mut self,
11952 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
11953 cx: &mut ViewContext<Self>,
11954 ) {
11955 self.buffer().update(cx, |multi_buffer, cx| {
11956 for (buffer_id, changes) in revert_changes {
11957 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
11958 buffer.update(cx, |buffer, cx| {
11959 buffer.edit(
11960 changes.into_iter().map(|(range, text)| {
11961 (range, text.to_string().map(Arc::<str>::from))
11962 }),
11963 None,
11964 cx,
11965 );
11966 });
11967 }
11968 }
11969 });
11970 self.change_selections(None, cx, |selections| selections.refresh());
11971 }
11972
11973 pub fn to_pixel_point(
11974 &mut self,
11975 source: multi_buffer::Anchor,
11976 editor_snapshot: &EditorSnapshot,
11977 cx: &mut ViewContext<Self>,
11978 ) -> Option<gpui::Point<Pixels>> {
11979 let source_point = source.to_display_point(editor_snapshot);
11980 self.display_to_pixel_point(source_point, editor_snapshot, cx)
11981 }
11982
11983 pub fn display_to_pixel_point(
11984 &mut self,
11985 source: DisplayPoint,
11986 editor_snapshot: &EditorSnapshot,
11987 cx: &mut ViewContext<Self>,
11988 ) -> Option<gpui::Point<Pixels>> {
11989 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
11990 let text_layout_details = self.text_layout_details(cx);
11991 let scroll_top = text_layout_details
11992 .scroll_anchor
11993 .scroll_position(editor_snapshot)
11994 .y;
11995
11996 if source.row().as_f32() < scroll_top.floor() {
11997 return None;
11998 }
11999 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12000 let source_y = line_height * (source.row().as_f32() - scroll_top);
12001 Some(gpui::Point::new(source_x, source_y))
12002 }
12003
12004 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12005 let bounds = self.last_bounds?;
12006 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12007 }
12008
12009 pub fn has_active_completions_menu(&self) -> bool {
12010 self.context_menu.read().as_ref().map_or(false, |menu| {
12011 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12012 })
12013 }
12014
12015 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12016 self.addons
12017 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12018 }
12019
12020 pub fn unregister_addon<T: Addon>(&mut self) {
12021 self.addons.remove(&std::any::TypeId::of::<T>());
12022 }
12023
12024 pub fn addon<T: Addon>(&self) -> Option<&T> {
12025 let type_id = std::any::TypeId::of::<T>();
12026 self.addons
12027 .get(&type_id)
12028 .and_then(|item| item.to_any().downcast_ref::<T>())
12029 }
12030}
12031
12032fn hunks_for_selections(
12033 multi_buffer_snapshot: &MultiBufferSnapshot,
12034 selections: &[Selection<Anchor>],
12035) -> Vec<DiffHunk<MultiBufferRow>> {
12036 let buffer_rows_for_selections = selections.iter().map(|selection| {
12037 let head = selection.head();
12038 let tail = selection.tail();
12039 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
12040 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
12041 if start > end {
12042 end..start
12043 } else {
12044 start..end
12045 }
12046 });
12047
12048 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12049}
12050
12051pub fn hunks_for_rows(
12052 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12053 multi_buffer_snapshot: &MultiBufferSnapshot,
12054) -> Vec<DiffHunk<MultiBufferRow>> {
12055 let mut hunks = Vec::new();
12056 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12057 HashMap::default();
12058 for selected_multi_buffer_rows in rows {
12059 let query_rows =
12060 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12061 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12062 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12063 // when the caret is just above or just below the deleted hunk.
12064 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12065 let related_to_selection = if allow_adjacent {
12066 hunk.associated_range.overlaps(&query_rows)
12067 || hunk.associated_range.start == query_rows.end
12068 || hunk.associated_range.end == query_rows.start
12069 } else {
12070 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12071 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12072 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12073 || selected_multi_buffer_rows.end == hunk.associated_range.start
12074 };
12075 if related_to_selection {
12076 if !processed_buffer_rows
12077 .entry(hunk.buffer_id)
12078 .or_default()
12079 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12080 {
12081 continue;
12082 }
12083 hunks.push(hunk);
12084 }
12085 }
12086 }
12087
12088 hunks
12089}
12090
12091pub trait CollaborationHub {
12092 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12093 fn user_participant_indices<'a>(
12094 &self,
12095 cx: &'a AppContext,
12096 ) -> &'a HashMap<u64, ParticipantIndex>;
12097 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12098}
12099
12100impl CollaborationHub for Model<Project> {
12101 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12102 self.read(cx).collaborators()
12103 }
12104
12105 fn user_participant_indices<'a>(
12106 &self,
12107 cx: &'a AppContext,
12108 ) -> &'a HashMap<u64, ParticipantIndex> {
12109 self.read(cx).user_store().read(cx).participant_indices()
12110 }
12111
12112 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12113 let this = self.read(cx);
12114 let user_ids = this.collaborators().values().map(|c| c.user_id);
12115 this.user_store().read_with(cx, |user_store, cx| {
12116 user_store.participant_names(user_ids, cx)
12117 })
12118 }
12119}
12120
12121pub trait CompletionProvider {
12122 fn completions(
12123 &self,
12124 buffer: &Model<Buffer>,
12125 buffer_position: text::Anchor,
12126 trigger: CompletionContext,
12127 cx: &mut ViewContext<Editor>,
12128 ) -> Task<Result<Vec<Completion>>>;
12129
12130 fn resolve_completions(
12131 &self,
12132 buffer: Model<Buffer>,
12133 completion_indices: Vec<usize>,
12134 completions: Arc<RwLock<Box<[Completion]>>>,
12135 cx: &mut ViewContext<Editor>,
12136 ) -> Task<Result<bool>>;
12137
12138 fn apply_additional_edits_for_completion(
12139 &self,
12140 buffer: Model<Buffer>,
12141 completion: Completion,
12142 push_to_history: bool,
12143 cx: &mut ViewContext<Editor>,
12144 ) -> Task<Result<Option<language::Transaction>>>;
12145
12146 fn is_completion_trigger(
12147 &self,
12148 buffer: &Model<Buffer>,
12149 position: language::Anchor,
12150 text: &str,
12151 trigger_in_words: bool,
12152 cx: &mut ViewContext<Editor>,
12153 ) -> bool;
12154
12155 fn sort_completions(&self) -> bool {
12156 true
12157 }
12158}
12159
12160fn snippet_completions(
12161 project: &Project,
12162 buffer: &Model<Buffer>,
12163 buffer_position: text::Anchor,
12164 cx: &mut AppContext,
12165) -> Vec<Completion> {
12166 let language = buffer.read(cx).language_at(buffer_position);
12167 let language_name = language.as_ref().map(|language| language.lsp_id());
12168 let snippet_store = project.snippets().read(cx);
12169 let snippets = snippet_store.snippets_for(language_name, cx);
12170
12171 if snippets.is_empty() {
12172 return vec![];
12173 }
12174 let snapshot = buffer.read(cx).text_snapshot();
12175 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12176
12177 let mut lines = chunks.lines();
12178 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12179 return vec![];
12180 };
12181
12182 let scope = language.map(|language| language.default_scope());
12183 let mut last_word = line_at
12184 .chars()
12185 .rev()
12186 .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
12187 .collect::<String>();
12188 last_word = last_word.chars().rev().collect();
12189 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12190 let to_lsp = |point: &text::Anchor| {
12191 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12192 point_to_lsp(end)
12193 };
12194 let lsp_end = to_lsp(&buffer_position);
12195 snippets
12196 .into_iter()
12197 .filter_map(|snippet| {
12198 let matching_prefix = snippet
12199 .prefix
12200 .iter()
12201 .find(|prefix| prefix.starts_with(&last_word))?;
12202 let start = as_offset - last_word.len();
12203 let start = snapshot.anchor_before(start);
12204 let range = start..buffer_position;
12205 let lsp_start = to_lsp(&start);
12206 let lsp_range = lsp::Range {
12207 start: lsp_start,
12208 end: lsp_end,
12209 };
12210 Some(Completion {
12211 old_range: range,
12212 new_text: snippet.body.clone(),
12213 label: CodeLabel {
12214 text: matching_prefix.clone(),
12215 runs: vec![],
12216 filter_range: 0..matching_prefix.len(),
12217 },
12218 server_id: LanguageServerId(usize::MAX),
12219 documentation: snippet
12220 .description
12221 .clone()
12222 .map(|description| Documentation::SingleLine(description)),
12223 lsp_completion: lsp::CompletionItem {
12224 label: snippet.prefix.first().unwrap().clone(),
12225 kind: Some(CompletionItemKind::SNIPPET),
12226 label_details: snippet.description.as_ref().map(|description| {
12227 lsp::CompletionItemLabelDetails {
12228 detail: Some(description.clone()),
12229 description: None,
12230 }
12231 }),
12232 insert_text_format: Some(InsertTextFormat::SNIPPET),
12233 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12234 lsp::InsertReplaceEdit {
12235 new_text: snippet.body.clone(),
12236 insert: lsp_range,
12237 replace: lsp_range,
12238 },
12239 )),
12240 filter_text: Some(snippet.body.clone()),
12241 sort_text: Some(char::MAX.to_string()),
12242 ..Default::default()
12243 },
12244 confirm: None,
12245 })
12246 })
12247 .collect()
12248}
12249
12250impl CompletionProvider for Model<Project> {
12251 fn completions(
12252 &self,
12253 buffer: &Model<Buffer>,
12254 buffer_position: text::Anchor,
12255 options: CompletionContext,
12256 cx: &mut ViewContext<Editor>,
12257 ) -> Task<Result<Vec<Completion>>> {
12258 self.update(cx, |project, cx| {
12259 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12260 let project_completions = project.completions(&buffer, buffer_position, options, cx);
12261 cx.background_executor().spawn(async move {
12262 let mut completions = project_completions.await?;
12263 //let snippets = snippets.into_iter().;
12264 completions.extend(snippets);
12265 Ok(completions)
12266 })
12267 })
12268 }
12269
12270 fn resolve_completions(
12271 &self,
12272 buffer: Model<Buffer>,
12273 completion_indices: Vec<usize>,
12274 completions: Arc<RwLock<Box<[Completion]>>>,
12275 cx: &mut ViewContext<Editor>,
12276 ) -> Task<Result<bool>> {
12277 self.update(cx, |project, cx| {
12278 project.resolve_completions(buffer, completion_indices, completions, cx)
12279 })
12280 }
12281
12282 fn apply_additional_edits_for_completion(
12283 &self,
12284 buffer: Model<Buffer>,
12285 completion: Completion,
12286 push_to_history: bool,
12287 cx: &mut ViewContext<Editor>,
12288 ) -> Task<Result<Option<language::Transaction>>> {
12289 self.update(cx, |project, cx| {
12290 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12291 })
12292 }
12293
12294 fn is_completion_trigger(
12295 &self,
12296 buffer: &Model<Buffer>,
12297 position: language::Anchor,
12298 text: &str,
12299 trigger_in_words: bool,
12300 cx: &mut ViewContext<Editor>,
12301 ) -> bool {
12302 if !EditorSettings::get_global(cx).show_completions_on_input {
12303 return false;
12304 }
12305
12306 let mut chars = text.chars();
12307 let char = if let Some(char) = chars.next() {
12308 char
12309 } else {
12310 return false;
12311 };
12312 if chars.next().is_some() {
12313 return false;
12314 }
12315
12316 let buffer = buffer.read(cx);
12317 let scope = buffer.snapshot().language_scope_at(position);
12318 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12319 return true;
12320 }
12321
12322 buffer
12323 .completion_triggers()
12324 .iter()
12325 .any(|string| string == text)
12326 }
12327}
12328
12329fn inlay_hint_settings(
12330 location: Anchor,
12331 snapshot: &MultiBufferSnapshot,
12332 cx: &mut ViewContext<'_, Editor>,
12333) -> InlayHintSettings {
12334 let file = snapshot.file_at(location);
12335 let language = snapshot.language_at(location);
12336 let settings = all_language_settings(file, cx);
12337 settings
12338 .language(language.map(|l| l.name()).as_deref())
12339 .inlay_hints
12340}
12341
12342fn consume_contiguous_rows(
12343 contiguous_row_selections: &mut Vec<Selection<Point>>,
12344 selection: &Selection<Point>,
12345 display_map: &DisplaySnapshot,
12346 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12347) -> (MultiBufferRow, MultiBufferRow) {
12348 contiguous_row_selections.push(selection.clone());
12349 let start_row = MultiBufferRow(selection.start.row);
12350 let mut end_row = ending_row(selection, display_map);
12351
12352 while let Some(next_selection) = selections.peek() {
12353 if next_selection.start.row <= end_row.0 {
12354 end_row = ending_row(next_selection, display_map);
12355 contiguous_row_selections.push(selections.next().unwrap().clone());
12356 } else {
12357 break;
12358 }
12359 }
12360 (start_row, end_row)
12361}
12362
12363fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12364 if next_selection.end.column > 0 || next_selection.is_empty() {
12365 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12366 } else {
12367 MultiBufferRow(next_selection.end.row)
12368 }
12369}
12370
12371impl EditorSnapshot {
12372 pub fn remote_selections_in_range<'a>(
12373 &'a self,
12374 range: &'a Range<Anchor>,
12375 collaboration_hub: &dyn CollaborationHub,
12376 cx: &'a AppContext,
12377 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12378 let participant_names = collaboration_hub.user_names(cx);
12379 let participant_indices = collaboration_hub.user_participant_indices(cx);
12380 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12381 let collaborators_by_replica_id = collaborators_by_peer_id
12382 .iter()
12383 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12384 .collect::<HashMap<_, _>>();
12385 self.buffer_snapshot
12386 .selections_in_range(range, false)
12387 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12388 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12389 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12390 let user_name = participant_names.get(&collaborator.user_id).cloned();
12391 Some(RemoteSelection {
12392 replica_id,
12393 selection,
12394 cursor_shape,
12395 line_mode,
12396 participant_index,
12397 peer_id: collaborator.peer_id,
12398 user_name,
12399 })
12400 })
12401 }
12402
12403 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12404 self.display_snapshot.buffer_snapshot.language_at(position)
12405 }
12406
12407 pub fn is_focused(&self) -> bool {
12408 self.is_focused
12409 }
12410
12411 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12412 self.placeholder_text.as_ref()
12413 }
12414
12415 pub fn scroll_position(&self) -> gpui::Point<f32> {
12416 self.scroll_anchor.scroll_position(&self.display_snapshot)
12417 }
12418
12419 fn gutter_dimensions(
12420 &self,
12421 font_id: FontId,
12422 font_size: Pixels,
12423 em_width: Pixels,
12424 max_line_number_width: Pixels,
12425 cx: &AppContext,
12426 ) -> GutterDimensions {
12427 if !self.show_gutter {
12428 return GutterDimensions::default();
12429 }
12430 let descent = cx.text_system().descent(font_id, font_size);
12431
12432 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12433 matches!(
12434 ProjectSettings::get_global(cx).git.git_gutter,
12435 Some(GitGutterSetting::TrackedFiles)
12436 )
12437 });
12438 let gutter_settings = EditorSettings::get_global(cx).gutter;
12439 let show_line_numbers = self
12440 .show_line_numbers
12441 .unwrap_or(gutter_settings.line_numbers);
12442 let line_gutter_width = if show_line_numbers {
12443 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12444 let min_width_for_number_on_gutter = em_width * 4.0;
12445 max_line_number_width.max(min_width_for_number_on_gutter)
12446 } else {
12447 0.0.into()
12448 };
12449
12450 let show_code_actions = self
12451 .show_code_actions
12452 .unwrap_or(gutter_settings.code_actions);
12453
12454 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12455
12456 let git_blame_entries_width = self
12457 .render_git_blame_gutter
12458 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12459
12460 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12461 left_padding += if show_code_actions || show_runnables {
12462 em_width * 3.0
12463 } else if show_git_gutter && show_line_numbers {
12464 em_width * 2.0
12465 } else if show_git_gutter || show_line_numbers {
12466 em_width
12467 } else {
12468 px(0.)
12469 };
12470
12471 let right_padding = if gutter_settings.folds && show_line_numbers {
12472 em_width * 4.0
12473 } else if gutter_settings.folds {
12474 em_width * 3.0
12475 } else if show_line_numbers {
12476 em_width
12477 } else {
12478 px(0.)
12479 };
12480
12481 GutterDimensions {
12482 left_padding,
12483 right_padding,
12484 width: line_gutter_width + left_padding + right_padding,
12485 margin: -descent,
12486 git_blame_entries_width,
12487 }
12488 }
12489
12490 pub fn render_fold_toggle(
12491 &self,
12492 buffer_row: MultiBufferRow,
12493 row_contains_cursor: bool,
12494 editor: View<Editor>,
12495 cx: &mut WindowContext,
12496 ) -> Option<AnyElement> {
12497 let folded = self.is_line_folded(buffer_row);
12498
12499 if let Some(crease) = self
12500 .crease_snapshot
12501 .query_row(buffer_row, &self.buffer_snapshot)
12502 {
12503 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12504 if folded {
12505 editor.update(cx, |editor, cx| {
12506 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12507 });
12508 } else {
12509 editor.update(cx, |editor, cx| {
12510 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12511 });
12512 }
12513 });
12514
12515 Some((crease.render_toggle)(
12516 buffer_row,
12517 folded,
12518 toggle_callback,
12519 cx,
12520 ))
12521 } else if folded
12522 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12523 {
12524 Some(
12525 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12526 .selected(folded)
12527 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12528 if folded {
12529 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12530 } else {
12531 this.fold_at(&FoldAt { buffer_row }, cx);
12532 }
12533 }))
12534 .into_any_element(),
12535 )
12536 } else {
12537 None
12538 }
12539 }
12540
12541 pub fn render_crease_trailer(
12542 &self,
12543 buffer_row: MultiBufferRow,
12544 cx: &mut WindowContext,
12545 ) -> Option<AnyElement> {
12546 let folded = self.is_line_folded(buffer_row);
12547 let crease = self
12548 .crease_snapshot
12549 .query_row(buffer_row, &self.buffer_snapshot)?;
12550 Some((crease.render_trailer)(buffer_row, folded, cx))
12551 }
12552}
12553
12554impl Deref for EditorSnapshot {
12555 type Target = DisplaySnapshot;
12556
12557 fn deref(&self) -> &Self::Target {
12558 &self.display_snapshot
12559 }
12560}
12561
12562#[derive(Clone, Debug, PartialEq, Eq)]
12563pub enum EditorEvent {
12564 InputIgnored {
12565 text: Arc<str>,
12566 },
12567 InputHandled {
12568 utf16_range_to_replace: Option<Range<isize>>,
12569 text: Arc<str>,
12570 },
12571 ExcerptsAdded {
12572 buffer: Model<Buffer>,
12573 predecessor: ExcerptId,
12574 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12575 },
12576 ExcerptsRemoved {
12577 ids: Vec<ExcerptId>,
12578 },
12579 ExcerptsEdited {
12580 ids: Vec<ExcerptId>,
12581 },
12582 ExcerptsExpanded {
12583 ids: Vec<ExcerptId>,
12584 },
12585 BufferEdited,
12586 Edited {
12587 transaction_id: clock::Lamport,
12588 },
12589 Reparsed(BufferId),
12590 Focused,
12591 FocusedIn,
12592 Blurred,
12593 DirtyChanged,
12594 Saved,
12595 TitleChanged,
12596 DiffBaseChanged,
12597 SelectionsChanged {
12598 local: bool,
12599 },
12600 ScrollPositionChanged {
12601 local: bool,
12602 autoscroll: bool,
12603 },
12604 Closed,
12605 TransactionUndone {
12606 transaction_id: clock::Lamport,
12607 },
12608 TransactionBegun {
12609 transaction_id: clock::Lamport,
12610 },
12611}
12612
12613impl EventEmitter<EditorEvent> for Editor {}
12614
12615impl FocusableView for Editor {
12616 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12617 self.focus_handle.clone()
12618 }
12619}
12620
12621impl Render for Editor {
12622 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12623 let settings = ThemeSettings::get_global(cx);
12624
12625 let text_style = match self.mode {
12626 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12627 color: cx.theme().colors().editor_foreground,
12628 font_family: settings.ui_font.family.clone(),
12629 font_features: settings.ui_font.features.clone(),
12630 font_fallbacks: settings.ui_font.fallbacks.clone(),
12631 font_size: rems(0.875).into(),
12632 font_weight: settings.ui_font.weight,
12633 line_height: relative(settings.buffer_line_height.value()),
12634 ..Default::default()
12635 },
12636 EditorMode::Full => TextStyle {
12637 color: cx.theme().colors().editor_foreground,
12638 font_family: settings.buffer_font.family.clone(),
12639 font_features: settings.buffer_font.features.clone(),
12640 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12641 font_size: settings.buffer_font_size(cx).into(),
12642 font_weight: settings.buffer_font.weight,
12643 line_height: relative(settings.buffer_line_height.value()),
12644 ..Default::default()
12645 },
12646 };
12647
12648 let background = match self.mode {
12649 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12650 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12651 EditorMode::Full => cx.theme().colors().editor_background,
12652 };
12653
12654 EditorElement::new(
12655 cx.view(),
12656 EditorStyle {
12657 background,
12658 local_player: cx.theme().players().local(),
12659 text: text_style,
12660 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12661 syntax: cx.theme().syntax().clone(),
12662 status: cx.theme().status().clone(),
12663 inlay_hints_style: HighlightStyle {
12664 color: Some(cx.theme().status().hint),
12665 ..HighlightStyle::default()
12666 },
12667 suggestions_style: HighlightStyle {
12668 color: Some(cx.theme().status().predictive),
12669 ..HighlightStyle::default()
12670 },
12671 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
12672 },
12673 )
12674 }
12675}
12676
12677impl ViewInputHandler for Editor {
12678 fn text_for_range(
12679 &mut self,
12680 range_utf16: Range<usize>,
12681 cx: &mut ViewContext<Self>,
12682 ) -> Option<String> {
12683 Some(
12684 self.buffer
12685 .read(cx)
12686 .read(cx)
12687 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12688 .collect(),
12689 )
12690 }
12691
12692 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12693 // Prevent the IME menu from appearing when holding down an alphabetic key
12694 // while input is disabled.
12695 if !self.input_enabled {
12696 return None;
12697 }
12698
12699 let range = self.selections.newest::<OffsetUtf16>(cx).range();
12700 Some(range.start.0..range.end.0)
12701 }
12702
12703 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12704 let snapshot = self.buffer.read(cx).read(cx);
12705 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12706 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12707 }
12708
12709 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12710 self.clear_highlights::<InputComposition>(cx);
12711 self.ime_transaction.take();
12712 }
12713
12714 fn replace_text_in_range(
12715 &mut self,
12716 range_utf16: Option<Range<usize>>,
12717 text: &str,
12718 cx: &mut ViewContext<Self>,
12719 ) {
12720 if !self.input_enabled {
12721 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12722 return;
12723 }
12724
12725 self.transact(cx, |this, cx| {
12726 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12727 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12728 Some(this.selection_replacement_ranges(range_utf16, cx))
12729 } else {
12730 this.marked_text_ranges(cx)
12731 };
12732
12733 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12734 let newest_selection_id = this.selections.newest_anchor().id;
12735 this.selections
12736 .all::<OffsetUtf16>(cx)
12737 .iter()
12738 .zip(ranges_to_replace.iter())
12739 .find_map(|(selection, range)| {
12740 if selection.id == newest_selection_id {
12741 Some(
12742 (range.start.0 as isize - selection.head().0 as isize)
12743 ..(range.end.0 as isize - selection.head().0 as isize),
12744 )
12745 } else {
12746 None
12747 }
12748 })
12749 });
12750
12751 cx.emit(EditorEvent::InputHandled {
12752 utf16_range_to_replace: range_to_replace,
12753 text: text.into(),
12754 });
12755
12756 if let Some(new_selected_ranges) = new_selected_ranges {
12757 this.change_selections(None, cx, |selections| {
12758 selections.select_ranges(new_selected_ranges)
12759 });
12760 this.backspace(&Default::default(), cx);
12761 }
12762
12763 this.handle_input(text, cx);
12764 });
12765
12766 if let Some(transaction) = self.ime_transaction {
12767 self.buffer.update(cx, |buffer, cx| {
12768 buffer.group_until_transaction(transaction, cx);
12769 });
12770 }
12771
12772 self.unmark_text(cx);
12773 }
12774
12775 fn replace_and_mark_text_in_range(
12776 &mut self,
12777 range_utf16: Option<Range<usize>>,
12778 text: &str,
12779 new_selected_range_utf16: Option<Range<usize>>,
12780 cx: &mut ViewContext<Self>,
12781 ) {
12782 if !self.input_enabled {
12783 return;
12784 }
12785
12786 let transaction = self.transact(cx, |this, cx| {
12787 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12788 let snapshot = this.buffer.read(cx).read(cx);
12789 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12790 for marked_range in &mut marked_ranges {
12791 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12792 marked_range.start.0 += relative_range_utf16.start;
12793 marked_range.start =
12794 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12795 marked_range.end =
12796 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12797 }
12798 }
12799 Some(marked_ranges)
12800 } else if let Some(range_utf16) = range_utf16 {
12801 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12802 Some(this.selection_replacement_ranges(range_utf16, cx))
12803 } else {
12804 None
12805 };
12806
12807 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12808 let newest_selection_id = this.selections.newest_anchor().id;
12809 this.selections
12810 .all::<OffsetUtf16>(cx)
12811 .iter()
12812 .zip(ranges_to_replace.iter())
12813 .find_map(|(selection, range)| {
12814 if selection.id == newest_selection_id {
12815 Some(
12816 (range.start.0 as isize - selection.head().0 as isize)
12817 ..(range.end.0 as isize - selection.head().0 as isize),
12818 )
12819 } else {
12820 None
12821 }
12822 })
12823 });
12824
12825 cx.emit(EditorEvent::InputHandled {
12826 utf16_range_to_replace: range_to_replace,
12827 text: text.into(),
12828 });
12829
12830 if let Some(ranges) = ranges_to_replace {
12831 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12832 }
12833
12834 let marked_ranges = {
12835 let snapshot = this.buffer.read(cx).read(cx);
12836 this.selections
12837 .disjoint_anchors()
12838 .iter()
12839 .map(|selection| {
12840 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12841 })
12842 .collect::<Vec<_>>()
12843 };
12844
12845 if text.is_empty() {
12846 this.unmark_text(cx);
12847 } else {
12848 this.highlight_text::<InputComposition>(
12849 marked_ranges.clone(),
12850 HighlightStyle {
12851 underline: Some(UnderlineStyle {
12852 thickness: px(1.),
12853 color: None,
12854 wavy: false,
12855 }),
12856 ..Default::default()
12857 },
12858 cx,
12859 );
12860 }
12861
12862 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12863 let use_autoclose = this.use_autoclose;
12864 let use_auto_surround = this.use_auto_surround;
12865 this.set_use_autoclose(false);
12866 this.set_use_auto_surround(false);
12867 this.handle_input(text, cx);
12868 this.set_use_autoclose(use_autoclose);
12869 this.set_use_auto_surround(use_auto_surround);
12870
12871 if let Some(new_selected_range) = new_selected_range_utf16 {
12872 let snapshot = this.buffer.read(cx).read(cx);
12873 let new_selected_ranges = marked_ranges
12874 .into_iter()
12875 .map(|marked_range| {
12876 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12877 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12878 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12879 snapshot.clip_offset_utf16(new_start, Bias::Left)
12880 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12881 })
12882 .collect::<Vec<_>>();
12883
12884 drop(snapshot);
12885 this.change_selections(None, cx, |selections| {
12886 selections.select_ranges(new_selected_ranges)
12887 });
12888 }
12889 });
12890
12891 self.ime_transaction = self.ime_transaction.or(transaction);
12892 if let Some(transaction) = self.ime_transaction {
12893 self.buffer.update(cx, |buffer, cx| {
12894 buffer.group_until_transaction(transaction, cx);
12895 });
12896 }
12897
12898 if self.text_highlights::<InputComposition>(cx).is_none() {
12899 self.ime_transaction.take();
12900 }
12901 }
12902
12903 fn bounds_for_range(
12904 &mut self,
12905 range_utf16: Range<usize>,
12906 element_bounds: gpui::Bounds<Pixels>,
12907 cx: &mut ViewContext<Self>,
12908 ) -> Option<gpui::Bounds<Pixels>> {
12909 let text_layout_details = self.text_layout_details(cx);
12910 let style = &text_layout_details.editor_style;
12911 let font_id = cx.text_system().resolve_font(&style.text.font());
12912 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12913 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12914
12915 let em_width = cx
12916 .text_system()
12917 .typographic_bounds(font_id, font_size, 'm')
12918 .unwrap()
12919 .size
12920 .width;
12921
12922 let snapshot = self.snapshot(cx);
12923 let scroll_position = snapshot.scroll_position();
12924 let scroll_left = scroll_position.x * em_width;
12925
12926 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12927 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12928 + self.gutter_dimensions.width;
12929 let y = line_height * (start.row().as_f32() - scroll_position.y);
12930
12931 Some(Bounds {
12932 origin: element_bounds.origin + point(x, y),
12933 size: size(em_width, line_height),
12934 })
12935 }
12936}
12937
12938trait SelectionExt {
12939 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12940 fn spanned_rows(
12941 &self,
12942 include_end_if_at_line_start: bool,
12943 map: &DisplaySnapshot,
12944 ) -> Range<MultiBufferRow>;
12945}
12946
12947impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12948 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12949 let start = self
12950 .start
12951 .to_point(&map.buffer_snapshot)
12952 .to_display_point(map);
12953 let end = self
12954 .end
12955 .to_point(&map.buffer_snapshot)
12956 .to_display_point(map);
12957 if self.reversed {
12958 end..start
12959 } else {
12960 start..end
12961 }
12962 }
12963
12964 fn spanned_rows(
12965 &self,
12966 include_end_if_at_line_start: bool,
12967 map: &DisplaySnapshot,
12968 ) -> Range<MultiBufferRow> {
12969 let start = self.start.to_point(&map.buffer_snapshot);
12970 let mut end = self.end.to_point(&map.buffer_snapshot);
12971 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12972 end.row -= 1;
12973 }
12974
12975 let buffer_start = map.prev_line_boundary(start).0;
12976 let buffer_end = map.next_line_boundary(end).0;
12977 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12978 }
12979}
12980
12981impl<T: InvalidationRegion> InvalidationStack<T> {
12982 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12983 where
12984 S: Clone + ToOffset,
12985 {
12986 while let Some(region) = self.last() {
12987 let all_selections_inside_invalidation_ranges =
12988 if selections.len() == region.ranges().len() {
12989 selections
12990 .iter()
12991 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12992 .all(|(selection, invalidation_range)| {
12993 let head = selection.head().to_offset(buffer);
12994 invalidation_range.start <= head && invalidation_range.end >= head
12995 })
12996 } else {
12997 false
12998 };
12999
13000 if all_selections_inside_invalidation_ranges {
13001 break;
13002 } else {
13003 self.pop();
13004 }
13005 }
13006 }
13007}
13008
13009impl<T> Default for InvalidationStack<T> {
13010 fn default() -> Self {
13011 Self(Default::default())
13012 }
13013}
13014
13015impl<T> Deref for InvalidationStack<T> {
13016 type Target = Vec<T>;
13017
13018 fn deref(&self) -> &Self::Target {
13019 &self.0
13020 }
13021}
13022
13023impl<T> DerefMut for InvalidationStack<T> {
13024 fn deref_mut(&mut self) -> &mut Self::Target {
13025 &mut self.0
13026 }
13027}
13028
13029impl InvalidationRegion for SnippetState {
13030 fn ranges(&self) -> &[Range<Anchor>] {
13031 &self.ranges[self.active_index]
13032 }
13033}
13034
13035pub fn diagnostic_block_renderer(
13036 diagnostic: Diagnostic,
13037 max_message_rows: Option<u8>,
13038 allow_closing: bool,
13039 _is_valid: bool,
13040) -> RenderBlock {
13041 let (text_without_backticks, code_ranges) =
13042 highlight_diagnostic_message(&diagnostic, max_message_rows);
13043
13044 Box::new(move |cx: &mut BlockContext| {
13045 let group_id: SharedString = cx.block_id.to_string().into();
13046
13047 let mut text_style = cx.text_style().clone();
13048 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13049 let theme_settings = ThemeSettings::get_global(cx);
13050 text_style.font_family = theme_settings.buffer_font.family.clone();
13051 text_style.font_style = theme_settings.buffer_font.style;
13052 text_style.font_features = theme_settings.buffer_font.features.clone();
13053 text_style.font_weight = theme_settings.buffer_font.weight;
13054
13055 let multi_line_diagnostic = diagnostic.message.contains('\n');
13056
13057 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13058 if multi_line_diagnostic {
13059 v_flex()
13060 } else {
13061 h_flex()
13062 }
13063 .when(allow_closing, |div| {
13064 div.children(diagnostic.is_primary.then(|| {
13065 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13066 .icon_color(Color::Muted)
13067 .size(ButtonSize::Compact)
13068 .style(ButtonStyle::Transparent)
13069 .visible_on_hover(group_id.clone())
13070 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13071 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13072 }))
13073 })
13074 .child(
13075 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13076 .icon_color(Color::Muted)
13077 .size(ButtonSize::Compact)
13078 .style(ButtonStyle::Transparent)
13079 .visible_on_hover(group_id.clone())
13080 .on_click({
13081 let message = diagnostic.message.clone();
13082 move |_click, cx| {
13083 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13084 }
13085 })
13086 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13087 )
13088 };
13089
13090 let icon_size = buttons(&diagnostic, cx.block_id)
13091 .into_any_element()
13092 .layout_as_root(AvailableSpace::min_size(), cx);
13093
13094 h_flex()
13095 .id(cx.block_id)
13096 .group(group_id.clone())
13097 .relative()
13098 .size_full()
13099 .pl(cx.gutter_dimensions.width)
13100 .w(cx.max_width + cx.gutter_dimensions.width)
13101 .child(
13102 div()
13103 .flex()
13104 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13105 .flex_shrink(),
13106 )
13107 .child(buttons(&diagnostic, cx.block_id))
13108 .child(div().flex().flex_shrink_0().child(
13109 StyledText::new(text_without_backticks.clone()).with_highlights(
13110 &text_style,
13111 code_ranges.iter().map(|range| {
13112 (
13113 range.clone(),
13114 HighlightStyle {
13115 font_weight: Some(FontWeight::BOLD),
13116 ..Default::default()
13117 },
13118 )
13119 }),
13120 ),
13121 ))
13122 .into_any_element()
13123 })
13124}
13125
13126pub fn highlight_diagnostic_message(
13127 diagnostic: &Diagnostic,
13128 mut max_message_rows: Option<u8>,
13129) -> (SharedString, Vec<Range<usize>>) {
13130 let mut text_without_backticks = String::new();
13131 let mut code_ranges = Vec::new();
13132
13133 if let Some(source) = &diagnostic.source {
13134 text_without_backticks.push_str(&source);
13135 code_ranges.push(0..source.len());
13136 text_without_backticks.push_str(": ");
13137 }
13138
13139 let mut prev_offset = 0;
13140 let mut in_code_block = false;
13141 let has_row_limit = max_message_rows.is_some();
13142 let mut newline_indices = diagnostic
13143 .message
13144 .match_indices('\n')
13145 .filter(|_| has_row_limit)
13146 .map(|(ix, _)| ix)
13147 .fuse()
13148 .peekable();
13149
13150 for (quote_ix, _) in diagnostic
13151 .message
13152 .match_indices('`')
13153 .chain([(diagnostic.message.len(), "")])
13154 {
13155 let mut first_newline_ix = None;
13156 let mut last_newline_ix = None;
13157 while let Some(newline_ix) = newline_indices.peek() {
13158 if *newline_ix < quote_ix {
13159 if first_newline_ix.is_none() {
13160 first_newline_ix = Some(*newline_ix);
13161 }
13162 last_newline_ix = Some(*newline_ix);
13163
13164 if let Some(rows_left) = &mut max_message_rows {
13165 if *rows_left == 0 {
13166 break;
13167 } else {
13168 *rows_left -= 1;
13169 }
13170 }
13171 let _ = newline_indices.next();
13172 } else {
13173 break;
13174 }
13175 }
13176 let prev_len = text_without_backticks.len();
13177 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13178 text_without_backticks.push_str(new_text);
13179 if in_code_block {
13180 code_ranges.push(prev_len..text_without_backticks.len());
13181 }
13182 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13183 in_code_block = !in_code_block;
13184 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13185 text_without_backticks.push_str("...");
13186 break;
13187 }
13188 }
13189
13190 (text_without_backticks.into(), code_ranges)
13191}
13192
13193fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13194 match severity {
13195 DiagnosticSeverity::ERROR => colors.error,
13196 DiagnosticSeverity::WARNING => colors.warning,
13197 DiagnosticSeverity::INFORMATION => colors.info,
13198 DiagnosticSeverity::HINT => colors.info,
13199 _ => colors.ignored,
13200 }
13201}
13202
13203pub fn styled_runs_for_code_label<'a>(
13204 label: &'a CodeLabel,
13205 syntax_theme: &'a theme::SyntaxTheme,
13206) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13207 let fade_out = HighlightStyle {
13208 fade_out: Some(0.35),
13209 ..Default::default()
13210 };
13211
13212 let mut prev_end = label.filter_range.end;
13213 label
13214 .runs
13215 .iter()
13216 .enumerate()
13217 .flat_map(move |(ix, (range, highlight_id))| {
13218 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13219 style
13220 } else {
13221 return Default::default();
13222 };
13223 let mut muted_style = style;
13224 muted_style.highlight(fade_out);
13225
13226 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13227 if range.start >= label.filter_range.end {
13228 if range.start > prev_end {
13229 runs.push((prev_end..range.start, fade_out));
13230 }
13231 runs.push((range.clone(), muted_style));
13232 } else if range.end <= label.filter_range.end {
13233 runs.push((range.clone(), style));
13234 } else {
13235 runs.push((range.start..label.filter_range.end, style));
13236 runs.push((label.filter_range.end..range.end, muted_style));
13237 }
13238 prev_end = cmp::max(prev_end, range.end);
13239
13240 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13241 runs.push((prev_end..label.text.len(), fade_out));
13242 }
13243
13244 runs
13245 })
13246}
13247
13248pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13249 let mut prev_index = 0;
13250 let mut prev_codepoint: Option<char> = None;
13251 text.char_indices()
13252 .chain([(text.len(), '\0')])
13253 .filter_map(move |(index, codepoint)| {
13254 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13255 let is_boundary = index == text.len()
13256 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13257 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13258 if is_boundary {
13259 let chunk = &text[prev_index..index];
13260 prev_index = index;
13261 Some(chunk)
13262 } else {
13263 None
13264 }
13265 })
13266}
13267
13268pub trait RangeToAnchorExt: Sized {
13269 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13270
13271 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13272 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13273 anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13274 }
13275}
13276
13277impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13278 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13279 let start_offset = self.start.to_offset(snapshot);
13280 let end_offset = self.end.to_offset(snapshot);
13281 if start_offset == end_offset {
13282 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13283 } else {
13284 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13285 }
13286 }
13287}
13288
13289pub trait RowExt {
13290 fn as_f32(&self) -> f32;
13291
13292 fn next_row(&self) -> Self;
13293
13294 fn previous_row(&self) -> Self;
13295
13296 fn minus(&self, other: Self) -> u32;
13297}
13298
13299impl RowExt for DisplayRow {
13300 fn as_f32(&self) -> f32 {
13301 self.0 as f32
13302 }
13303
13304 fn next_row(&self) -> Self {
13305 Self(self.0 + 1)
13306 }
13307
13308 fn previous_row(&self) -> Self {
13309 Self(self.0.saturating_sub(1))
13310 }
13311
13312 fn minus(&self, other: Self) -> u32 {
13313 self.0 - other.0
13314 }
13315}
13316
13317impl RowExt for MultiBufferRow {
13318 fn as_f32(&self) -> f32 {
13319 self.0 as f32
13320 }
13321
13322 fn next_row(&self) -> Self {
13323 Self(self.0 + 1)
13324 }
13325
13326 fn previous_row(&self) -> Self {
13327 Self(self.0.saturating_sub(1))
13328 }
13329
13330 fn minus(&self, other: Self) -> u32 {
13331 self.0 - other.0
13332 }
13333}
13334
13335trait RowRangeExt {
13336 type Row;
13337
13338 fn len(&self) -> usize;
13339
13340 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13341}
13342
13343impl RowRangeExt for Range<MultiBufferRow> {
13344 type Row = MultiBufferRow;
13345
13346 fn len(&self) -> usize {
13347 (self.end.0 - self.start.0) as usize
13348 }
13349
13350 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13351 (self.start.0..self.end.0).map(MultiBufferRow)
13352 }
13353}
13354
13355impl RowRangeExt for Range<DisplayRow> {
13356 type Row = DisplayRow;
13357
13358 fn len(&self) -> usize {
13359 (self.end.0 - self.start.0) as usize
13360 }
13361
13362 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13363 (self.start.0..self.end.0).map(DisplayRow)
13364 }
13365}
13366
13367fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13368 if hunk.diff_base_byte_range.is_empty() {
13369 DiffHunkStatus::Added
13370 } else if hunk.associated_range.is_empty() {
13371 DiffHunkStatus::Removed
13372 } else {
13373 DiffHunkStatus::Modified
13374 }
13375}
13376
13377/// If select range has more than one line, we
13378/// just point the cursor to range.start.
13379fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13380 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13381 range
13382 } else {
13383 range.start..range.start
13384 }
13385}