1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31mod inline_completion_provider;
32pub mod items;
33mod linked_editing_ranges;
34mod lsp_ext;
35mod mouse_context_menu;
36pub mod movement;
37mod persistence;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45mod signature_help;
46#[cfg(any(test, feature = "test-support"))]
47pub mod test;
48
49use ::git::diff::{DiffHunk, DiffHunkStatus};
50use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
51pub(crate) use actions::*;
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use client::{Collaborator, ParticipantIndex};
56use clock::ReplicaId;
57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
58use convert_case::{Case, Casing};
59use debounced_delay::DebouncedDelay;
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{CurrentLineHighlight, EditorSettings};
63pub use editor_settings_controls::*;
64use element::LineWithInvisibles;
65pub use element::{
66 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
67};
68use futures::FutureExt;
69use fuzzy::{StringMatch, StringMatchCandidate};
70use git::blame::GitBlame;
71use git::diff_hunk_to_display;
72use gpui::{
73 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
74 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
75 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
76 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
77 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
78 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
79 UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext,
80 WeakFocusHandle, WeakView, WindowContext,
81};
82use highlight_matching_bracket::refresh_matching_bracket_highlights;
83use hover_popover::{hide_hover, HoverState};
84use hunk_diff::ExpandedHunks;
85pub(crate) use hunk_diff::HoveredHunk;
86use indent_guides::ActiveIndentGuidesState;
87use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
88pub use inline_completion_provider::*;
89pub use items::MAX_TAB_TITLE_LEN;
90use itertools::Itertools;
91use language::{
92 char_kind,
93 language_settings::{self, all_language_settings, InlayHintSettings},
94 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
95 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
96 Point, Selection, SelectionGoal, TransactionId,
97};
98use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
99use linked_editing_ranges::refresh_linked_ranges;
100use task::{ResolvedTask, TaskTemplate, TaskVariables};
101
102use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
103pub use lsp::CompletionContext;
104use lsp::{
105 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
106 LanguageServerId,
107};
108use mouse_context_menu::MouseContextMenu;
109use movement::TextLayoutDetails;
110pub use multi_buffer::{
111 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
112 ToPoint,
113};
114use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
115use ordered_float::OrderedFloat;
116use parking_lot::{Mutex, RwLock};
117use project::project_settings::{GitGutterSetting, ProjectSettings};
118use project::{
119 CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
120 ProjectTransaction, TaskSourceKind, WorktreeId,
121};
122use rand::prelude::*;
123use rpc::{proto::*, ErrorExt};
124use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
125use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
126use serde::{Deserialize, Serialize};
127use settings::{update_settings_file, Settings, SettingsStore};
128use smallvec::SmallVec;
129use snippet::Snippet;
130use std::{
131 any::TypeId,
132 borrow::Cow,
133 cell::RefCell,
134 cmp::{self, Ordering, Reverse},
135 mem,
136 num::NonZeroU32,
137 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
138 path::{Path, PathBuf},
139 rc::Rc,
140 sync::Arc,
141 time::{Duration, Instant},
142};
143pub use sum_tree::Bias;
144use sum_tree::TreeMap;
145use text::{BufferId, OffsetUtf16, Rope};
146use theme::{
147 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
148 ThemeColors, ThemeSettings,
149};
150use ui::{
151 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
152 ListItem, Popover, Tooltip,
153};
154use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
155use workspace::item::{ItemHandle, PreviewTabsSettings};
156use workspace::notifications::{DetachAndPromptErr, NotificationId};
157use workspace::{
158 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
159};
160use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
161
162use crate::hover_links::find_url;
163use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
164
165pub const FILE_HEADER_HEIGHT: u32 = 1;
166pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
167pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
168pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
169const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
170const MAX_LINE_LEN: usize = 1024;
171const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
172const MAX_SELECTION_HISTORY_LEN: usize = 1024;
173pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
174#[doc(hidden)]
175pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
176#[doc(hidden)]
177pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
178
179pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
180pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
181
182pub fn render_parsed_markdown(
183 element_id: impl Into<ElementId>,
184 parsed: &language::ParsedMarkdown,
185 editor_style: &EditorStyle,
186 workspace: Option<WeakView<Workspace>>,
187 cx: &mut WindowContext,
188) -> InteractiveText {
189 let code_span_background_color = cx
190 .theme()
191 .colors()
192 .editor_document_highlight_read_background;
193
194 let highlights = gpui::combine_highlights(
195 parsed.highlights.iter().filter_map(|(range, highlight)| {
196 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
197 Some((range.clone(), highlight))
198 }),
199 parsed
200 .regions
201 .iter()
202 .zip(&parsed.region_ranges)
203 .filter_map(|(region, range)| {
204 if region.code {
205 Some((
206 range.clone(),
207 HighlightStyle {
208 background_color: Some(code_span_background_color),
209 ..Default::default()
210 },
211 ))
212 } else {
213 None
214 }
215 }),
216 );
217
218 let mut links = Vec::new();
219 let mut link_ranges = Vec::new();
220 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
221 if let Some(link) = region.link.clone() {
222 links.push(link);
223 link_ranges.push(range.clone());
224 }
225 }
226
227 InteractiveText::new(
228 element_id,
229 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
230 )
231 .on_click(link_ranges, move |clicked_range_ix, cx| {
232 match &links[clicked_range_ix] {
233 markdown::Link::Web { url } => cx.open_url(url),
234 markdown::Link::Path { path } => {
235 if let Some(workspace) = &workspace {
236 _ = workspace.update(cx, |workspace, cx| {
237 workspace.open_abs_path(path.clone(), false, cx).detach();
238 });
239 }
240 }
241 }
242 })
243}
244
245#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
246pub(crate) enum InlayId {
247 Suggestion(usize),
248 Hint(usize),
249}
250
251impl InlayId {
252 fn id(&self) -> usize {
253 match self {
254 Self::Suggestion(id) => *id,
255 Self::Hint(id) => *id,
256 }
257 }
258}
259
260enum DiffRowHighlight {}
261enum DocumentHighlightRead {}
262enum DocumentHighlightWrite {}
263enum InputComposition {}
264
265#[derive(Copy, Clone, PartialEq, Eq)]
266pub enum Direction {
267 Prev,
268 Next,
269}
270
271#[derive(Debug, Copy, Clone, PartialEq, Eq)]
272pub enum Navigated {
273 Yes,
274 No,
275}
276
277impl Navigated {
278 pub fn from_bool(yes: bool) -> Navigated {
279 if yes {
280 Navigated::Yes
281 } else {
282 Navigated::No
283 }
284 }
285}
286
287pub fn init_settings(cx: &mut AppContext) {
288 EditorSettings::register(cx);
289}
290
291pub fn init(cx: &mut AppContext) {
292 init_settings(cx);
293
294 workspace::register_project_item::<Editor>(cx);
295 workspace::FollowableViewRegistry::register::<Editor>(cx);
296 workspace::register_serializable_item::<Editor>(cx);
297
298 cx.observe_new_views(
299 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
300 workspace.register_action(Editor::new_file);
301 workspace.register_action(Editor::new_file_in_direction);
302 },
303 )
304 .detach();
305
306 cx.on_action(move |_: &workspace::NewFile, cx| {
307 let app_state = workspace::AppState::global(cx);
308 if let Some(app_state) = app_state.upgrade() {
309 workspace::open_new(app_state, cx, |workspace, cx| {
310 Editor::new_file(workspace, &Default::default(), cx)
311 })
312 .detach();
313 }
314 });
315 cx.on_action(move |_: &workspace::NewWindow, cx| {
316 let app_state = workspace::AppState::global(cx);
317 if let Some(app_state) = app_state.upgrade() {
318 workspace::open_new(app_state, cx, |workspace, cx| {
319 Editor::new_file(workspace, &Default::default(), cx)
320 })
321 .detach();
322 }
323 });
324}
325
326pub struct SearchWithinRange;
327
328trait InvalidationRegion {
329 fn ranges(&self) -> &[Range<Anchor>];
330}
331
332#[derive(Clone, Debug, PartialEq)]
333pub enum SelectPhase {
334 Begin {
335 position: DisplayPoint,
336 add: bool,
337 click_count: usize,
338 },
339 BeginColumnar {
340 position: DisplayPoint,
341 reset: bool,
342 goal_column: u32,
343 },
344 Extend {
345 position: DisplayPoint,
346 click_count: usize,
347 },
348 Update {
349 position: DisplayPoint,
350 goal_column: u32,
351 scroll_delta: gpui::Point<f32>,
352 },
353 End,
354}
355
356#[derive(Clone, Debug)]
357pub enum SelectMode {
358 Character,
359 Word(Range<Anchor>),
360 Line(Range<Anchor>),
361 All,
362}
363
364#[derive(Copy, Clone, PartialEq, Eq, Debug)]
365pub enum EditorMode {
366 SingleLine { auto_width: bool },
367 AutoHeight { max_lines: usize },
368 Full,
369}
370
371#[derive(Clone, Debug)]
372pub enum SoftWrap {
373 None,
374 PreferLine,
375 EditorWidth,
376 Column(u32),
377}
378
379#[derive(Clone)]
380pub struct EditorStyle {
381 pub background: Hsla,
382 pub local_player: PlayerColor,
383 pub text: TextStyle,
384 pub scrollbar_width: Pixels,
385 pub syntax: Arc<SyntaxTheme>,
386 pub status: StatusColors,
387 pub inlay_hints_style: HighlightStyle,
388 pub suggestions_style: HighlightStyle,
389 pub unnecessary_code_fade: f32,
390}
391
392impl Default for EditorStyle {
393 fn default() -> Self {
394 Self {
395 background: Hsla::default(),
396 local_player: PlayerColor::default(),
397 text: TextStyle::default(),
398 scrollbar_width: Pixels::default(),
399 syntax: Default::default(),
400 // HACK: Status colors don't have a real default.
401 // We should look into removing the status colors from the editor
402 // style and retrieve them directly from the theme.
403 status: StatusColors::dark(),
404 inlay_hints_style: HighlightStyle::default(),
405 suggestions_style: HighlightStyle::default(),
406 unnecessary_code_fade: Default::default(),
407 }
408 }
409}
410
411type CompletionId = usize;
412
413#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
414struct EditorActionId(usize);
415
416impl EditorActionId {
417 pub fn post_inc(&mut self) -> Self {
418 let answer = self.0;
419
420 *self = Self(answer + 1);
421
422 Self(answer)
423 }
424}
425
426// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
427// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
428
429type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
430type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
431
432#[derive(Default)]
433struct ScrollbarMarkerState {
434 scrollbar_size: Size<Pixels>,
435 dirty: bool,
436 markers: Arc<[PaintQuad]>,
437 pending_refresh: Option<Task<Result<()>>>,
438}
439
440impl ScrollbarMarkerState {
441 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
442 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
443 }
444}
445
446#[derive(Clone, Debug)]
447struct RunnableTasks {
448 templates: Vec<(TaskSourceKind, TaskTemplate)>,
449 offset: MultiBufferOffset,
450 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
451 column: u32,
452 // Values of all named captures, including those starting with '_'
453 extra_variables: HashMap<String, String>,
454 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
455 context_range: Range<BufferOffset>,
456}
457
458#[derive(Clone)]
459struct ResolvedTasks {
460 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
461 position: Anchor,
462}
463#[derive(Copy, Clone, Debug)]
464struct MultiBufferOffset(usize);
465#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
466struct BufferOffset(usize);
467
468// Addons allow storing per-editor state in other crates (e.g. Vim)
469pub trait Addon: 'static {
470 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
471
472 fn to_any(&self) -> &dyn std::any::Any;
473}
474
475/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
476///
477/// See the [module level documentation](self) for more information.
478pub struct Editor {
479 focus_handle: FocusHandle,
480 last_focused_descendant: Option<WeakFocusHandle>,
481 /// The text buffer being edited
482 buffer: Model<MultiBuffer>,
483 /// Map of how text in the buffer should be displayed.
484 /// Handles soft wraps, folds, fake inlay text insertions, etc.
485 pub display_map: Model<DisplayMap>,
486 pub selections: SelectionsCollection,
487 pub scroll_manager: ScrollManager,
488 /// When inline assist editors are linked, they all render cursors because
489 /// typing enters text into each of them, even the ones that aren't focused.
490 pub(crate) show_cursor_when_unfocused: bool,
491 columnar_selection_tail: Option<Anchor>,
492 add_selections_state: Option<AddSelectionsState>,
493 select_next_state: Option<SelectNextState>,
494 select_prev_state: Option<SelectNextState>,
495 selection_history: SelectionHistory,
496 autoclose_regions: Vec<AutocloseRegion>,
497 snippet_stack: InvalidationStack<SnippetState>,
498 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
499 ime_transaction: Option<TransactionId>,
500 active_diagnostics: Option<ActiveDiagnosticGroup>,
501 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
502 project: Option<Model<Project>>,
503 completion_provider: Option<Box<dyn CompletionProvider>>,
504 collaboration_hub: Option<Box<dyn CollaborationHub>>,
505 blink_manager: Model<BlinkManager>,
506 show_cursor_names: bool,
507 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
508 pub show_local_selections: bool,
509 mode: EditorMode,
510 show_breadcrumbs: bool,
511 show_gutter: bool,
512 show_line_numbers: Option<bool>,
513 show_git_diff_gutter: Option<bool>,
514 show_code_actions: Option<bool>,
515 show_runnables: Option<bool>,
516 show_wrap_guides: Option<bool>,
517 show_indent_guides: Option<bool>,
518 placeholder_text: Option<Arc<str>>,
519 highlight_order: usize,
520 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
521 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
522 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
523 scrollbar_marker_state: ScrollbarMarkerState,
524 active_indent_guides_state: ActiveIndentGuidesState,
525 nav_history: Option<ItemNavHistory>,
526 context_menu: RwLock<Option<ContextMenu>>,
527 mouse_context_menu: Option<MouseContextMenu>,
528 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
529 signature_help_state: SignatureHelpState,
530 auto_signature_help: Option<bool>,
531 find_all_references_task_sources: Vec<Anchor>,
532 next_completion_id: CompletionId,
533 completion_documentation_pre_resolve_debounce: DebouncedDelay,
534 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
535 code_actions_task: Option<Task<()>>,
536 document_highlights_task: Option<Task<()>>,
537 linked_editing_range_task: Option<Task<Option<()>>>,
538 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
539 pending_rename: Option<RenameState>,
540 searchable: bool,
541 cursor_shape: CursorShape,
542 current_line_highlight: Option<CurrentLineHighlight>,
543 collapse_matches: bool,
544 autoindent_mode: Option<AutoindentMode>,
545 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
546 input_enabled: bool,
547 use_modal_editing: bool,
548 read_only: bool,
549 leader_peer_id: Option<PeerId>,
550 remote_id: Option<ViewId>,
551 hover_state: HoverState,
552 gutter_hovered: bool,
553 hovered_link_state: Option<HoveredLinkState>,
554 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
555 active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
556 show_inline_completions: bool,
557 inlay_hint_cache: InlayHintCache,
558 expanded_hunks: ExpandedHunks,
559 next_inlay_id: usize,
560 _subscriptions: Vec<Subscription>,
561 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
562 gutter_dimensions: GutterDimensions,
563 style: Option<EditorStyle>,
564 next_editor_action_id: EditorActionId,
565 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
566 use_autoclose: bool,
567 use_auto_surround: bool,
568 auto_replace_emoji_shortcode: bool,
569 show_git_blame_gutter: bool,
570 show_git_blame_inline: bool,
571 show_git_blame_inline_delay_task: Option<Task<()>>,
572 git_blame_inline_enabled: bool,
573 serialize_dirty_buffers: bool,
574 show_selection_menu: Option<bool>,
575 blame: Option<Model<GitBlame>>,
576 blame_subscription: Option<Subscription>,
577 custom_context_menu: Option<
578 Box<
579 dyn 'static
580 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
581 >,
582 >,
583 last_bounds: Option<Bounds<Pixels>>,
584 expect_bounds_change: Option<Bounds<Pixels>>,
585 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
586 tasks_update_task: Option<Task<()>>,
587 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
588 file_header_size: u32,
589 breadcrumb_header: Option<String>,
590 focused_block: Option<FocusedBlock>,
591 next_scroll_position: NextScrollCursorCenterTopBottom,
592 addons: HashMap<TypeId, Box<dyn Addon>>,
593 _scroll_cursor_center_top_bottom_task: Task<()>,
594}
595
596#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
597enum NextScrollCursorCenterTopBottom {
598 #[default]
599 Center,
600 Top,
601 Bottom,
602}
603
604impl NextScrollCursorCenterTopBottom {
605 fn next(&self) -> Self {
606 match self {
607 Self::Center => Self::Top,
608 Self::Top => Self::Bottom,
609 Self::Bottom => Self::Center,
610 }
611 }
612}
613
614#[derive(Clone)]
615pub struct EditorSnapshot {
616 pub mode: EditorMode,
617 show_gutter: bool,
618 show_line_numbers: Option<bool>,
619 show_git_diff_gutter: Option<bool>,
620 show_code_actions: Option<bool>,
621 show_runnables: Option<bool>,
622 render_git_blame_gutter: bool,
623 pub display_snapshot: DisplaySnapshot,
624 pub placeholder_text: Option<Arc<str>>,
625 is_focused: bool,
626 scroll_anchor: ScrollAnchor,
627 ongoing_scroll: OngoingScroll,
628 current_line_highlight: CurrentLineHighlight,
629 gutter_hovered: bool,
630}
631
632const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
633
634#[derive(Default, Debug, Clone, Copy)]
635pub struct GutterDimensions {
636 pub left_padding: Pixels,
637 pub right_padding: Pixels,
638 pub width: Pixels,
639 pub margin: Pixels,
640 pub git_blame_entries_width: Option<Pixels>,
641}
642
643impl GutterDimensions {
644 /// The full width of the space taken up by the gutter.
645 pub fn full_width(&self) -> Pixels {
646 self.margin + self.width
647 }
648
649 /// The width of the space reserved for the fold indicators,
650 /// use alongside 'justify_end' and `gutter_width` to
651 /// right align content with the line numbers
652 pub fn fold_area_width(&self) -> Pixels {
653 self.margin + self.right_padding
654 }
655}
656
657#[derive(Debug)]
658pub struct RemoteSelection {
659 pub replica_id: ReplicaId,
660 pub selection: Selection<Anchor>,
661 pub cursor_shape: CursorShape,
662 pub peer_id: PeerId,
663 pub line_mode: bool,
664 pub participant_index: Option<ParticipantIndex>,
665 pub user_name: Option<SharedString>,
666}
667
668#[derive(Clone, Debug)]
669struct SelectionHistoryEntry {
670 selections: Arc<[Selection<Anchor>]>,
671 select_next_state: Option<SelectNextState>,
672 select_prev_state: Option<SelectNextState>,
673 add_selections_state: Option<AddSelectionsState>,
674}
675
676enum SelectionHistoryMode {
677 Normal,
678 Undoing,
679 Redoing,
680}
681
682#[derive(Clone, PartialEq, Eq, Hash)]
683struct HoveredCursor {
684 replica_id: u16,
685 selection_id: usize,
686}
687
688impl Default for SelectionHistoryMode {
689 fn default() -> Self {
690 Self::Normal
691 }
692}
693
694#[derive(Default)]
695struct SelectionHistory {
696 #[allow(clippy::type_complexity)]
697 selections_by_transaction:
698 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
699 mode: SelectionHistoryMode,
700 undo_stack: VecDeque<SelectionHistoryEntry>,
701 redo_stack: VecDeque<SelectionHistoryEntry>,
702}
703
704impl SelectionHistory {
705 fn insert_transaction(
706 &mut self,
707 transaction_id: TransactionId,
708 selections: Arc<[Selection<Anchor>]>,
709 ) {
710 self.selections_by_transaction
711 .insert(transaction_id, (selections, None));
712 }
713
714 #[allow(clippy::type_complexity)]
715 fn transaction(
716 &self,
717 transaction_id: TransactionId,
718 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
719 self.selections_by_transaction.get(&transaction_id)
720 }
721
722 #[allow(clippy::type_complexity)]
723 fn transaction_mut(
724 &mut self,
725 transaction_id: TransactionId,
726 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
727 self.selections_by_transaction.get_mut(&transaction_id)
728 }
729
730 fn push(&mut self, entry: SelectionHistoryEntry) {
731 if !entry.selections.is_empty() {
732 match self.mode {
733 SelectionHistoryMode::Normal => {
734 self.push_undo(entry);
735 self.redo_stack.clear();
736 }
737 SelectionHistoryMode::Undoing => self.push_redo(entry),
738 SelectionHistoryMode::Redoing => self.push_undo(entry),
739 }
740 }
741 }
742
743 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
744 if self
745 .undo_stack
746 .back()
747 .map_or(true, |e| e.selections != entry.selections)
748 {
749 self.undo_stack.push_back(entry);
750 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
751 self.undo_stack.pop_front();
752 }
753 }
754 }
755
756 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
757 if self
758 .redo_stack
759 .back()
760 .map_or(true, |e| e.selections != entry.selections)
761 {
762 self.redo_stack.push_back(entry);
763 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
764 self.redo_stack.pop_front();
765 }
766 }
767 }
768}
769
770struct RowHighlight {
771 index: usize,
772 range: RangeInclusive<Anchor>,
773 color: Option<Hsla>,
774 should_autoscroll: bool,
775}
776
777#[derive(Clone, Debug)]
778struct AddSelectionsState {
779 above: bool,
780 stack: Vec<usize>,
781}
782
783#[derive(Clone)]
784struct SelectNextState {
785 query: AhoCorasick,
786 wordwise: bool,
787 done: bool,
788}
789
790impl std::fmt::Debug for SelectNextState {
791 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
792 f.debug_struct(std::any::type_name::<Self>())
793 .field("wordwise", &self.wordwise)
794 .field("done", &self.done)
795 .finish()
796 }
797}
798
799#[derive(Debug)]
800struct AutocloseRegion {
801 selection_id: usize,
802 range: Range<Anchor>,
803 pair: BracketPair,
804}
805
806#[derive(Debug)]
807struct SnippetState {
808 ranges: Vec<Vec<Range<Anchor>>>,
809 active_index: usize,
810}
811
812#[doc(hidden)]
813pub struct RenameState {
814 pub range: Range<Anchor>,
815 pub old_name: Arc<str>,
816 pub editor: View<Editor>,
817 block_id: CustomBlockId,
818}
819
820struct InvalidationStack<T>(Vec<T>);
821
822struct RegisteredInlineCompletionProvider {
823 provider: Arc<dyn InlineCompletionProviderHandle>,
824 _subscription: Subscription,
825}
826
827enum ContextMenu {
828 Completions(CompletionsMenu),
829 CodeActions(CodeActionsMenu),
830}
831
832impl ContextMenu {
833 fn select_first(
834 &mut self,
835 project: Option<&Model<Project>>,
836 cx: &mut ViewContext<Editor>,
837 ) -> bool {
838 if self.visible() {
839 match self {
840 ContextMenu::Completions(menu) => menu.select_first(project, cx),
841 ContextMenu::CodeActions(menu) => menu.select_first(cx),
842 }
843 true
844 } else {
845 false
846 }
847 }
848
849 fn select_prev(
850 &mut self,
851 project: Option<&Model<Project>>,
852 cx: &mut ViewContext<Editor>,
853 ) -> bool {
854 if self.visible() {
855 match self {
856 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
857 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
858 }
859 true
860 } else {
861 false
862 }
863 }
864
865 fn select_next(
866 &mut self,
867 project: Option<&Model<Project>>,
868 cx: &mut ViewContext<Editor>,
869 ) -> bool {
870 if self.visible() {
871 match self {
872 ContextMenu::Completions(menu) => menu.select_next(project, cx),
873 ContextMenu::CodeActions(menu) => menu.select_next(cx),
874 }
875 true
876 } else {
877 false
878 }
879 }
880
881 fn select_last(
882 &mut self,
883 project: Option<&Model<Project>>,
884 cx: &mut ViewContext<Editor>,
885 ) -> bool {
886 if self.visible() {
887 match self {
888 ContextMenu::Completions(menu) => menu.select_last(project, cx),
889 ContextMenu::CodeActions(menu) => menu.select_last(cx),
890 }
891 true
892 } else {
893 false
894 }
895 }
896
897 fn visible(&self) -> bool {
898 match self {
899 ContextMenu::Completions(menu) => menu.visible(),
900 ContextMenu::CodeActions(menu) => menu.visible(),
901 }
902 }
903
904 fn render(
905 &self,
906 cursor_position: DisplayPoint,
907 style: &EditorStyle,
908 max_height: Pixels,
909 workspace: Option<WeakView<Workspace>>,
910 cx: &mut ViewContext<Editor>,
911 ) -> (ContextMenuOrigin, AnyElement) {
912 match self {
913 ContextMenu::Completions(menu) => (
914 ContextMenuOrigin::EditorPoint(cursor_position),
915 menu.render(style, max_height, workspace, cx),
916 ),
917 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
918 }
919 }
920}
921
922enum ContextMenuOrigin {
923 EditorPoint(DisplayPoint),
924 GutterIndicator(DisplayRow),
925}
926
927#[derive(Clone)]
928struct CompletionsMenu {
929 id: CompletionId,
930 sort_completions: bool,
931 initial_position: Anchor,
932 buffer: Model<Buffer>,
933 completions: Arc<RwLock<Box<[Completion]>>>,
934 match_candidates: Arc<[StringMatchCandidate]>,
935 matches: Arc<[StringMatch]>,
936 selected_item: usize,
937 scroll_handle: UniformListScrollHandle,
938 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
939}
940
941impl CompletionsMenu {
942 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
943 self.selected_item = 0;
944 self.scroll_handle.scroll_to_item(self.selected_item);
945 self.attempt_resolve_selected_completion_documentation(project, cx);
946 cx.notify();
947 }
948
949 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
950 if self.selected_item > 0 {
951 self.selected_item -= 1;
952 } else {
953 self.selected_item = self.matches.len() - 1;
954 }
955 self.scroll_handle.scroll_to_item(self.selected_item);
956 self.attempt_resolve_selected_completion_documentation(project, cx);
957 cx.notify();
958 }
959
960 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
961 if self.selected_item + 1 < self.matches.len() {
962 self.selected_item += 1;
963 } else {
964 self.selected_item = 0;
965 }
966 self.scroll_handle.scroll_to_item(self.selected_item);
967 self.attempt_resolve_selected_completion_documentation(project, cx);
968 cx.notify();
969 }
970
971 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
972 self.selected_item = self.matches.len() - 1;
973 self.scroll_handle.scroll_to_item(self.selected_item);
974 self.attempt_resolve_selected_completion_documentation(project, cx);
975 cx.notify();
976 }
977
978 fn pre_resolve_completion_documentation(
979 buffer: Model<Buffer>,
980 completions: Arc<RwLock<Box<[Completion]>>>,
981 matches: Arc<[StringMatch]>,
982 editor: &Editor,
983 cx: &mut ViewContext<Editor>,
984 ) -> Task<()> {
985 let settings = EditorSettings::get_global(cx);
986 if !settings.show_completion_documentation {
987 return Task::ready(());
988 }
989
990 let Some(provider) = editor.completion_provider.as_ref() else {
991 return Task::ready(());
992 };
993
994 let resolve_task = provider.resolve_completions(
995 buffer,
996 matches.iter().map(|m| m.candidate_id).collect(),
997 completions.clone(),
998 cx,
999 );
1000
1001 return cx.spawn(move |this, mut cx| async move {
1002 if let Some(true) = resolve_task.await.log_err() {
1003 this.update(&mut cx, |_, cx| cx.notify()).ok();
1004 }
1005 });
1006 }
1007
1008 fn attempt_resolve_selected_completion_documentation(
1009 &mut self,
1010 project: Option<&Model<Project>>,
1011 cx: &mut ViewContext<Editor>,
1012 ) {
1013 let settings = EditorSettings::get_global(cx);
1014 if !settings.show_completion_documentation {
1015 return;
1016 }
1017
1018 let completion_index = self.matches[self.selected_item].candidate_id;
1019 let Some(project) = project else {
1020 return;
1021 };
1022
1023 let resolve_task = project.update(cx, |project, cx| {
1024 project.resolve_completions(
1025 self.buffer.clone(),
1026 vec![completion_index],
1027 self.completions.clone(),
1028 cx,
1029 )
1030 });
1031
1032 let delay_ms =
1033 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1034 let delay = Duration::from_millis(delay_ms);
1035
1036 self.selected_completion_documentation_resolve_debounce
1037 .lock()
1038 .fire_new(delay, cx, |_, cx| {
1039 cx.spawn(move |this, mut cx| async move {
1040 if let Some(true) = resolve_task.await.log_err() {
1041 this.update(&mut cx, |_, cx| cx.notify()).ok();
1042 }
1043 })
1044 });
1045 }
1046
1047 fn visible(&self) -> bool {
1048 !self.matches.is_empty()
1049 }
1050
1051 fn render(
1052 &self,
1053 style: &EditorStyle,
1054 max_height: Pixels,
1055 workspace: Option<WeakView<Workspace>>,
1056 cx: &mut ViewContext<Editor>,
1057 ) -> AnyElement {
1058 let settings = EditorSettings::get_global(cx);
1059 let show_completion_documentation = settings.show_completion_documentation;
1060
1061 let widest_completion_ix = self
1062 .matches
1063 .iter()
1064 .enumerate()
1065 .max_by_key(|(_, mat)| {
1066 let completions = self.completions.read();
1067 let completion = &completions[mat.candidate_id];
1068 let documentation = &completion.documentation;
1069
1070 let mut len = completion.label.text.chars().count();
1071 if let Some(Documentation::SingleLine(text)) = documentation {
1072 if show_completion_documentation {
1073 len += text.chars().count();
1074 }
1075 }
1076
1077 len
1078 })
1079 .map(|(ix, _)| ix);
1080
1081 let completions = self.completions.clone();
1082 let matches = self.matches.clone();
1083 let selected_item = self.selected_item;
1084 let style = style.clone();
1085
1086 let multiline_docs = if show_completion_documentation {
1087 let mat = &self.matches[selected_item];
1088 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1089 Some(Documentation::MultiLinePlainText(text)) => {
1090 Some(div().child(SharedString::from(text.clone())))
1091 }
1092 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1093 Some(div().child(render_parsed_markdown(
1094 "completions_markdown",
1095 parsed,
1096 &style,
1097 workspace,
1098 cx,
1099 )))
1100 }
1101 _ => None,
1102 };
1103 multiline_docs.map(|div| {
1104 div.id("multiline_docs")
1105 .max_h(max_height)
1106 .flex_1()
1107 .px_1p5()
1108 .py_1()
1109 .min_w(px(260.))
1110 .max_w(px(640.))
1111 .w(px(500.))
1112 .overflow_y_scroll()
1113 .occlude()
1114 })
1115 } else {
1116 None
1117 };
1118
1119 let list = uniform_list(
1120 cx.view().clone(),
1121 "completions",
1122 matches.len(),
1123 move |_editor, range, cx| {
1124 let start_ix = range.start;
1125 let completions_guard = completions.read();
1126
1127 matches[range]
1128 .iter()
1129 .enumerate()
1130 .map(|(ix, mat)| {
1131 let item_ix = start_ix + ix;
1132 let candidate_id = mat.candidate_id;
1133 let completion = &completions_guard[candidate_id];
1134
1135 let documentation = if show_completion_documentation {
1136 &completion.documentation
1137 } else {
1138 &None
1139 };
1140
1141 let highlights = gpui::combine_highlights(
1142 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1143 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1144 |(range, mut highlight)| {
1145 // Ignore font weight for syntax highlighting, as we'll use it
1146 // for fuzzy matches.
1147 highlight.font_weight = None;
1148
1149 if completion.lsp_completion.deprecated.unwrap_or(false) {
1150 highlight.strikethrough = Some(StrikethroughStyle {
1151 thickness: 1.0.into(),
1152 ..Default::default()
1153 });
1154 highlight.color = Some(cx.theme().colors().text_muted);
1155 }
1156
1157 (range, highlight)
1158 },
1159 ),
1160 );
1161 let completion_label = StyledText::new(completion.label.text.clone())
1162 .with_highlights(&style.text, highlights);
1163 let documentation_label =
1164 if let Some(Documentation::SingleLine(text)) = documentation {
1165 if text.trim().is_empty() {
1166 None
1167 } else {
1168 Some(
1169 Label::new(text.clone())
1170 .ml_4()
1171 .size(LabelSize::Small)
1172 .color(Color::Muted),
1173 )
1174 }
1175 } else {
1176 None
1177 };
1178
1179 div().min_w(px(220.)).max_w(px(540.)).child(
1180 ListItem::new(mat.candidate_id)
1181 .inset(true)
1182 .selected(item_ix == selected_item)
1183 .on_click(cx.listener(move |editor, _event, cx| {
1184 cx.stop_propagation();
1185 if let Some(task) = editor.confirm_completion(
1186 &ConfirmCompletion {
1187 item_ix: Some(item_ix),
1188 },
1189 cx,
1190 ) {
1191 task.detach_and_log_err(cx)
1192 }
1193 }))
1194 .child(h_flex().overflow_hidden().child(completion_label))
1195 .end_slot::<Label>(documentation_label),
1196 )
1197 })
1198 .collect()
1199 },
1200 )
1201 .occlude()
1202 .max_h(max_height)
1203 .track_scroll(self.scroll_handle.clone())
1204 .with_width_from_item(widest_completion_ix)
1205 .with_sizing_behavior(ListSizingBehavior::Infer);
1206
1207 Popover::new()
1208 .child(list)
1209 .when_some(multiline_docs, |popover, multiline_docs| {
1210 popover.aside(multiline_docs)
1211 })
1212 .into_any_element()
1213 }
1214
1215 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1216 let mut matches = if let Some(query) = query {
1217 fuzzy::match_strings(
1218 &self.match_candidates,
1219 query,
1220 query.chars().any(|c| c.is_uppercase()),
1221 100,
1222 &Default::default(),
1223 executor,
1224 )
1225 .await
1226 } else {
1227 self.match_candidates
1228 .iter()
1229 .enumerate()
1230 .map(|(candidate_id, candidate)| StringMatch {
1231 candidate_id,
1232 score: Default::default(),
1233 positions: Default::default(),
1234 string: candidate.string.clone(),
1235 })
1236 .collect()
1237 };
1238
1239 // Remove all candidates where the query's start does not match the start of any word in the candidate
1240 if let Some(query) = query {
1241 if let Some(query_start) = query.chars().next() {
1242 matches.retain(|string_match| {
1243 split_words(&string_match.string).any(|word| {
1244 // Check that the first codepoint of the word as lowercase matches the first
1245 // codepoint of the query as lowercase
1246 word.chars()
1247 .flat_map(|codepoint| codepoint.to_lowercase())
1248 .zip(query_start.to_lowercase())
1249 .all(|(word_cp, query_cp)| word_cp == query_cp)
1250 })
1251 });
1252 }
1253 }
1254
1255 let completions = self.completions.read();
1256 if self.sort_completions {
1257 matches.sort_unstable_by_key(|mat| {
1258 // We do want to strike a balance here between what the language server tells us
1259 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1260 // `Creat` and there is a local variable called `CreateComponent`).
1261 // So what we do is: we bucket all matches into two buckets
1262 // - Strong matches
1263 // - Weak matches
1264 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1265 // and the Weak matches are the rest.
1266 //
1267 // For the strong matches, we sort by the language-servers score first and for the weak
1268 // matches, we prefer our fuzzy finder first.
1269 //
1270 // The thinking behind that: it's useless to take the sort_text the language-server gives
1271 // us into account when it's obviously a bad match.
1272
1273 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1274 enum MatchScore<'a> {
1275 Strong {
1276 sort_text: Option<&'a str>,
1277 score: Reverse<OrderedFloat<f64>>,
1278 sort_key: (usize, &'a str),
1279 },
1280 Weak {
1281 score: Reverse<OrderedFloat<f64>>,
1282 sort_text: Option<&'a str>,
1283 sort_key: (usize, &'a str),
1284 },
1285 }
1286
1287 let completion = &completions[mat.candidate_id];
1288 let sort_key = completion.sort_key();
1289 let sort_text = completion.lsp_completion.sort_text.as_deref();
1290 let score = Reverse(OrderedFloat(mat.score));
1291
1292 if mat.score >= 0.2 {
1293 MatchScore::Strong {
1294 sort_text,
1295 score,
1296 sort_key,
1297 }
1298 } else {
1299 MatchScore::Weak {
1300 score,
1301 sort_text,
1302 sort_key,
1303 }
1304 }
1305 });
1306 }
1307
1308 for mat in &mut matches {
1309 let completion = &completions[mat.candidate_id];
1310 mat.string.clone_from(&completion.label.text);
1311 for position in &mut mat.positions {
1312 *position += completion.label.filter_range.start;
1313 }
1314 }
1315 drop(completions);
1316
1317 self.matches = matches.into();
1318 self.selected_item = 0;
1319 }
1320}
1321
1322#[derive(Clone)]
1323struct CodeActionContents {
1324 tasks: Option<Arc<ResolvedTasks>>,
1325 actions: Option<Arc<[CodeAction]>>,
1326}
1327
1328impl CodeActionContents {
1329 fn len(&self) -> usize {
1330 match (&self.tasks, &self.actions) {
1331 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1332 (Some(tasks), None) => tasks.templates.len(),
1333 (None, Some(actions)) => actions.len(),
1334 (None, None) => 0,
1335 }
1336 }
1337
1338 fn is_empty(&self) -> bool {
1339 match (&self.tasks, &self.actions) {
1340 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1341 (Some(tasks), None) => tasks.templates.is_empty(),
1342 (None, Some(actions)) => actions.is_empty(),
1343 (None, None) => true,
1344 }
1345 }
1346
1347 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1348 self.tasks
1349 .iter()
1350 .flat_map(|tasks| {
1351 tasks
1352 .templates
1353 .iter()
1354 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1355 })
1356 .chain(self.actions.iter().flat_map(|actions| {
1357 actions
1358 .iter()
1359 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1360 }))
1361 }
1362 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1363 match (&self.tasks, &self.actions) {
1364 (Some(tasks), Some(actions)) => {
1365 if index < tasks.templates.len() {
1366 tasks
1367 .templates
1368 .get(index)
1369 .cloned()
1370 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1371 } else {
1372 actions
1373 .get(index - tasks.templates.len())
1374 .cloned()
1375 .map(CodeActionsItem::CodeAction)
1376 }
1377 }
1378 (Some(tasks), None) => tasks
1379 .templates
1380 .get(index)
1381 .cloned()
1382 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1383 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1384 (None, None) => None,
1385 }
1386 }
1387}
1388
1389#[allow(clippy::large_enum_variant)]
1390#[derive(Clone)]
1391enum CodeActionsItem {
1392 Task(TaskSourceKind, ResolvedTask),
1393 CodeAction(CodeAction),
1394}
1395
1396impl CodeActionsItem {
1397 fn as_task(&self) -> Option<&ResolvedTask> {
1398 let Self::Task(_, task) = self else {
1399 return None;
1400 };
1401 Some(task)
1402 }
1403 fn as_code_action(&self) -> Option<&CodeAction> {
1404 let Self::CodeAction(action) = self else {
1405 return None;
1406 };
1407 Some(action)
1408 }
1409 fn label(&self) -> String {
1410 match self {
1411 Self::CodeAction(action) => action.lsp_action.title.clone(),
1412 Self::Task(_, task) => task.resolved_label.clone(),
1413 }
1414 }
1415}
1416
1417struct CodeActionsMenu {
1418 actions: CodeActionContents,
1419 buffer: Model<Buffer>,
1420 selected_item: usize,
1421 scroll_handle: UniformListScrollHandle,
1422 deployed_from_indicator: Option<DisplayRow>,
1423}
1424
1425impl CodeActionsMenu {
1426 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1427 self.selected_item = 0;
1428 self.scroll_handle.scroll_to_item(self.selected_item);
1429 cx.notify()
1430 }
1431
1432 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1433 if self.selected_item > 0 {
1434 self.selected_item -= 1;
1435 } else {
1436 self.selected_item = self.actions.len() - 1;
1437 }
1438 self.scroll_handle.scroll_to_item(self.selected_item);
1439 cx.notify();
1440 }
1441
1442 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1443 if self.selected_item + 1 < self.actions.len() {
1444 self.selected_item += 1;
1445 } else {
1446 self.selected_item = 0;
1447 }
1448 self.scroll_handle.scroll_to_item(self.selected_item);
1449 cx.notify();
1450 }
1451
1452 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1453 self.selected_item = self.actions.len() - 1;
1454 self.scroll_handle.scroll_to_item(self.selected_item);
1455 cx.notify()
1456 }
1457
1458 fn visible(&self) -> bool {
1459 !self.actions.is_empty()
1460 }
1461
1462 fn render(
1463 &self,
1464 cursor_position: DisplayPoint,
1465 _style: &EditorStyle,
1466 max_height: Pixels,
1467 cx: &mut ViewContext<Editor>,
1468 ) -> (ContextMenuOrigin, AnyElement) {
1469 let actions = self.actions.clone();
1470 let selected_item = self.selected_item;
1471 let element = uniform_list(
1472 cx.view().clone(),
1473 "code_actions_menu",
1474 self.actions.len(),
1475 move |_this, range, cx| {
1476 actions
1477 .iter()
1478 .skip(range.start)
1479 .take(range.end - range.start)
1480 .enumerate()
1481 .map(|(ix, action)| {
1482 let item_ix = range.start + ix;
1483 let selected = selected_item == item_ix;
1484 let colors = cx.theme().colors();
1485 div()
1486 .px_2()
1487 .text_color(colors.text)
1488 .when(selected, |style| {
1489 style
1490 .bg(colors.element_active)
1491 .text_color(colors.text_accent)
1492 })
1493 .hover(|style| {
1494 style
1495 .bg(colors.element_hover)
1496 .text_color(colors.text_accent)
1497 })
1498 .whitespace_nowrap()
1499 .when_some(action.as_code_action(), |this, action| {
1500 this.on_mouse_down(
1501 MouseButton::Left,
1502 cx.listener(move |editor, _, cx| {
1503 cx.stop_propagation();
1504 if let Some(task) = editor.confirm_code_action(
1505 &ConfirmCodeAction {
1506 item_ix: Some(item_ix),
1507 },
1508 cx,
1509 ) {
1510 task.detach_and_log_err(cx)
1511 }
1512 }),
1513 )
1514 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1515 .child(SharedString::from(action.lsp_action.title.clone()))
1516 })
1517 .when_some(action.as_task(), |this, task| {
1518 this.on_mouse_down(
1519 MouseButton::Left,
1520 cx.listener(move |editor, _, cx| {
1521 cx.stop_propagation();
1522 if let Some(task) = editor.confirm_code_action(
1523 &ConfirmCodeAction {
1524 item_ix: Some(item_ix),
1525 },
1526 cx,
1527 ) {
1528 task.detach_and_log_err(cx)
1529 }
1530 }),
1531 )
1532 .child(SharedString::from(task.resolved_label.clone()))
1533 })
1534 })
1535 .collect()
1536 },
1537 )
1538 .elevation_1(cx)
1539 .px_2()
1540 .py_1()
1541 .max_h(max_height)
1542 .occlude()
1543 .track_scroll(self.scroll_handle.clone())
1544 .with_width_from_item(
1545 self.actions
1546 .iter()
1547 .enumerate()
1548 .max_by_key(|(_, action)| match action {
1549 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1550 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1551 })
1552 .map(|(ix, _)| ix),
1553 )
1554 .with_sizing_behavior(ListSizingBehavior::Infer)
1555 .into_any_element();
1556
1557 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1558 ContextMenuOrigin::GutterIndicator(row)
1559 } else {
1560 ContextMenuOrigin::EditorPoint(cursor_position)
1561 };
1562
1563 (cursor_position, element)
1564 }
1565}
1566
1567#[derive(Debug)]
1568struct ActiveDiagnosticGroup {
1569 primary_range: Range<Anchor>,
1570 primary_message: String,
1571 group_id: usize,
1572 blocks: HashMap<CustomBlockId, Diagnostic>,
1573 is_valid: bool,
1574}
1575
1576#[derive(Serialize, Deserialize, Clone, Debug)]
1577pub struct ClipboardSelection {
1578 pub len: usize,
1579 pub is_entire_line: bool,
1580 pub first_line_indent: u32,
1581}
1582
1583#[derive(Debug)]
1584pub(crate) struct NavigationData {
1585 cursor_anchor: Anchor,
1586 cursor_position: Point,
1587 scroll_anchor: ScrollAnchor,
1588 scroll_top_row: u32,
1589}
1590
1591#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1592enum GotoDefinitionKind {
1593 Symbol,
1594 Declaration,
1595 Type,
1596 Implementation,
1597}
1598
1599#[derive(Debug, Clone)]
1600enum InlayHintRefreshReason {
1601 Toggle(bool),
1602 SettingsChange(InlayHintSettings),
1603 NewLinesShown,
1604 BufferEdited(HashSet<Arc<Language>>),
1605 RefreshRequested,
1606 ExcerptsRemoved(Vec<ExcerptId>),
1607}
1608
1609impl InlayHintRefreshReason {
1610 fn description(&self) -> &'static str {
1611 match self {
1612 Self::Toggle(_) => "toggle",
1613 Self::SettingsChange(_) => "settings change",
1614 Self::NewLinesShown => "new lines shown",
1615 Self::BufferEdited(_) => "buffer edited",
1616 Self::RefreshRequested => "refresh requested",
1617 Self::ExcerptsRemoved(_) => "excerpts removed",
1618 }
1619 }
1620}
1621
1622pub(crate) struct FocusedBlock {
1623 id: BlockId,
1624 focus_handle: WeakFocusHandle,
1625}
1626
1627impl Editor {
1628 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1629 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1630 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1631 Self::new(
1632 EditorMode::SingleLine { auto_width: false },
1633 buffer,
1634 None,
1635 false,
1636 cx,
1637 )
1638 }
1639
1640 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1641 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1642 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1643 Self::new(EditorMode::Full, buffer, None, false, cx)
1644 }
1645
1646 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1647 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1648 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1649 Self::new(
1650 EditorMode::SingleLine { auto_width: true },
1651 buffer,
1652 None,
1653 false,
1654 cx,
1655 )
1656 }
1657
1658 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1659 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1660 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1661 Self::new(
1662 EditorMode::AutoHeight { max_lines },
1663 buffer,
1664 None,
1665 false,
1666 cx,
1667 )
1668 }
1669
1670 pub fn for_buffer(
1671 buffer: Model<Buffer>,
1672 project: Option<Model<Project>>,
1673 cx: &mut ViewContext<Self>,
1674 ) -> Self {
1675 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1676 Self::new(EditorMode::Full, buffer, project, false, cx)
1677 }
1678
1679 pub fn for_multibuffer(
1680 buffer: Model<MultiBuffer>,
1681 project: Option<Model<Project>>,
1682 show_excerpt_controls: bool,
1683 cx: &mut ViewContext<Self>,
1684 ) -> Self {
1685 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1686 }
1687
1688 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1689 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1690 let mut clone = Self::new(
1691 self.mode,
1692 self.buffer.clone(),
1693 self.project.clone(),
1694 show_excerpt_controls,
1695 cx,
1696 );
1697 self.display_map.update(cx, |display_map, cx| {
1698 let snapshot = display_map.snapshot(cx);
1699 clone.display_map.update(cx, |display_map, cx| {
1700 display_map.set_state(&snapshot, cx);
1701 });
1702 });
1703 clone.selections.clone_state(&self.selections);
1704 clone.scroll_manager.clone_state(&self.scroll_manager);
1705 clone.searchable = self.searchable;
1706 clone
1707 }
1708
1709 pub fn new(
1710 mode: EditorMode,
1711 buffer: Model<MultiBuffer>,
1712 project: Option<Model<Project>>,
1713 show_excerpt_controls: bool,
1714 cx: &mut ViewContext<Self>,
1715 ) -> Self {
1716 let style = cx.text_style();
1717 let font_size = style.font_size.to_pixels(cx.rem_size());
1718 let editor = cx.view().downgrade();
1719 let fold_placeholder = FoldPlaceholder {
1720 constrain_width: true,
1721 render: Arc::new(move |fold_id, fold_range, cx| {
1722 let editor = editor.clone();
1723 div()
1724 .id(fold_id)
1725 .bg(cx.theme().colors().ghost_element_background)
1726 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1727 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1728 .rounded_sm()
1729 .size_full()
1730 .cursor_pointer()
1731 .child("⋯")
1732 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1733 .on_click(move |_, cx| {
1734 editor
1735 .update(cx, |editor, cx| {
1736 editor.unfold_ranges(
1737 [fold_range.start..fold_range.end],
1738 true,
1739 false,
1740 cx,
1741 );
1742 cx.stop_propagation();
1743 })
1744 .ok();
1745 })
1746 .into_any()
1747 }),
1748 merge_adjacent: true,
1749 };
1750 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1751 let display_map = cx.new_model(|cx| {
1752 DisplayMap::new(
1753 buffer.clone(),
1754 style.font(),
1755 font_size,
1756 None,
1757 show_excerpt_controls,
1758 file_header_size,
1759 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1760 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1761 fold_placeholder,
1762 cx,
1763 )
1764 });
1765
1766 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1767
1768 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1769
1770 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1771 .then(|| language_settings::SoftWrap::PreferLine);
1772
1773 let mut project_subscriptions = Vec::new();
1774 if mode == EditorMode::Full {
1775 if let Some(project) = project.as_ref() {
1776 if buffer.read(cx).is_singleton() {
1777 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1778 cx.emit(EditorEvent::TitleChanged);
1779 }));
1780 }
1781 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1782 if let project::Event::RefreshInlayHints = event {
1783 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1784 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1785 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1786 let focus_handle = editor.focus_handle(cx);
1787 if focus_handle.is_focused(cx) {
1788 let snapshot = buffer.read(cx).snapshot();
1789 for (range, snippet) in snippet_edits {
1790 let editor_range =
1791 language::range_from_lsp(*range).to_offset(&snapshot);
1792 editor
1793 .insert_snippet(&[editor_range], snippet.clone(), cx)
1794 .ok();
1795 }
1796 }
1797 }
1798 }
1799 }));
1800 let task_inventory = project.read(cx).task_inventory().clone();
1801 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1802 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1803 }));
1804 }
1805 }
1806
1807 let inlay_hint_settings = inlay_hint_settings(
1808 selections.newest_anchor().head(),
1809 &buffer.read(cx).snapshot(cx),
1810 cx,
1811 );
1812 let focus_handle = cx.focus_handle();
1813 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1814 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1815 .detach();
1816 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1817 .detach();
1818 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1819
1820 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1821 Some(false)
1822 } else {
1823 None
1824 };
1825
1826 let mut this = Self {
1827 focus_handle,
1828 show_cursor_when_unfocused: false,
1829 last_focused_descendant: None,
1830 buffer: buffer.clone(),
1831 display_map: display_map.clone(),
1832 selections,
1833 scroll_manager: ScrollManager::new(cx),
1834 columnar_selection_tail: None,
1835 add_selections_state: None,
1836 select_next_state: None,
1837 select_prev_state: None,
1838 selection_history: Default::default(),
1839 autoclose_regions: Default::default(),
1840 snippet_stack: Default::default(),
1841 select_larger_syntax_node_stack: Vec::new(),
1842 ime_transaction: Default::default(),
1843 active_diagnostics: None,
1844 soft_wrap_mode_override,
1845 completion_provider: project.clone().map(|project| Box::new(project) as _),
1846 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1847 project,
1848 blink_manager: blink_manager.clone(),
1849 show_local_selections: true,
1850 mode,
1851 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1852 show_gutter: mode == EditorMode::Full,
1853 show_line_numbers: None,
1854 show_git_diff_gutter: None,
1855 show_code_actions: None,
1856 show_runnables: None,
1857 show_wrap_guides: None,
1858 show_indent_guides,
1859 placeholder_text: None,
1860 highlight_order: 0,
1861 highlighted_rows: HashMap::default(),
1862 background_highlights: Default::default(),
1863 gutter_highlights: TreeMap::default(),
1864 scrollbar_marker_state: ScrollbarMarkerState::default(),
1865 active_indent_guides_state: ActiveIndentGuidesState::default(),
1866 nav_history: None,
1867 context_menu: RwLock::new(None),
1868 mouse_context_menu: None,
1869 completion_tasks: Default::default(),
1870 signature_help_state: SignatureHelpState::default(),
1871 auto_signature_help: None,
1872 find_all_references_task_sources: Vec::new(),
1873 next_completion_id: 0,
1874 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1875 next_inlay_id: 0,
1876 available_code_actions: Default::default(),
1877 code_actions_task: Default::default(),
1878 document_highlights_task: Default::default(),
1879 linked_editing_range_task: Default::default(),
1880 pending_rename: Default::default(),
1881 searchable: true,
1882 cursor_shape: Default::default(),
1883 current_line_highlight: None,
1884 autoindent_mode: Some(AutoindentMode::EachLine),
1885 collapse_matches: false,
1886 workspace: None,
1887 input_enabled: true,
1888 use_modal_editing: mode == EditorMode::Full,
1889 read_only: false,
1890 use_autoclose: true,
1891 use_auto_surround: true,
1892 auto_replace_emoji_shortcode: false,
1893 leader_peer_id: None,
1894 remote_id: None,
1895 hover_state: Default::default(),
1896 hovered_link_state: Default::default(),
1897 inline_completion_provider: None,
1898 active_inline_completion: None,
1899 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1900 expanded_hunks: ExpandedHunks::default(),
1901 gutter_hovered: false,
1902 pixel_position_of_newest_cursor: None,
1903 last_bounds: None,
1904 expect_bounds_change: None,
1905 gutter_dimensions: GutterDimensions::default(),
1906 style: None,
1907 show_cursor_names: false,
1908 hovered_cursors: Default::default(),
1909 next_editor_action_id: EditorActionId::default(),
1910 editor_actions: Rc::default(),
1911 show_inline_completions: mode == EditorMode::Full,
1912 custom_context_menu: None,
1913 show_git_blame_gutter: false,
1914 show_git_blame_inline: false,
1915 show_selection_menu: None,
1916 show_git_blame_inline_delay_task: None,
1917 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1918 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1919 .session
1920 .restore_unsaved_buffers,
1921 blame: None,
1922 blame_subscription: None,
1923 file_header_size,
1924 tasks: Default::default(),
1925 _subscriptions: vec![
1926 cx.observe(&buffer, Self::on_buffer_changed),
1927 cx.subscribe(&buffer, Self::on_buffer_event),
1928 cx.observe(&display_map, Self::on_display_map_changed),
1929 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1930 cx.observe_global::<SettingsStore>(Self::settings_changed),
1931 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1932 cx.observe_window_activation(|editor, cx| {
1933 let active = cx.is_window_active();
1934 editor.blink_manager.update(cx, |blink_manager, cx| {
1935 if active {
1936 blink_manager.enable(cx);
1937 } else {
1938 blink_manager.disable(cx);
1939 }
1940 });
1941 }),
1942 ],
1943 tasks_update_task: None,
1944 linked_edit_ranges: Default::default(),
1945 previous_search_ranges: None,
1946 breadcrumb_header: None,
1947 focused_block: None,
1948 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1949 addons: HashMap::default(),
1950 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1951 };
1952 this.tasks_update_task = Some(this.refresh_runnables(cx));
1953 this._subscriptions.extend(project_subscriptions);
1954
1955 this.end_selection(cx);
1956 this.scroll_manager.show_scrollbar(cx);
1957
1958 if mode == EditorMode::Full {
1959 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1960 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1961
1962 if this.git_blame_inline_enabled {
1963 this.git_blame_inline_enabled = true;
1964 this.start_git_blame_inline(false, cx);
1965 }
1966 }
1967
1968 this.report_editor_event("open", None, cx);
1969 this
1970 }
1971
1972 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
1973 self.mouse_context_menu
1974 .as_ref()
1975 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1976 }
1977
1978 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
1979 let mut key_context = KeyContext::new_with_defaults();
1980 key_context.add("Editor");
1981 let mode = match self.mode {
1982 EditorMode::SingleLine { .. } => "single_line",
1983 EditorMode::AutoHeight { .. } => "auto_height",
1984 EditorMode::Full => "full",
1985 };
1986
1987 if EditorSettings::jupyter_enabled(cx) {
1988 key_context.add("jupyter");
1989 }
1990
1991 key_context.set("mode", mode);
1992 if self.pending_rename.is_some() {
1993 key_context.add("renaming");
1994 }
1995 if self.context_menu_visible() {
1996 match self.context_menu.read().as_ref() {
1997 Some(ContextMenu::Completions(_)) => {
1998 key_context.add("menu");
1999 key_context.add("showing_completions")
2000 }
2001 Some(ContextMenu::CodeActions(_)) => {
2002 key_context.add("menu");
2003 key_context.add("showing_code_actions")
2004 }
2005 None => {}
2006 }
2007 }
2008
2009 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2010 if !self.focus_handle(cx).contains_focused(cx)
2011 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2012 {
2013 for addon in self.addons.values() {
2014 addon.extend_key_context(&mut key_context, cx)
2015 }
2016 }
2017
2018 if let Some(extension) = self
2019 .buffer
2020 .read(cx)
2021 .as_singleton()
2022 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2023 {
2024 key_context.set("extension", extension.to_string());
2025 }
2026
2027 if self.has_active_inline_completion(cx) {
2028 key_context.add("copilot_suggestion");
2029 key_context.add("inline_completion");
2030 }
2031
2032 key_context
2033 }
2034
2035 pub fn new_file(
2036 workspace: &mut Workspace,
2037 _: &workspace::NewFile,
2038 cx: &mut ViewContext<Workspace>,
2039 ) {
2040 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2041 "Failed to create buffer",
2042 cx,
2043 |e, _| match e.error_code() {
2044 ErrorCode::RemoteUpgradeRequired => Some(format!(
2045 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2046 e.error_tag("required").unwrap_or("the latest version")
2047 )),
2048 _ => None,
2049 },
2050 );
2051 }
2052
2053 pub fn new_in_workspace(
2054 workspace: &mut Workspace,
2055 cx: &mut ViewContext<Workspace>,
2056 ) -> Task<Result<View<Editor>>> {
2057 let project = workspace.project().clone();
2058 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2059
2060 cx.spawn(|workspace, mut cx| async move {
2061 let buffer = create.await?;
2062 workspace.update(&mut cx, |workspace, cx| {
2063 let editor =
2064 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2065 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2066 editor
2067 })
2068 })
2069 }
2070
2071 pub fn new_file_in_direction(
2072 workspace: &mut Workspace,
2073 action: &workspace::NewFileInDirection,
2074 cx: &mut ViewContext<Workspace>,
2075 ) {
2076 let project = workspace.project().clone();
2077 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2078 let direction = action.0;
2079
2080 cx.spawn(|workspace, mut cx| async move {
2081 let buffer = create.await?;
2082 workspace.update(&mut cx, move |workspace, cx| {
2083 workspace.split_item(
2084 direction,
2085 Box::new(
2086 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2087 ),
2088 cx,
2089 )
2090 })?;
2091 anyhow::Ok(())
2092 })
2093 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2094 ErrorCode::RemoteUpgradeRequired => Some(format!(
2095 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2096 e.error_tag("required").unwrap_or("the latest version")
2097 )),
2098 _ => None,
2099 });
2100 }
2101
2102 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2103 self.buffer.read(cx).replica_id()
2104 }
2105
2106 pub fn leader_peer_id(&self) -> Option<PeerId> {
2107 self.leader_peer_id
2108 }
2109
2110 pub fn buffer(&self) -> &Model<MultiBuffer> {
2111 &self.buffer
2112 }
2113
2114 pub fn workspace(&self) -> Option<View<Workspace>> {
2115 self.workspace.as_ref()?.0.upgrade()
2116 }
2117
2118 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2119 self.buffer().read(cx).title(cx)
2120 }
2121
2122 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2123 EditorSnapshot {
2124 mode: self.mode,
2125 show_gutter: self.show_gutter,
2126 show_line_numbers: self.show_line_numbers,
2127 show_git_diff_gutter: self.show_git_diff_gutter,
2128 show_code_actions: self.show_code_actions,
2129 show_runnables: self.show_runnables,
2130 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2131 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2132 scroll_anchor: self.scroll_manager.anchor(),
2133 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2134 placeholder_text: self.placeholder_text.clone(),
2135 is_focused: self.focus_handle.is_focused(cx),
2136 current_line_highlight: self
2137 .current_line_highlight
2138 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2139 gutter_hovered: self.gutter_hovered,
2140 }
2141 }
2142
2143 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2144 self.buffer.read(cx).language_at(point, cx)
2145 }
2146
2147 pub fn file_at<T: ToOffset>(
2148 &self,
2149 point: T,
2150 cx: &AppContext,
2151 ) -> Option<Arc<dyn language::File>> {
2152 self.buffer.read(cx).read(cx).file_at(point).cloned()
2153 }
2154
2155 pub fn active_excerpt(
2156 &self,
2157 cx: &AppContext,
2158 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2159 self.buffer
2160 .read(cx)
2161 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2162 }
2163
2164 pub fn mode(&self) -> EditorMode {
2165 self.mode
2166 }
2167
2168 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2169 self.collaboration_hub.as_deref()
2170 }
2171
2172 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2173 self.collaboration_hub = Some(hub);
2174 }
2175
2176 pub fn set_custom_context_menu(
2177 &mut self,
2178 f: impl 'static
2179 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2180 ) {
2181 self.custom_context_menu = Some(Box::new(f))
2182 }
2183
2184 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2185 self.completion_provider = Some(provider);
2186 }
2187
2188 pub fn set_inline_completion_provider<T>(
2189 &mut self,
2190 provider: Option<Model<T>>,
2191 cx: &mut ViewContext<Self>,
2192 ) where
2193 T: InlineCompletionProvider,
2194 {
2195 self.inline_completion_provider =
2196 provider.map(|provider| RegisteredInlineCompletionProvider {
2197 _subscription: cx.observe(&provider, |this, _, cx| {
2198 if this.focus_handle.is_focused(cx) {
2199 this.update_visible_inline_completion(cx);
2200 }
2201 }),
2202 provider: Arc::new(provider),
2203 });
2204 self.refresh_inline_completion(false, 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(crate) fn navigate_to_hover_links(
9183 &mut self,
9184 kind: Option<GotoDefinitionKind>,
9185 mut definitions: Vec<HoverLink>,
9186 split: bool,
9187 cx: &mut ViewContext<Editor>,
9188 ) -> Task<Result<Navigated>> {
9189 // If there is one definition, just open it directly
9190 if definitions.len() == 1 {
9191 let definition = definitions.pop().unwrap();
9192 let target_task = match definition {
9193 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9194 HoverLink::InlayHint(lsp_location, server_id) => {
9195 self.compute_target_location(lsp_location, server_id, cx)
9196 }
9197 HoverLink::Url(url) => {
9198 cx.open_url(&url);
9199 Task::ready(Ok(None))
9200 }
9201 };
9202 cx.spawn(|editor, mut cx| async move {
9203 let target = target_task.await.context("target resolution task")?;
9204 let Some(target) = target else {
9205 return Ok(Navigated::No);
9206 };
9207 editor.update(&mut cx, |editor, cx| {
9208 let Some(workspace) = editor.workspace() else {
9209 return Navigated::No;
9210 };
9211 let pane = workspace.read(cx).active_pane().clone();
9212
9213 let range = target.range.to_offset(target.buffer.read(cx));
9214 let range = editor.range_for_match(&range);
9215
9216 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9217 let buffer = target.buffer.read(cx);
9218 let range = check_multiline_range(buffer, range);
9219 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9220 s.select_ranges([range]);
9221 });
9222 } else {
9223 cx.window_context().defer(move |cx| {
9224 let target_editor: View<Self> =
9225 workspace.update(cx, |workspace, cx| {
9226 let pane = if split {
9227 workspace.adjacent_pane(cx)
9228 } else {
9229 workspace.active_pane().clone()
9230 };
9231
9232 workspace.open_project_item(
9233 pane,
9234 target.buffer.clone(),
9235 true,
9236 true,
9237 cx,
9238 )
9239 });
9240 target_editor.update(cx, |target_editor, cx| {
9241 // When selecting a definition in a different buffer, disable the nav history
9242 // to avoid creating a history entry at the previous cursor location.
9243 pane.update(cx, |pane, _| pane.disable_history());
9244 let buffer = target.buffer.read(cx);
9245 let range = check_multiline_range(buffer, range);
9246 target_editor.change_selections(
9247 Some(Autoscroll::focused()),
9248 cx,
9249 |s| {
9250 s.select_ranges([range]);
9251 },
9252 );
9253 pane.update(cx, |pane, _| pane.enable_history());
9254 });
9255 });
9256 }
9257 Navigated::Yes
9258 })
9259 })
9260 } else if !definitions.is_empty() {
9261 let replica_id = self.replica_id(cx);
9262 cx.spawn(|editor, mut cx| async move {
9263 let (title, location_tasks, workspace) = editor
9264 .update(&mut cx, |editor, cx| {
9265 let tab_kind = match kind {
9266 Some(GotoDefinitionKind::Implementation) => "Implementations",
9267 _ => "Definitions",
9268 };
9269 let title = definitions
9270 .iter()
9271 .find_map(|definition| match definition {
9272 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9273 let buffer = origin.buffer.read(cx);
9274 format!(
9275 "{} for {}",
9276 tab_kind,
9277 buffer
9278 .text_for_range(origin.range.clone())
9279 .collect::<String>()
9280 )
9281 }),
9282 HoverLink::InlayHint(_, _) => None,
9283 HoverLink::Url(_) => None,
9284 })
9285 .unwrap_or(tab_kind.to_string());
9286 let location_tasks = definitions
9287 .into_iter()
9288 .map(|definition| match definition {
9289 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9290 HoverLink::InlayHint(lsp_location, server_id) => {
9291 editor.compute_target_location(lsp_location, server_id, cx)
9292 }
9293 HoverLink::Url(_) => Task::ready(Ok(None)),
9294 })
9295 .collect::<Vec<_>>();
9296 (title, location_tasks, editor.workspace().clone())
9297 })
9298 .context("location tasks preparation")?;
9299
9300 let locations = futures::future::join_all(location_tasks)
9301 .await
9302 .into_iter()
9303 .filter_map(|location| location.transpose())
9304 .collect::<Result<_>>()
9305 .context("location tasks")?;
9306
9307 let Some(workspace) = workspace else {
9308 return Ok(Navigated::No);
9309 };
9310 let opened = workspace
9311 .update(&mut cx, |workspace, cx| {
9312 Self::open_locations_in_multibuffer(
9313 workspace, locations, replica_id, title, split, cx,
9314 )
9315 })
9316 .ok();
9317
9318 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9319 })
9320 } else {
9321 Task::ready(Ok(Navigated::No))
9322 }
9323 }
9324
9325 fn compute_target_location(
9326 &self,
9327 lsp_location: lsp::Location,
9328 server_id: LanguageServerId,
9329 cx: &mut ViewContext<Editor>,
9330 ) -> Task<anyhow::Result<Option<Location>>> {
9331 let Some(project) = self.project.clone() else {
9332 return Task::Ready(Some(Ok(None)));
9333 };
9334
9335 cx.spawn(move |editor, mut cx| async move {
9336 let location_task = editor.update(&mut cx, |editor, cx| {
9337 project.update(cx, |project, cx| {
9338 let language_server_name =
9339 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9340 project
9341 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9342 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9343 });
9344 language_server_name.map(|language_server_name| {
9345 project.open_local_buffer_via_lsp(
9346 lsp_location.uri.clone(),
9347 server_id,
9348 language_server_name,
9349 cx,
9350 )
9351 })
9352 })
9353 })?;
9354 let location = match location_task {
9355 Some(task) => Some({
9356 let target_buffer_handle = task.await.context("open local buffer")?;
9357 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9358 let target_start = target_buffer
9359 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9360 let target_end = target_buffer
9361 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9362 target_buffer.anchor_after(target_start)
9363 ..target_buffer.anchor_before(target_end)
9364 })?;
9365 Location {
9366 buffer: target_buffer_handle,
9367 range,
9368 }
9369 }),
9370 None => None,
9371 };
9372 Ok(location)
9373 })
9374 }
9375
9376 pub fn find_all_references(
9377 &mut self,
9378 _: &FindAllReferences,
9379 cx: &mut ViewContext<Self>,
9380 ) -> Option<Task<Result<Navigated>>> {
9381 let multi_buffer = self.buffer.read(cx);
9382 let selection = self.selections.newest::<usize>(cx);
9383 let head = selection.head();
9384
9385 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9386 let head_anchor = multi_buffer_snapshot.anchor_at(
9387 head,
9388 if head < selection.tail() {
9389 Bias::Right
9390 } else {
9391 Bias::Left
9392 },
9393 );
9394
9395 match self
9396 .find_all_references_task_sources
9397 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9398 {
9399 Ok(_) => {
9400 log::info!(
9401 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9402 );
9403 return None;
9404 }
9405 Err(i) => {
9406 self.find_all_references_task_sources.insert(i, head_anchor);
9407 }
9408 }
9409
9410 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9411 let replica_id = self.replica_id(cx);
9412 let workspace = self.workspace()?;
9413 let project = workspace.read(cx).project().clone();
9414 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9415 Some(cx.spawn(|editor, mut cx| async move {
9416 let _cleanup = defer({
9417 let mut cx = cx.clone();
9418 move || {
9419 let _ = editor.update(&mut cx, |editor, _| {
9420 if let Ok(i) =
9421 editor
9422 .find_all_references_task_sources
9423 .binary_search_by(|anchor| {
9424 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9425 })
9426 {
9427 editor.find_all_references_task_sources.remove(i);
9428 }
9429 });
9430 }
9431 });
9432
9433 let locations = references.await?;
9434 if locations.is_empty() {
9435 return anyhow::Ok(Navigated::No);
9436 }
9437
9438 workspace.update(&mut cx, |workspace, cx| {
9439 let title = locations
9440 .first()
9441 .as_ref()
9442 .map(|location| {
9443 let buffer = location.buffer.read(cx);
9444 format!(
9445 "References to `{}`",
9446 buffer
9447 .text_for_range(location.range.clone())
9448 .collect::<String>()
9449 )
9450 })
9451 .unwrap();
9452 Self::open_locations_in_multibuffer(
9453 workspace, locations, replica_id, title, false, cx,
9454 );
9455 Navigated::Yes
9456 })
9457 }))
9458 }
9459
9460 /// Opens a multibuffer with the given project locations in it
9461 pub fn open_locations_in_multibuffer(
9462 workspace: &mut Workspace,
9463 mut locations: Vec<Location>,
9464 replica_id: ReplicaId,
9465 title: String,
9466 split: bool,
9467 cx: &mut ViewContext<Workspace>,
9468 ) {
9469 // If there are multiple definitions, open them in a multibuffer
9470 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9471 let mut locations = locations.into_iter().peekable();
9472 let mut ranges_to_highlight = Vec::new();
9473 let capability = workspace.project().read(cx).capability();
9474
9475 let excerpt_buffer = cx.new_model(|cx| {
9476 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9477 while let Some(location) = locations.next() {
9478 let buffer = location.buffer.read(cx);
9479 let mut ranges_for_buffer = Vec::new();
9480 let range = location.range.to_offset(buffer);
9481 ranges_for_buffer.push(range.clone());
9482
9483 while let Some(next_location) = locations.peek() {
9484 if next_location.buffer == location.buffer {
9485 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9486 locations.next();
9487 } else {
9488 break;
9489 }
9490 }
9491
9492 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9493 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9494 location.buffer.clone(),
9495 ranges_for_buffer,
9496 DEFAULT_MULTIBUFFER_CONTEXT,
9497 cx,
9498 ))
9499 }
9500
9501 multibuffer.with_title(title)
9502 });
9503
9504 let editor = cx.new_view(|cx| {
9505 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9506 });
9507 editor.update(cx, |editor, cx| {
9508 if let Some(first_range) = ranges_to_highlight.first() {
9509 editor.change_selections(None, cx, |selections| {
9510 selections.clear_disjoint();
9511 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9512 });
9513 }
9514 editor.highlight_background::<Self>(
9515 &ranges_to_highlight,
9516 |theme| theme.editor_highlighted_line_background,
9517 cx,
9518 );
9519 });
9520
9521 let item = Box::new(editor);
9522 let item_id = item.item_id();
9523
9524 if split {
9525 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9526 } else {
9527 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9528 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9529 pane.close_current_preview_item(cx)
9530 } else {
9531 None
9532 }
9533 });
9534 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9535 }
9536 workspace.active_pane().update(cx, |pane, cx| {
9537 pane.set_preview_item_id(Some(item_id), cx);
9538 });
9539 }
9540
9541 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9542 use language::ToOffset as _;
9543
9544 let project = self.project.clone()?;
9545 let selection = self.selections.newest_anchor().clone();
9546 let (cursor_buffer, cursor_buffer_position) = self
9547 .buffer
9548 .read(cx)
9549 .text_anchor_for_position(selection.head(), cx)?;
9550 let (tail_buffer, cursor_buffer_position_end) = self
9551 .buffer
9552 .read(cx)
9553 .text_anchor_for_position(selection.tail(), cx)?;
9554 if tail_buffer != cursor_buffer {
9555 return None;
9556 }
9557
9558 let snapshot = cursor_buffer.read(cx).snapshot();
9559 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9560 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9561 let prepare_rename = project.update(cx, |project, cx| {
9562 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9563 });
9564 drop(snapshot);
9565
9566 Some(cx.spawn(|this, mut cx| async move {
9567 let rename_range = if let Some(range) = prepare_rename.await? {
9568 Some(range)
9569 } else {
9570 this.update(&mut cx, |this, cx| {
9571 let buffer = this.buffer.read(cx).snapshot(cx);
9572 let mut buffer_highlights = this
9573 .document_highlights_for_position(selection.head(), &buffer)
9574 .filter(|highlight| {
9575 highlight.start.excerpt_id == selection.head().excerpt_id
9576 && highlight.end.excerpt_id == selection.head().excerpt_id
9577 });
9578 buffer_highlights
9579 .next()
9580 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9581 })?
9582 };
9583 if let Some(rename_range) = rename_range {
9584 this.update(&mut cx, |this, cx| {
9585 let snapshot = cursor_buffer.read(cx).snapshot();
9586 let rename_buffer_range = rename_range.to_offset(&snapshot);
9587 let cursor_offset_in_rename_range =
9588 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9589 let cursor_offset_in_rename_range_end =
9590 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9591
9592 this.take_rename(false, cx);
9593 let buffer = this.buffer.read(cx).read(cx);
9594 let cursor_offset = selection.head().to_offset(&buffer);
9595 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9596 let rename_end = rename_start + rename_buffer_range.len();
9597 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9598 let mut old_highlight_id = None;
9599 let old_name: Arc<str> = buffer
9600 .chunks(rename_start..rename_end, true)
9601 .map(|chunk| {
9602 if old_highlight_id.is_none() {
9603 old_highlight_id = chunk.syntax_highlight_id;
9604 }
9605 chunk.text
9606 })
9607 .collect::<String>()
9608 .into();
9609
9610 drop(buffer);
9611
9612 // Position the selection in the rename editor so that it matches the current selection.
9613 this.show_local_selections = false;
9614 let rename_editor = cx.new_view(|cx| {
9615 let mut editor = Editor::single_line(cx);
9616 editor.buffer.update(cx, |buffer, cx| {
9617 buffer.edit([(0..0, old_name.clone())], None, cx)
9618 });
9619 let rename_selection_range = match cursor_offset_in_rename_range
9620 .cmp(&cursor_offset_in_rename_range_end)
9621 {
9622 Ordering::Equal => {
9623 editor.select_all(&SelectAll, cx);
9624 return editor;
9625 }
9626 Ordering::Less => {
9627 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9628 }
9629 Ordering::Greater => {
9630 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9631 }
9632 };
9633 if rename_selection_range.end > old_name.len() {
9634 editor.select_all(&SelectAll, cx);
9635 } else {
9636 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9637 s.select_ranges([rename_selection_range]);
9638 });
9639 }
9640 editor
9641 });
9642 cx.subscribe(&rename_editor, |_, _, e, cx| match e {
9643 EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
9644 _ => {}
9645 })
9646 .detach();
9647
9648 let write_highlights =
9649 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9650 let read_highlights =
9651 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9652 let ranges = write_highlights
9653 .iter()
9654 .flat_map(|(_, ranges)| ranges.iter())
9655 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9656 .cloned()
9657 .collect();
9658
9659 this.highlight_text::<Rename>(
9660 ranges,
9661 HighlightStyle {
9662 fade_out: Some(0.6),
9663 ..Default::default()
9664 },
9665 cx,
9666 );
9667 let rename_focus_handle = rename_editor.focus_handle(cx);
9668 cx.focus(&rename_focus_handle);
9669 let block_id = this.insert_blocks(
9670 [BlockProperties {
9671 style: BlockStyle::Flex,
9672 position: range.start,
9673 height: 1,
9674 render: Box::new({
9675 let rename_editor = rename_editor.clone();
9676 move |cx: &mut BlockContext| {
9677 let mut text_style = cx.editor_style.text.clone();
9678 if let Some(highlight_style) = old_highlight_id
9679 .and_then(|h| h.style(&cx.editor_style.syntax))
9680 {
9681 text_style = text_style.highlight(highlight_style);
9682 }
9683 div()
9684 .pl(cx.anchor_x)
9685 .child(EditorElement::new(
9686 &rename_editor,
9687 EditorStyle {
9688 background: cx.theme().system().transparent,
9689 local_player: cx.editor_style.local_player,
9690 text: text_style,
9691 scrollbar_width: cx.editor_style.scrollbar_width,
9692 syntax: cx.editor_style.syntax.clone(),
9693 status: cx.editor_style.status.clone(),
9694 inlay_hints_style: HighlightStyle {
9695 color: Some(cx.theme().status().hint),
9696 font_weight: Some(FontWeight::BOLD),
9697 ..HighlightStyle::default()
9698 },
9699 suggestions_style: HighlightStyle {
9700 color: Some(cx.theme().status().predictive),
9701 ..HighlightStyle::default()
9702 },
9703 ..EditorStyle::default()
9704 },
9705 ))
9706 .into_any_element()
9707 }
9708 }),
9709 disposition: BlockDisposition::Below,
9710 priority: 0,
9711 }],
9712 Some(Autoscroll::fit()),
9713 cx,
9714 )[0];
9715 this.pending_rename = Some(RenameState {
9716 range,
9717 old_name,
9718 editor: rename_editor,
9719 block_id,
9720 });
9721 })?;
9722 }
9723
9724 Ok(())
9725 }))
9726 }
9727
9728 pub fn confirm_rename(
9729 &mut self,
9730 _: &ConfirmRename,
9731 cx: &mut ViewContext<Self>,
9732 ) -> Option<Task<Result<()>>> {
9733 let rename = self.take_rename(false, cx)?;
9734 let workspace = self.workspace()?;
9735 let (start_buffer, start) = self
9736 .buffer
9737 .read(cx)
9738 .text_anchor_for_position(rename.range.start, cx)?;
9739 let (end_buffer, end) = self
9740 .buffer
9741 .read(cx)
9742 .text_anchor_for_position(rename.range.end, cx)?;
9743 if start_buffer != end_buffer {
9744 return None;
9745 }
9746
9747 let buffer = start_buffer;
9748 let range = start..end;
9749 let old_name = rename.old_name;
9750 let new_name = rename.editor.read(cx).text(cx);
9751
9752 let rename = workspace
9753 .read(cx)
9754 .project()
9755 .clone()
9756 .update(cx, |project, cx| {
9757 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9758 });
9759 let workspace = workspace.downgrade();
9760
9761 Some(cx.spawn(|editor, mut cx| async move {
9762 let project_transaction = rename.await?;
9763 Self::open_project_transaction(
9764 &editor,
9765 workspace,
9766 project_transaction,
9767 format!("Rename: {} → {}", old_name, new_name),
9768 cx.clone(),
9769 )
9770 .await?;
9771
9772 editor.update(&mut cx, |editor, cx| {
9773 editor.refresh_document_highlights(cx);
9774 })?;
9775 Ok(())
9776 }))
9777 }
9778
9779 fn take_rename(
9780 &mut self,
9781 moving_cursor: bool,
9782 cx: &mut ViewContext<Self>,
9783 ) -> Option<RenameState> {
9784 let rename = self.pending_rename.take()?;
9785 if rename.editor.focus_handle(cx).is_focused(cx) {
9786 cx.focus(&self.focus_handle);
9787 }
9788
9789 self.remove_blocks(
9790 [rename.block_id].into_iter().collect(),
9791 Some(Autoscroll::fit()),
9792 cx,
9793 );
9794 self.clear_highlights::<Rename>(cx);
9795 self.show_local_selections = true;
9796
9797 if moving_cursor {
9798 let rename_editor = rename.editor.read(cx);
9799 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9800
9801 // Update the selection to match the position of the selection inside
9802 // the rename editor.
9803 let snapshot = self.buffer.read(cx).read(cx);
9804 let rename_range = rename.range.to_offset(&snapshot);
9805 let cursor_in_editor = snapshot
9806 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9807 .min(rename_range.end);
9808 drop(snapshot);
9809
9810 self.change_selections(None, cx, |s| {
9811 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9812 });
9813 } else {
9814 self.refresh_document_highlights(cx);
9815 }
9816
9817 Some(rename)
9818 }
9819
9820 pub fn pending_rename(&self) -> Option<&RenameState> {
9821 self.pending_rename.as_ref()
9822 }
9823
9824 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9825 let project = match &self.project {
9826 Some(project) => project.clone(),
9827 None => return None,
9828 };
9829
9830 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9831 }
9832
9833 fn perform_format(
9834 &mut self,
9835 project: Model<Project>,
9836 trigger: FormatTrigger,
9837 cx: &mut ViewContext<Self>,
9838 ) -> Task<Result<()>> {
9839 let buffer = self.buffer().clone();
9840 let mut buffers = buffer.read(cx).all_buffers();
9841 if trigger == FormatTrigger::Save {
9842 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9843 }
9844
9845 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9846 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9847
9848 cx.spawn(|_, mut cx| async move {
9849 let transaction = futures::select_biased! {
9850 () = timeout => {
9851 log::warn!("timed out waiting for formatting");
9852 None
9853 }
9854 transaction = format.log_err().fuse() => transaction,
9855 };
9856
9857 buffer
9858 .update(&mut cx, |buffer, cx| {
9859 if let Some(transaction) = transaction {
9860 if !buffer.is_singleton() {
9861 buffer.push_transaction(&transaction.0, cx);
9862 }
9863 }
9864
9865 cx.notify();
9866 })
9867 .ok();
9868
9869 Ok(())
9870 })
9871 }
9872
9873 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
9874 if let Some(project) = self.project.clone() {
9875 self.buffer.update(cx, |multi_buffer, cx| {
9876 project.update(cx, |project, cx| {
9877 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
9878 });
9879 })
9880 }
9881 }
9882
9883 fn cancel_language_server_work(
9884 &mut self,
9885 _: &CancelLanguageServerWork,
9886 cx: &mut ViewContext<Self>,
9887 ) {
9888 if let Some(project) = self.project.clone() {
9889 self.buffer.update(cx, |multi_buffer, cx| {
9890 project.update(cx, |project, cx| {
9891 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
9892 });
9893 })
9894 }
9895 }
9896
9897 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
9898 cx.show_character_palette();
9899 }
9900
9901 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
9902 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
9903 let buffer = self.buffer.read(cx).snapshot(cx);
9904 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
9905 let is_valid = buffer
9906 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
9907 .any(|entry| {
9908 entry.diagnostic.is_primary
9909 && !entry.range.is_empty()
9910 && entry.range.start == primary_range_start
9911 && entry.diagnostic.message == active_diagnostics.primary_message
9912 });
9913
9914 if is_valid != active_diagnostics.is_valid {
9915 active_diagnostics.is_valid = is_valid;
9916 let mut new_styles = HashMap::default();
9917 for (block_id, diagnostic) in &active_diagnostics.blocks {
9918 new_styles.insert(
9919 *block_id,
9920 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
9921 );
9922 }
9923 self.display_map.update(cx, |display_map, _cx| {
9924 display_map.replace_blocks(new_styles)
9925 });
9926 }
9927 }
9928 }
9929
9930 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
9931 self.dismiss_diagnostics(cx);
9932 let snapshot = self.snapshot(cx);
9933 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
9934 let buffer = self.buffer.read(cx).snapshot(cx);
9935
9936 let mut primary_range = None;
9937 let mut primary_message = None;
9938 let mut group_end = Point::zero();
9939 let diagnostic_group = buffer
9940 .diagnostic_group::<MultiBufferPoint>(group_id)
9941 .filter_map(|entry| {
9942 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
9943 && (entry.range.start.row == entry.range.end.row
9944 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
9945 {
9946 return None;
9947 }
9948 if entry.range.end > group_end {
9949 group_end = entry.range.end;
9950 }
9951 if entry.diagnostic.is_primary {
9952 primary_range = Some(entry.range.clone());
9953 primary_message = Some(entry.diagnostic.message.clone());
9954 }
9955 Some(entry)
9956 })
9957 .collect::<Vec<_>>();
9958 let primary_range = primary_range?;
9959 let primary_message = primary_message?;
9960 let primary_range =
9961 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
9962
9963 let blocks = display_map
9964 .insert_blocks(
9965 diagnostic_group.iter().map(|entry| {
9966 let diagnostic = entry.diagnostic.clone();
9967 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
9968 BlockProperties {
9969 style: BlockStyle::Fixed,
9970 position: buffer.anchor_after(entry.range.start),
9971 height: message_height,
9972 render: diagnostic_block_renderer(diagnostic, None, true, true),
9973 disposition: BlockDisposition::Below,
9974 priority: 0,
9975 }
9976 }),
9977 cx,
9978 )
9979 .into_iter()
9980 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
9981 .collect();
9982
9983 Some(ActiveDiagnosticGroup {
9984 primary_range,
9985 primary_message,
9986 group_id,
9987 blocks,
9988 is_valid: true,
9989 })
9990 });
9991 self.active_diagnostics.is_some()
9992 }
9993
9994 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
9995 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
9996 self.display_map.update(cx, |display_map, cx| {
9997 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
9998 });
9999 cx.notify();
10000 }
10001 }
10002
10003 pub fn set_selections_from_remote(
10004 &mut self,
10005 selections: Vec<Selection<Anchor>>,
10006 pending_selection: Option<Selection<Anchor>>,
10007 cx: &mut ViewContext<Self>,
10008 ) {
10009 let old_cursor_position = self.selections.newest_anchor().head();
10010 self.selections.change_with(cx, |s| {
10011 s.select_anchors(selections);
10012 if let Some(pending_selection) = pending_selection {
10013 s.set_pending(pending_selection, SelectMode::Character);
10014 } else {
10015 s.clear_pending();
10016 }
10017 });
10018 self.selections_did_change(false, &old_cursor_position, true, cx);
10019 }
10020
10021 fn push_to_selection_history(&mut self) {
10022 self.selection_history.push(SelectionHistoryEntry {
10023 selections: self.selections.disjoint_anchors(),
10024 select_next_state: self.select_next_state.clone(),
10025 select_prev_state: self.select_prev_state.clone(),
10026 add_selections_state: self.add_selections_state.clone(),
10027 });
10028 }
10029
10030 pub fn transact(
10031 &mut self,
10032 cx: &mut ViewContext<Self>,
10033 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10034 ) -> Option<TransactionId> {
10035 self.start_transaction_at(Instant::now(), cx);
10036 update(self, cx);
10037 self.end_transaction_at(Instant::now(), cx)
10038 }
10039
10040 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10041 self.end_selection(cx);
10042 if let Some(tx_id) = self
10043 .buffer
10044 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10045 {
10046 self.selection_history
10047 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10048 cx.emit(EditorEvent::TransactionBegun {
10049 transaction_id: tx_id,
10050 })
10051 }
10052 }
10053
10054 fn end_transaction_at(
10055 &mut self,
10056 now: Instant,
10057 cx: &mut ViewContext<Self>,
10058 ) -> Option<TransactionId> {
10059 if let Some(transaction_id) = self
10060 .buffer
10061 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10062 {
10063 if let Some((_, end_selections)) =
10064 self.selection_history.transaction_mut(transaction_id)
10065 {
10066 *end_selections = Some(self.selections.disjoint_anchors());
10067 } else {
10068 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10069 }
10070
10071 cx.emit(EditorEvent::Edited { transaction_id });
10072 Some(transaction_id)
10073 } else {
10074 None
10075 }
10076 }
10077
10078 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10079 let mut fold_ranges = Vec::new();
10080
10081 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10082
10083 let selections = self.selections.all_adjusted(cx);
10084 for selection in selections {
10085 let range = selection.range().sorted();
10086 let buffer_start_row = range.start.row;
10087
10088 for row in (0..=range.end.row).rev() {
10089 if let Some((foldable_range, fold_text)) =
10090 display_map.foldable_range(MultiBufferRow(row))
10091 {
10092 if foldable_range.end.row >= buffer_start_row {
10093 fold_ranges.push((foldable_range, fold_text));
10094 if row <= range.start.row {
10095 break;
10096 }
10097 }
10098 }
10099 }
10100 }
10101
10102 self.fold_ranges(fold_ranges, true, cx);
10103 }
10104
10105 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10106 let buffer_row = fold_at.buffer_row;
10107 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10108
10109 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10110 let autoscroll = self
10111 .selections
10112 .all::<Point>(cx)
10113 .iter()
10114 .any(|selection| fold_range.overlaps(&selection.range()));
10115
10116 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10117 }
10118 }
10119
10120 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10121 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10122 let buffer = &display_map.buffer_snapshot;
10123 let selections = self.selections.all::<Point>(cx);
10124 let ranges = selections
10125 .iter()
10126 .map(|s| {
10127 let range = s.display_range(&display_map).sorted();
10128 let mut start = range.start.to_point(&display_map);
10129 let mut end = range.end.to_point(&display_map);
10130 start.column = 0;
10131 end.column = buffer.line_len(MultiBufferRow(end.row));
10132 start..end
10133 })
10134 .collect::<Vec<_>>();
10135
10136 self.unfold_ranges(ranges, true, true, cx);
10137 }
10138
10139 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10140 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10141
10142 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10143 ..Point::new(
10144 unfold_at.buffer_row.0,
10145 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10146 );
10147
10148 let autoscroll = self
10149 .selections
10150 .all::<Point>(cx)
10151 .iter()
10152 .any(|selection| selection.range().overlaps(&intersection_range));
10153
10154 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10155 }
10156
10157 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10158 let selections = self.selections.all::<Point>(cx);
10159 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10160 let line_mode = self.selections.line_mode;
10161 let ranges = selections.into_iter().map(|s| {
10162 if line_mode {
10163 let start = Point::new(s.start.row, 0);
10164 let end = Point::new(
10165 s.end.row,
10166 display_map
10167 .buffer_snapshot
10168 .line_len(MultiBufferRow(s.end.row)),
10169 );
10170 (start..end, display_map.fold_placeholder.clone())
10171 } else {
10172 (s.start..s.end, display_map.fold_placeholder.clone())
10173 }
10174 });
10175 self.fold_ranges(ranges, true, cx);
10176 }
10177
10178 pub fn fold_ranges<T: ToOffset + Clone>(
10179 &mut self,
10180 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10181 auto_scroll: bool,
10182 cx: &mut ViewContext<Self>,
10183 ) {
10184 let mut fold_ranges = Vec::new();
10185 let mut buffers_affected = HashMap::default();
10186 let multi_buffer = self.buffer().read(cx);
10187 for (fold_range, fold_text) in ranges {
10188 if let Some((_, buffer, _)) =
10189 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10190 {
10191 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10192 };
10193 fold_ranges.push((fold_range, fold_text));
10194 }
10195
10196 let mut ranges = fold_ranges.into_iter().peekable();
10197 if ranges.peek().is_some() {
10198 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10199
10200 if auto_scroll {
10201 self.request_autoscroll(Autoscroll::fit(), cx);
10202 }
10203
10204 for buffer in buffers_affected.into_values() {
10205 self.sync_expanded_diff_hunks(buffer, cx);
10206 }
10207
10208 cx.notify();
10209
10210 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10211 // Clear diagnostics block when folding a range that contains it.
10212 let snapshot = self.snapshot(cx);
10213 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10214 drop(snapshot);
10215 self.active_diagnostics = Some(active_diagnostics);
10216 self.dismiss_diagnostics(cx);
10217 } else {
10218 self.active_diagnostics = Some(active_diagnostics);
10219 }
10220 }
10221
10222 self.scrollbar_marker_state.dirty = true;
10223 }
10224 }
10225
10226 pub fn unfold_ranges<T: ToOffset + Clone>(
10227 &mut self,
10228 ranges: impl IntoIterator<Item = Range<T>>,
10229 inclusive: bool,
10230 auto_scroll: bool,
10231 cx: &mut ViewContext<Self>,
10232 ) {
10233 let mut unfold_ranges = Vec::new();
10234 let mut buffers_affected = HashMap::default();
10235 let multi_buffer = self.buffer().read(cx);
10236 for range in ranges {
10237 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10238 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10239 };
10240 unfold_ranges.push(range);
10241 }
10242
10243 let mut ranges = unfold_ranges.into_iter().peekable();
10244 if ranges.peek().is_some() {
10245 self.display_map
10246 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10247 if auto_scroll {
10248 self.request_autoscroll(Autoscroll::fit(), cx);
10249 }
10250
10251 for buffer in buffers_affected.into_values() {
10252 self.sync_expanded_diff_hunks(buffer, cx);
10253 }
10254
10255 cx.notify();
10256 self.scrollbar_marker_state.dirty = true;
10257 self.active_indent_guides_state.dirty = true;
10258 }
10259 }
10260
10261 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10262 if hovered != self.gutter_hovered {
10263 self.gutter_hovered = hovered;
10264 cx.notify();
10265 }
10266 }
10267
10268 pub fn insert_blocks(
10269 &mut self,
10270 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10271 autoscroll: Option<Autoscroll>,
10272 cx: &mut ViewContext<Self>,
10273 ) -> Vec<CustomBlockId> {
10274 let blocks = self
10275 .display_map
10276 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10277 if let Some(autoscroll) = autoscroll {
10278 self.request_autoscroll(autoscroll, cx);
10279 }
10280 cx.notify();
10281 blocks
10282 }
10283
10284 pub fn resize_blocks(
10285 &mut self,
10286 heights: HashMap<CustomBlockId, u32>,
10287 autoscroll: Option<Autoscroll>,
10288 cx: &mut ViewContext<Self>,
10289 ) {
10290 self.display_map
10291 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10292 if let Some(autoscroll) = autoscroll {
10293 self.request_autoscroll(autoscroll, cx);
10294 }
10295 cx.notify();
10296 }
10297
10298 pub fn replace_blocks(
10299 &mut self,
10300 renderers: HashMap<CustomBlockId, RenderBlock>,
10301 autoscroll: Option<Autoscroll>,
10302 cx: &mut ViewContext<Self>,
10303 ) {
10304 self.display_map
10305 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10306 if let Some(autoscroll) = autoscroll {
10307 self.request_autoscroll(autoscroll, cx);
10308 }
10309 cx.notify();
10310 }
10311
10312 pub fn remove_blocks(
10313 &mut self,
10314 block_ids: HashSet<CustomBlockId>,
10315 autoscroll: Option<Autoscroll>,
10316 cx: &mut ViewContext<Self>,
10317 ) {
10318 self.display_map.update(cx, |display_map, cx| {
10319 display_map.remove_blocks(block_ids, cx)
10320 });
10321 if let Some(autoscroll) = autoscroll {
10322 self.request_autoscroll(autoscroll, cx);
10323 }
10324 cx.notify();
10325 }
10326
10327 pub fn row_for_block(
10328 &self,
10329 block_id: CustomBlockId,
10330 cx: &mut ViewContext<Self>,
10331 ) -> Option<DisplayRow> {
10332 self.display_map
10333 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10334 }
10335
10336 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10337 self.focused_block = Some(focused_block);
10338 }
10339
10340 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10341 self.focused_block.take()
10342 }
10343
10344 pub fn insert_creases(
10345 &mut self,
10346 creases: impl IntoIterator<Item = Crease>,
10347 cx: &mut ViewContext<Self>,
10348 ) -> Vec<CreaseId> {
10349 self.display_map
10350 .update(cx, |map, cx| map.insert_creases(creases, cx))
10351 }
10352
10353 pub fn remove_creases(
10354 &mut self,
10355 ids: impl IntoIterator<Item = CreaseId>,
10356 cx: &mut ViewContext<Self>,
10357 ) {
10358 self.display_map
10359 .update(cx, |map, cx| map.remove_creases(ids, cx));
10360 }
10361
10362 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10363 self.display_map
10364 .update(cx, |map, cx| map.snapshot(cx))
10365 .longest_row()
10366 }
10367
10368 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10369 self.display_map
10370 .update(cx, |map, cx| map.snapshot(cx))
10371 .max_point()
10372 }
10373
10374 pub fn text(&self, cx: &AppContext) -> String {
10375 self.buffer.read(cx).read(cx).text()
10376 }
10377
10378 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10379 let text = self.text(cx);
10380 let text = text.trim();
10381
10382 if text.is_empty() {
10383 return None;
10384 }
10385
10386 Some(text.to_string())
10387 }
10388
10389 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10390 self.transact(cx, |this, cx| {
10391 this.buffer
10392 .read(cx)
10393 .as_singleton()
10394 .expect("you can only call set_text on editors for singleton buffers")
10395 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10396 });
10397 }
10398
10399 pub fn display_text(&self, cx: &mut AppContext) -> String {
10400 self.display_map
10401 .update(cx, |map, cx| map.snapshot(cx))
10402 .text()
10403 }
10404
10405 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10406 let mut wrap_guides = smallvec::smallvec![];
10407
10408 if self.show_wrap_guides == Some(false) {
10409 return wrap_guides;
10410 }
10411
10412 let settings = self.buffer.read(cx).settings_at(0, cx);
10413 if settings.show_wrap_guides {
10414 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10415 wrap_guides.push((soft_wrap as usize, true));
10416 }
10417 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10418 }
10419
10420 wrap_guides
10421 }
10422
10423 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10424 let settings = self.buffer.read(cx).settings_at(0, cx);
10425 let mode = self
10426 .soft_wrap_mode_override
10427 .unwrap_or_else(|| settings.soft_wrap);
10428 match mode {
10429 language_settings::SoftWrap::None => SoftWrap::None,
10430 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10431 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10432 language_settings::SoftWrap::PreferredLineLength => {
10433 SoftWrap::Column(settings.preferred_line_length)
10434 }
10435 }
10436 }
10437
10438 pub fn set_soft_wrap_mode(
10439 &mut self,
10440 mode: language_settings::SoftWrap,
10441 cx: &mut ViewContext<Self>,
10442 ) {
10443 self.soft_wrap_mode_override = Some(mode);
10444 cx.notify();
10445 }
10446
10447 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10448 let rem_size = cx.rem_size();
10449 self.display_map.update(cx, |map, cx| {
10450 map.set_font(
10451 style.text.font(),
10452 style.text.font_size.to_pixels(rem_size),
10453 cx,
10454 )
10455 });
10456 self.style = Some(style);
10457 }
10458
10459 pub fn style(&self) -> Option<&EditorStyle> {
10460 self.style.as_ref()
10461 }
10462
10463 // Called by the element. This method is not designed to be called outside of the editor
10464 // element's layout code because it does not notify when rewrapping is computed synchronously.
10465 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10466 self.display_map
10467 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10468 }
10469
10470 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10471 if self.soft_wrap_mode_override.is_some() {
10472 self.soft_wrap_mode_override.take();
10473 } else {
10474 let soft_wrap = match self.soft_wrap_mode(cx) {
10475 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10476 SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10477 language_settings::SoftWrap::PreferLine
10478 }
10479 };
10480 self.soft_wrap_mode_override = Some(soft_wrap);
10481 }
10482 cx.notify();
10483 }
10484
10485 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10486 let Some(workspace) = self.workspace() else {
10487 return;
10488 };
10489 let fs = workspace.read(cx).app_state().fs.clone();
10490 let current_show = TabBarSettings::get_global(cx).show;
10491 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10492 setting.show = Some(!current_show);
10493 });
10494 }
10495
10496 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10497 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10498 self.buffer
10499 .read(cx)
10500 .settings_at(0, cx)
10501 .indent_guides
10502 .enabled
10503 });
10504 self.show_indent_guides = Some(!currently_enabled);
10505 cx.notify();
10506 }
10507
10508 fn should_show_indent_guides(&self) -> Option<bool> {
10509 self.show_indent_guides
10510 }
10511
10512 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10513 let mut editor_settings = EditorSettings::get_global(cx).clone();
10514 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10515 EditorSettings::override_global(editor_settings, cx);
10516 }
10517
10518 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10519 self.show_gutter = show_gutter;
10520 cx.notify();
10521 }
10522
10523 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10524 self.show_line_numbers = Some(show_line_numbers);
10525 cx.notify();
10526 }
10527
10528 pub fn set_show_git_diff_gutter(
10529 &mut self,
10530 show_git_diff_gutter: bool,
10531 cx: &mut ViewContext<Self>,
10532 ) {
10533 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10534 cx.notify();
10535 }
10536
10537 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10538 self.show_code_actions = Some(show_code_actions);
10539 cx.notify();
10540 }
10541
10542 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10543 self.show_runnables = Some(show_runnables);
10544 cx.notify();
10545 }
10546
10547 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10548 if self.display_map.read(cx).masked != masked {
10549 self.display_map.update(cx, |map, _| map.masked = masked);
10550 }
10551 cx.notify()
10552 }
10553
10554 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10555 self.show_wrap_guides = Some(show_wrap_guides);
10556 cx.notify();
10557 }
10558
10559 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10560 self.show_indent_guides = Some(show_indent_guides);
10561 cx.notify();
10562 }
10563
10564 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10565 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10566 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10567 if let Some(dir) = file.abs_path(cx).parent() {
10568 return Some(dir.to_owned());
10569 }
10570 }
10571
10572 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10573 return Some(project_path.path.to_path_buf());
10574 }
10575 }
10576
10577 None
10578 }
10579
10580 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10581 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10582 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10583 cx.reveal_path(&file.abs_path(cx));
10584 }
10585 }
10586 }
10587
10588 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10589 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10590 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10591 if let Some(path) = file.abs_path(cx).to_str() {
10592 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10593 }
10594 }
10595 }
10596 }
10597
10598 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10599 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10600 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10601 if let Some(path) = file.path().to_str() {
10602 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10603 }
10604 }
10605 }
10606 }
10607
10608 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10609 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10610
10611 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10612 self.start_git_blame(true, cx);
10613 }
10614
10615 cx.notify();
10616 }
10617
10618 pub fn toggle_git_blame_inline(
10619 &mut self,
10620 _: &ToggleGitBlameInline,
10621 cx: &mut ViewContext<Self>,
10622 ) {
10623 self.toggle_git_blame_inline_internal(true, cx);
10624 cx.notify();
10625 }
10626
10627 pub fn git_blame_inline_enabled(&self) -> bool {
10628 self.git_blame_inline_enabled
10629 }
10630
10631 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10632 self.show_selection_menu = self
10633 .show_selection_menu
10634 .map(|show_selections_menu| !show_selections_menu)
10635 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10636
10637 cx.notify();
10638 }
10639
10640 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10641 self.show_selection_menu
10642 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10643 }
10644
10645 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10646 if let Some(project) = self.project.as_ref() {
10647 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10648 return;
10649 };
10650
10651 if buffer.read(cx).file().is_none() {
10652 return;
10653 }
10654
10655 let focused = self.focus_handle(cx).contains_focused(cx);
10656
10657 let project = project.clone();
10658 let blame =
10659 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10660 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10661 self.blame = Some(blame);
10662 }
10663 }
10664
10665 fn toggle_git_blame_inline_internal(
10666 &mut self,
10667 user_triggered: bool,
10668 cx: &mut ViewContext<Self>,
10669 ) {
10670 if self.git_blame_inline_enabled {
10671 self.git_blame_inline_enabled = false;
10672 self.show_git_blame_inline = false;
10673 self.show_git_blame_inline_delay_task.take();
10674 } else {
10675 self.git_blame_inline_enabled = true;
10676 self.start_git_blame_inline(user_triggered, cx);
10677 }
10678
10679 cx.notify();
10680 }
10681
10682 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10683 self.start_git_blame(user_triggered, cx);
10684
10685 if ProjectSettings::get_global(cx)
10686 .git
10687 .inline_blame_delay()
10688 .is_some()
10689 {
10690 self.start_inline_blame_timer(cx);
10691 } else {
10692 self.show_git_blame_inline = true
10693 }
10694 }
10695
10696 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10697 self.blame.as_ref()
10698 }
10699
10700 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10701 self.show_git_blame_gutter && self.has_blame_entries(cx)
10702 }
10703
10704 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10705 self.show_git_blame_inline
10706 && self.focus_handle.is_focused(cx)
10707 && !self.newest_selection_head_on_empty_line(cx)
10708 && self.has_blame_entries(cx)
10709 }
10710
10711 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10712 self.blame()
10713 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10714 }
10715
10716 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10717 let cursor_anchor = self.selections.newest_anchor().head();
10718
10719 let snapshot = self.buffer.read(cx).snapshot(cx);
10720 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10721
10722 snapshot.line_len(buffer_row) == 0
10723 }
10724
10725 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10726 let (path, selection, repo) = maybe!({
10727 let project_handle = self.project.as_ref()?.clone();
10728 let project = project_handle.read(cx);
10729
10730 let selection = self.selections.newest::<Point>(cx);
10731 let selection_range = selection.range();
10732
10733 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10734 (buffer, selection_range.start.row..selection_range.end.row)
10735 } else {
10736 let buffer_ranges = self
10737 .buffer()
10738 .read(cx)
10739 .range_to_buffer_ranges(selection_range, cx);
10740
10741 let (buffer, range, _) = if selection.reversed {
10742 buffer_ranges.first()
10743 } else {
10744 buffer_ranges.last()
10745 }?;
10746
10747 let snapshot = buffer.read(cx).snapshot();
10748 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10749 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10750 (buffer.clone(), selection)
10751 };
10752
10753 let path = buffer
10754 .read(cx)
10755 .file()?
10756 .as_local()?
10757 .path()
10758 .to_str()?
10759 .to_string();
10760 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10761 Some((path, selection, repo))
10762 })
10763 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10764
10765 const REMOTE_NAME: &str = "origin";
10766 let origin_url = repo
10767 .remote_url(REMOTE_NAME)
10768 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10769 let sha = repo
10770 .head_sha()
10771 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10772
10773 let (provider, remote) =
10774 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10775 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10776
10777 Ok(provider.build_permalink(
10778 remote,
10779 BuildPermalinkParams {
10780 sha: &sha,
10781 path: &path,
10782 selection: Some(selection),
10783 },
10784 ))
10785 }
10786
10787 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10788 let permalink = self.get_permalink_to_line(cx);
10789
10790 match permalink {
10791 Ok(permalink) => {
10792 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
10793 }
10794 Err(err) => {
10795 let message = format!("Failed to copy permalink: {err}");
10796
10797 Err::<(), anyhow::Error>(err).log_err();
10798
10799 if let Some(workspace) = self.workspace() {
10800 workspace.update(cx, |workspace, cx| {
10801 struct CopyPermalinkToLine;
10802
10803 workspace.show_toast(
10804 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10805 cx,
10806 )
10807 })
10808 }
10809 }
10810 }
10811 }
10812
10813 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10814 let permalink = self.get_permalink_to_line(cx);
10815
10816 match permalink {
10817 Ok(permalink) => {
10818 cx.open_url(permalink.as_ref());
10819 }
10820 Err(err) => {
10821 let message = format!("Failed to open permalink: {err}");
10822
10823 Err::<(), anyhow::Error>(err).log_err();
10824
10825 if let Some(workspace) = self.workspace() {
10826 workspace.update(cx, |workspace, cx| {
10827 struct OpenPermalinkToLine;
10828
10829 workspace.show_toast(
10830 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10831 cx,
10832 )
10833 })
10834 }
10835 }
10836 }
10837 }
10838
10839 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10840 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10841 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10842 pub fn highlight_rows<T: 'static>(
10843 &mut self,
10844 rows: RangeInclusive<Anchor>,
10845 color: Option<Hsla>,
10846 should_autoscroll: bool,
10847 cx: &mut ViewContext<Self>,
10848 ) {
10849 let snapshot = self.buffer().read(cx).snapshot(cx);
10850 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10851 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10852 highlight
10853 .range
10854 .start()
10855 .cmp(&rows.start(), &snapshot)
10856 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10857 });
10858 match (color, existing_highlight_index) {
10859 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10860 ix,
10861 RowHighlight {
10862 index: post_inc(&mut self.highlight_order),
10863 range: rows,
10864 should_autoscroll,
10865 color,
10866 },
10867 ),
10868 (None, Ok(i)) => {
10869 row_highlights.remove(i);
10870 }
10871 }
10872 }
10873
10874 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10875 pub fn clear_row_highlights<T: 'static>(&mut self) {
10876 self.highlighted_rows.remove(&TypeId::of::<T>());
10877 }
10878
10879 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10880 pub fn highlighted_rows<T: 'static>(
10881 &self,
10882 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10883 Some(
10884 self.highlighted_rows
10885 .get(&TypeId::of::<T>())?
10886 .iter()
10887 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10888 )
10889 }
10890
10891 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10892 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10893 /// Allows to ignore certain kinds of highlights.
10894 pub fn highlighted_display_rows(
10895 &mut self,
10896 cx: &mut WindowContext,
10897 ) -> BTreeMap<DisplayRow, Hsla> {
10898 let snapshot = self.snapshot(cx);
10899 let mut used_highlight_orders = HashMap::default();
10900 self.highlighted_rows
10901 .iter()
10902 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10903 .fold(
10904 BTreeMap::<DisplayRow, Hsla>::new(),
10905 |mut unique_rows, highlight| {
10906 let start_row = highlight.range.start().to_display_point(&snapshot).row();
10907 let end_row = highlight.range.end().to_display_point(&snapshot).row();
10908 for row in start_row.0..=end_row.0 {
10909 let used_index =
10910 used_highlight_orders.entry(row).or_insert(highlight.index);
10911 if highlight.index >= *used_index {
10912 *used_index = highlight.index;
10913 match highlight.color {
10914 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10915 None => unique_rows.remove(&DisplayRow(row)),
10916 };
10917 }
10918 }
10919 unique_rows
10920 },
10921 )
10922 }
10923
10924 pub fn highlighted_display_row_for_autoscroll(
10925 &self,
10926 snapshot: &DisplaySnapshot,
10927 ) -> Option<DisplayRow> {
10928 self.highlighted_rows
10929 .values()
10930 .flat_map(|highlighted_rows| highlighted_rows.iter())
10931 .filter_map(|highlight| {
10932 if highlight.color.is_none() || !highlight.should_autoscroll {
10933 return None;
10934 }
10935 Some(highlight.range.start().to_display_point(&snapshot).row())
10936 })
10937 .min()
10938 }
10939
10940 pub fn set_search_within_ranges(
10941 &mut self,
10942 ranges: &[Range<Anchor>],
10943 cx: &mut ViewContext<Self>,
10944 ) {
10945 self.highlight_background::<SearchWithinRange>(
10946 ranges,
10947 |colors| colors.editor_document_highlight_read_background,
10948 cx,
10949 )
10950 }
10951
10952 pub fn set_breadcrumb_header(&mut self, new_header: String) {
10953 self.breadcrumb_header = Some(new_header);
10954 }
10955
10956 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10957 self.clear_background_highlights::<SearchWithinRange>(cx);
10958 }
10959
10960 pub fn highlight_background<T: 'static>(
10961 &mut self,
10962 ranges: &[Range<Anchor>],
10963 color_fetcher: fn(&ThemeColors) -> Hsla,
10964 cx: &mut ViewContext<Self>,
10965 ) {
10966 self.background_highlights
10967 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10968 self.scrollbar_marker_state.dirty = true;
10969 cx.notify();
10970 }
10971
10972 pub fn clear_background_highlights<T: 'static>(
10973 &mut self,
10974 cx: &mut ViewContext<Self>,
10975 ) -> Option<BackgroundHighlight> {
10976 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10977 if !text_highlights.1.is_empty() {
10978 self.scrollbar_marker_state.dirty = true;
10979 cx.notify();
10980 }
10981 Some(text_highlights)
10982 }
10983
10984 pub fn highlight_gutter<T: 'static>(
10985 &mut self,
10986 ranges: &[Range<Anchor>],
10987 color_fetcher: fn(&AppContext) -> Hsla,
10988 cx: &mut ViewContext<Self>,
10989 ) {
10990 self.gutter_highlights
10991 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10992 cx.notify();
10993 }
10994
10995 pub fn clear_gutter_highlights<T: 'static>(
10996 &mut self,
10997 cx: &mut ViewContext<Self>,
10998 ) -> Option<GutterHighlight> {
10999 cx.notify();
11000 self.gutter_highlights.remove(&TypeId::of::<T>())
11001 }
11002
11003 #[cfg(feature = "test-support")]
11004 pub fn all_text_background_highlights(
11005 &mut self,
11006 cx: &mut ViewContext<Self>,
11007 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11008 let snapshot = self.snapshot(cx);
11009 let buffer = &snapshot.buffer_snapshot;
11010 let start = buffer.anchor_before(0);
11011 let end = buffer.anchor_after(buffer.len());
11012 let theme = cx.theme().colors();
11013 self.background_highlights_in_range(start..end, &snapshot, theme)
11014 }
11015
11016 #[cfg(feature = "test-support")]
11017 pub fn search_background_highlights(
11018 &mut self,
11019 cx: &mut ViewContext<Self>,
11020 ) -> Vec<Range<Point>> {
11021 let snapshot = self.buffer().read(cx).snapshot(cx);
11022
11023 let highlights = self
11024 .background_highlights
11025 .get(&TypeId::of::<items::BufferSearchHighlights>());
11026
11027 if let Some((_color, ranges)) = highlights {
11028 ranges
11029 .iter()
11030 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11031 .collect_vec()
11032 } else {
11033 vec![]
11034 }
11035 }
11036
11037 fn document_highlights_for_position<'a>(
11038 &'a self,
11039 position: Anchor,
11040 buffer: &'a MultiBufferSnapshot,
11041 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11042 let read_highlights = self
11043 .background_highlights
11044 .get(&TypeId::of::<DocumentHighlightRead>())
11045 .map(|h| &h.1);
11046 let write_highlights = self
11047 .background_highlights
11048 .get(&TypeId::of::<DocumentHighlightWrite>())
11049 .map(|h| &h.1);
11050 let left_position = position.bias_left(buffer);
11051 let right_position = position.bias_right(buffer);
11052 read_highlights
11053 .into_iter()
11054 .chain(write_highlights)
11055 .flat_map(move |ranges| {
11056 let start_ix = match ranges.binary_search_by(|probe| {
11057 let cmp = probe.end.cmp(&left_position, buffer);
11058 if cmp.is_ge() {
11059 Ordering::Greater
11060 } else {
11061 Ordering::Less
11062 }
11063 }) {
11064 Ok(i) | Err(i) => i,
11065 };
11066
11067 ranges[start_ix..]
11068 .iter()
11069 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11070 })
11071 }
11072
11073 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11074 self.background_highlights
11075 .get(&TypeId::of::<T>())
11076 .map_or(false, |(_, highlights)| !highlights.is_empty())
11077 }
11078
11079 pub fn background_highlights_in_range(
11080 &self,
11081 search_range: Range<Anchor>,
11082 display_snapshot: &DisplaySnapshot,
11083 theme: &ThemeColors,
11084 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11085 let mut results = Vec::new();
11086 for (color_fetcher, ranges) in self.background_highlights.values() {
11087 let color = color_fetcher(theme);
11088 let start_ix = match ranges.binary_search_by(|probe| {
11089 let cmp = probe
11090 .end
11091 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11092 if cmp.is_gt() {
11093 Ordering::Greater
11094 } else {
11095 Ordering::Less
11096 }
11097 }) {
11098 Ok(i) | Err(i) => i,
11099 };
11100 for range in &ranges[start_ix..] {
11101 if range
11102 .start
11103 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11104 .is_ge()
11105 {
11106 break;
11107 }
11108
11109 let start = range.start.to_display_point(&display_snapshot);
11110 let end = range.end.to_display_point(&display_snapshot);
11111 results.push((start..end, color))
11112 }
11113 }
11114 results
11115 }
11116
11117 pub fn background_highlight_row_ranges<T: 'static>(
11118 &self,
11119 search_range: Range<Anchor>,
11120 display_snapshot: &DisplaySnapshot,
11121 count: usize,
11122 ) -> Vec<RangeInclusive<DisplayPoint>> {
11123 let mut results = Vec::new();
11124 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11125 return vec![];
11126 };
11127
11128 let start_ix = match ranges.binary_search_by(|probe| {
11129 let cmp = probe
11130 .end
11131 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11132 if cmp.is_gt() {
11133 Ordering::Greater
11134 } else {
11135 Ordering::Less
11136 }
11137 }) {
11138 Ok(i) | Err(i) => i,
11139 };
11140 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11141 if let (Some(start_display), Some(end_display)) = (start, end) {
11142 results.push(
11143 start_display.to_display_point(display_snapshot)
11144 ..=end_display.to_display_point(display_snapshot),
11145 );
11146 }
11147 };
11148 let mut start_row: Option<Point> = None;
11149 let mut end_row: Option<Point> = None;
11150 if ranges.len() > count {
11151 return Vec::new();
11152 }
11153 for range in &ranges[start_ix..] {
11154 if range
11155 .start
11156 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11157 .is_ge()
11158 {
11159 break;
11160 }
11161 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11162 if let Some(current_row) = &end_row {
11163 if end.row == current_row.row {
11164 continue;
11165 }
11166 }
11167 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11168 if start_row.is_none() {
11169 assert_eq!(end_row, None);
11170 start_row = Some(start);
11171 end_row = Some(end);
11172 continue;
11173 }
11174 if let Some(current_end) = end_row.as_mut() {
11175 if start.row > current_end.row + 1 {
11176 push_region(start_row, end_row);
11177 start_row = Some(start);
11178 end_row = Some(end);
11179 } else {
11180 // Merge two hunks.
11181 *current_end = end;
11182 }
11183 } else {
11184 unreachable!();
11185 }
11186 }
11187 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11188 push_region(start_row, end_row);
11189 results
11190 }
11191
11192 pub fn gutter_highlights_in_range(
11193 &self,
11194 search_range: Range<Anchor>,
11195 display_snapshot: &DisplaySnapshot,
11196 cx: &AppContext,
11197 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11198 let mut results = Vec::new();
11199 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11200 let color = color_fetcher(cx);
11201 let start_ix = match ranges.binary_search_by(|probe| {
11202 let cmp = probe
11203 .end
11204 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11205 if cmp.is_gt() {
11206 Ordering::Greater
11207 } else {
11208 Ordering::Less
11209 }
11210 }) {
11211 Ok(i) | Err(i) => i,
11212 };
11213 for range in &ranges[start_ix..] {
11214 if range
11215 .start
11216 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11217 .is_ge()
11218 {
11219 break;
11220 }
11221
11222 let start = range.start.to_display_point(&display_snapshot);
11223 let end = range.end.to_display_point(&display_snapshot);
11224 results.push((start..end, color))
11225 }
11226 }
11227 results
11228 }
11229
11230 /// Get the text ranges corresponding to the redaction query
11231 pub fn redacted_ranges(
11232 &self,
11233 search_range: Range<Anchor>,
11234 display_snapshot: &DisplaySnapshot,
11235 cx: &WindowContext,
11236 ) -> Vec<Range<DisplayPoint>> {
11237 display_snapshot
11238 .buffer_snapshot
11239 .redacted_ranges(search_range, |file| {
11240 if let Some(file) = file {
11241 file.is_private()
11242 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11243 } else {
11244 false
11245 }
11246 })
11247 .map(|range| {
11248 range.start.to_display_point(display_snapshot)
11249 ..range.end.to_display_point(display_snapshot)
11250 })
11251 .collect()
11252 }
11253
11254 pub fn highlight_text<T: 'static>(
11255 &mut self,
11256 ranges: Vec<Range<Anchor>>,
11257 style: HighlightStyle,
11258 cx: &mut ViewContext<Self>,
11259 ) {
11260 self.display_map.update(cx, |map, _| {
11261 map.highlight_text(TypeId::of::<T>(), ranges, style)
11262 });
11263 cx.notify();
11264 }
11265
11266 pub(crate) fn highlight_inlays<T: 'static>(
11267 &mut self,
11268 highlights: Vec<InlayHighlight>,
11269 style: HighlightStyle,
11270 cx: &mut ViewContext<Self>,
11271 ) {
11272 self.display_map.update(cx, |map, _| {
11273 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11274 });
11275 cx.notify();
11276 }
11277
11278 pub fn text_highlights<'a, T: 'static>(
11279 &'a self,
11280 cx: &'a AppContext,
11281 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11282 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11283 }
11284
11285 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11286 let cleared = self
11287 .display_map
11288 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11289 if cleared {
11290 cx.notify();
11291 }
11292 }
11293
11294 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11295 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11296 && self.focus_handle.is_focused(cx)
11297 }
11298
11299 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11300 self.show_cursor_when_unfocused = is_enabled;
11301 cx.notify();
11302 }
11303
11304 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11305 cx.notify();
11306 }
11307
11308 fn on_buffer_event(
11309 &mut self,
11310 multibuffer: Model<MultiBuffer>,
11311 event: &multi_buffer::Event,
11312 cx: &mut ViewContext<Self>,
11313 ) {
11314 match event {
11315 multi_buffer::Event::Edited {
11316 singleton_buffer_edited,
11317 } => {
11318 self.scrollbar_marker_state.dirty = true;
11319 self.active_indent_guides_state.dirty = true;
11320 self.refresh_active_diagnostics(cx);
11321 self.refresh_code_actions(cx);
11322 if self.has_active_inline_completion(cx) {
11323 self.update_visible_inline_completion(cx);
11324 }
11325 cx.emit(EditorEvent::BufferEdited);
11326 cx.emit(SearchEvent::MatchesInvalidated);
11327 if *singleton_buffer_edited {
11328 if let Some(project) = &self.project {
11329 let project = project.read(cx);
11330 #[allow(clippy::mutable_key_type)]
11331 let languages_affected = multibuffer
11332 .read(cx)
11333 .all_buffers()
11334 .into_iter()
11335 .filter_map(|buffer| {
11336 let buffer = buffer.read(cx);
11337 let language = buffer.language()?;
11338 if project.is_local()
11339 && project.language_servers_for_buffer(buffer, cx).count() == 0
11340 {
11341 None
11342 } else {
11343 Some(language)
11344 }
11345 })
11346 .cloned()
11347 .collect::<HashSet<_>>();
11348 if !languages_affected.is_empty() {
11349 self.refresh_inlay_hints(
11350 InlayHintRefreshReason::BufferEdited(languages_affected),
11351 cx,
11352 );
11353 }
11354 }
11355 }
11356
11357 let Some(project) = &self.project else { return };
11358 let telemetry = project.read(cx).client().telemetry().clone();
11359 refresh_linked_ranges(self, cx);
11360 telemetry.log_edit_event("editor");
11361 }
11362 multi_buffer::Event::ExcerptsAdded {
11363 buffer,
11364 predecessor,
11365 excerpts,
11366 } => {
11367 self.tasks_update_task = Some(self.refresh_runnables(cx));
11368 cx.emit(EditorEvent::ExcerptsAdded {
11369 buffer: buffer.clone(),
11370 predecessor: *predecessor,
11371 excerpts: excerpts.clone(),
11372 });
11373 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11374 }
11375 multi_buffer::Event::ExcerptsRemoved { ids } => {
11376 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11377 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11378 }
11379 multi_buffer::Event::ExcerptsEdited { ids } => {
11380 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11381 }
11382 multi_buffer::Event::ExcerptsExpanded { ids } => {
11383 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11384 }
11385 multi_buffer::Event::Reparsed(buffer_id) => {
11386 self.tasks_update_task = Some(self.refresh_runnables(cx));
11387
11388 cx.emit(EditorEvent::Reparsed(*buffer_id));
11389 }
11390 multi_buffer::Event::LanguageChanged(buffer_id) => {
11391 linked_editing_ranges::refresh_linked_ranges(self, cx);
11392 cx.emit(EditorEvent::Reparsed(*buffer_id));
11393 cx.notify();
11394 }
11395 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11396 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11397 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11398 cx.emit(EditorEvent::TitleChanged)
11399 }
11400 multi_buffer::Event::DiffBaseChanged => {
11401 self.scrollbar_marker_state.dirty = true;
11402 cx.emit(EditorEvent::DiffBaseChanged);
11403 cx.notify();
11404 }
11405 multi_buffer::Event::DiffUpdated { buffer } => {
11406 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11407 cx.notify();
11408 }
11409 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11410 multi_buffer::Event::DiagnosticsUpdated => {
11411 self.refresh_active_diagnostics(cx);
11412 self.scrollbar_marker_state.dirty = true;
11413 cx.notify();
11414 }
11415 _ => {}
11416 };
11417 }
11418
11419 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11420 cx.notify();
11421 }
11422
11423 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11424 self.tasks_update_task = Some(self.refresh_runnables(cx));
11425 self.refresh_inline_completion(true, false, cx);
11426 self.refresh_inlay_hints(
11427 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11428 self.selections.newest_anchor().head(),
11429 &self.buffer.read(cx).snapshot(cx),
11430 cx,
11431 )),
11432 cx,
11433 );
11434 let editor_settings = EditorSettings::get_global(cx);
11435 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11436 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11437
11438 let project_settings = ProjectSettings::get_global(cx);
11439 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11440
11441 if self.mode == EditorMode::Full {
11442 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11443 if self.git_blame_inline_enabled != inline_blame_enabled {
11444 self.toggle_git_blame_inline_internal(false, cx);
11445 }
11446 }
11447
11448 cx.notify();
11449 }
11450
11451 pub fn set_searchable(&mut self, searchable: bool) {
11452 self.searchable = searchable;
11453 }
11454
11455 pub fn searchable(&self) -> bool {
11456 self.searchable
11457 }
11458
11459 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11460 self.open_excerpts_common(true, cx)
11461 }
11462
11463 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11464 self.open_excerpts_common(false, cx)
11465 }
11466
11467 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11468 let buffer = self.buffer.read(cx);
11469 if buffer.is_singleton() {
11470 cx.propagate();
11471 return;
11472 }
11473
11474 let Some(workspace) = self.workspace() else {
11475 cx.propagate();
11476 return;
11477 };
11478
11479 let mut new_selections_by_buffer = HashMap::default();
11480 for selection in self.selections.all::<usize>(cx) {
11481 for (buffer, mut range, _) in
11482 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11483 {
11484 if selection.reversed {
11485 mem::swap(&mut range.start, &mut range.end);
11486 }
11487 new_selections_by_buffer
11488 .entry(buffer)
11489 .or_insert(Vec::new())
11490 .push(range)
11491 }
11492 }
11493
11494 // We defer the pane interaction because we ourselves are a workspace item
11495 // and activating a new item causes the pane to call a method on us reentrantly,
11496 // which panics if we're on the stack.
11497 cx.window_context().defer(move |cx| {
11498 workspace.update(cx, |workspace, cx| {
11499 let pane = if split {
11500 workspace.adjacent_pane(cx)
11501 } else {
11502 workspace.active_pane().clone()
11503 };
11504
11505 for (buffer, ranges) in new_selections_by_buffer {
11506 let editor =
11507 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11508 editor.update(cx, |editor, cx| {
11509 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11510 s.select_ranges(ranges);
11511 });
11512 });
11513 }
11514 })
11515 });
11516 }
11517
11518 fn jump(
11519 &mut self,
11520 path: ProjectPath,
11521 position: Point,
11522 anchor: language::Anchor,
11523 offset_from_top: u32,
11524 cx: &mut ViewContext<Self>,
11525 ) {
11526 let workspace = self.workspace();
11527 cx.spawn(|_, mut cx| async move {
11528 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11529 let editor = workspace.update(&mut cx, |workspace, cx| {
11530 // Reset the preview item id before opening the new item
11531 workspace.active_pane().update(cx, |pane, cx| {
11532 pane.set_preview_item_id(None, cx);
11533 });
11534 workspace.open_path_preview(path, None, true, true, cx)
11535 })?;
11536 let editor = editor
11537 .await?
11538 .downcast::<Editor>()
11539 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11540 .downgrade();
11541 editor.update(&mut cx, |editor, cx| {
11542 let buffer = editor
11543 .buffer()
11544 .read(cx)
11545 .as_singleton()
11546 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11547 let buffer = buffer.read(cx);
11548 let cursor = if buffer.can_resolve(&anchor) {
11549 language::ToPoint::to_point(&anchor, buffer)
11550 } else {
11551 buffer.clip_point(position, Bias::Left)
11552 };
11553
11554 let nav_history = editor.nav_history.take();
11555 editor.change_selections(
11556 Some(Autoscroll::top_relative(offset_from_top as usize)),
11557 cx,
11558 |s| {
11559 s.select_ranges([cursor..cursor]);
11560 },
11561 );
11562 editor.nav_history = nav_history;
11563
11564 anyhow::Ok(())
11565 })??;
11566
11567 anyhow::Ok(())
11568 })
11569 .detach_and_log_err(cx);
11570 }
11571
11572 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11573 let snapshot = self.buffer.read(cx).read(cx);
11574 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11575 Some(
11576 ranges
11577 .iter()
11578 .map(move |range| {
11579 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11580 })
11581 .collect(),
11582 )
11583 }
11584
11585 fn selection_replacement_ranges(
11586 &self,
11587 range: Range<OffsetUtf16>,
11588 cx: &AppContext,
11589 ) -> Vec<Range<OffsetUtf16>> {
11590 let selections = self.selections.all::<OffsetUtf16>(cx);
11591 let newest_selection = selections
11592 .iter()
11593 .max_by_key(|selection| selection.id)
11594 .unwrap();
11595 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11596 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11597 let snapshot = self.buffer.read(cx).read(cx);
11598 selections
11599 .into_iter()
11600 .map(|mut selection| {
11601 selection.start.0 =
11602 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11603 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11604 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11605 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11606 })
11607 .collect()
11608 }
11609
11610 fn report_editor_event(
11611 &self,
11612 operation: &'static str,
11613 file_extension: Option<String>,
11614 cx: &AppContext,
11615 ) {
11616 if cfg!(any(test, feature = "test-support")) {
11617 return;
11618 }
11619
11620 let Some(project) = &self.project else { return };
11621
11622 // If None, we are in a file without an extension
11623 let file = self
11624 .buffer
11625 .read(cx)
11626 .as_singleton()
11627 .and_then(|b| b.read(cx).file());
11628 let file_extension = file_extension.or(file
11629 .as_ref()
11630 .and_then(|file| Path::new(file.file_name(cx)).extension())
11631 .and_then(|e| e.to_str())
11632 .map(|a| a.to_string()));
11633
11634 let vim_mode = cx
11635 .global::<SettingsStore>()
11636 .raw_user_settings()
11637 .get("vim_mode")
11638 == Some(&serde_json::Value::Bool(true));
11639
11640 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11641 == language::language_settings::InlineCompletionProvider::Copilot;
11642 let copilot_enabled_for_language = self
11643 .buffer
11644 .read(cx)
11645 .settings_at(0, cx)
11646 .show_inline_completions;
11647
11648 let telemetry = project.read(cx).client().telemetry().clone();
11649 telemetry.report_editor_event(
11650 file_extension,
11651 vim_mode,
11652 operation,
11653 copilot_enabled,
11654 copilot_enabled_for_language,
11655 )
11656 }
11657
11658 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11659 /// with each line being an array of {text, highlight} objects.
11660 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11661 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11662 return;
11663 };
11664
11665 #[derive(Serialize)]
11666 struct Chunk<'a> {
11667 text: String,
11668 highlight: Option<&'a str>,
11669 }
11670
11671 let snapshot = buffer.read(cx).snapshot();
11672 let range = self
11673 .selected_text_range(cx)
11674 .and_then(|selected_range| {
11675 if selected_range.is_empty() {
11676 None
11677 } else {
11678 Some(selected_range)
11679 }
11680 })
11681 .unwrap_or_else(|| 0..snapshot.len());
11682
11683 let chunks = snapshot.chunks(range, true);
11684 let mut lines = Vec::new();
11685 let mut line: VecDeque<Chunk> = VecDeque::new();
11686
11687 let Some(style) = self.style.as_ref() else {
11688 return;
11689 };
11690
11691 for chunk in chunks {
11692 let highlight = chunk
11693 .syntax_highlight_id
11694 .and_then(|id| id.name(&style.syntax));
11695 let mut chunk_lines = chunk.text.split('\n').peekable();
11696 while let Some(text) = chunk_lines.next() {
11697 let mut merged_with_last_token = false;
11698 if let Some(last_token) = line.back_mut() {
11699 if last_token.highlight == highlight {
11700 last_token.text.push_str(text);
11701 merged_with_last_token = true;
11702 }
11703 }
11704
11705 if !merged_with_last_token {
11706 line.push_back(Chunk {
11707 text: text.into(),
11708 highlight,
11709 });
11710 }
11711
11712 if chunk_lines.peek().is_some() {
11713 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11714 line.pop_front();
11715 }
11716 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11717 line.pop_back();
11718 }
11719
11720 lines.push(mem::take(&mut line));
11721 }
11722 }
11723 }
11724
11725 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11726 return;
11727 };
11728 cx.write_to_clipboard(ClipboardItem::new_string(lines));
11729 }
11730
11731 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11732 &self.inlay_hint_cache
11733 }
11734
11735 pub fn replay_insert_event(
11736 &mut self,
11737 text: &str,
11738 relative_utf16_range: Option<Range<isize>>,
11739 cx: &mut ViewContext<Self>,
11740 ) {
11741 if !self.input_enabled {
11742 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11743 return;
11744 }
11745 if let Some(relative_utf16_range) = relative_utf16_range {
11746 let selections = self.selections.all::<OffsetUtf16>(cx);
11747 self.change_selections(None, cx, |s| {
11748 let new_ranges = selections.into_iter().map(|range| {
11749 let start = OffsetUtf16(
11750 range
11751 .head()
11752 .0
11753 .saturating_add_signed(relative_utf16_range.start),
11754 );
11755 let end = OffsetUtf16(
11756 range
11757 .head()
11758 .0
11759 .saturating_add_signed(relative_utf16_range.end),
11760 );
11761 start..end
11762 });
11763 s.select_ranges(new_ranges);
11764 });
11765 }
11766
11767 self.handle_input(text, cx);
11768 }
11769
11770 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11771 let Some(project) = self.project.as_ref() else {
11772 return false;
11773 };
11774 let project = project.read(cx);
11775
11776 let mut supports = false;
11777 self.buffer().read(cx).for_each_buffer(|buffer| {
11778 if !supports {
11779 supports = project
11780 .language_servers_for_buffer(buffer.read(cx), cx)
11781 .any(
11782 |(_, server)| match server.capabilities().inlay_hint_provider {
11783 Some(lsp::OneOf::Left(enabled)) => enabled,
11784 Some(lsp::OneOf::Right(_)) => true,
11785 None => false,
11786 },
11787 )
11788 }
11789 });
11790 supports
11791 }
11792
11793 pub fn focus(&self, cx: &mut WindowContext) {
11794 cx.focus(&self.focus_handle)
11795 }
11796
11797 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11798 self.focus_handle.is_focused(cx)
11799 }
11800
11801 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11802 cx.emit(EditorEvent::Focused);
11803
11804 if let Some(descendant) = self
11805 .last_focused_descendant
11806 .take()
11807 .and_then(|descendant| descendant.upgrade())
11808 {
11809 cx.focus(&descendant);
11810 } else {
11811 if let Some(blame) = self.blame.as_ref() {
11812 blame.update(cx, GitBlame::focus)
11813 }
11814
11815 self.blink_manager.update(cx, BlinkManager::enable);
11816 self.show_cursor_names(cx);
11817 self.buffer.update(cx, |buffer, cx| {
11818 buffer.finalize_last_transaction(cx);
11819 if self.leader_peer_id.is_none() {
11820 buffer.set_active_selections(
11821 &self.selections.disjoint_anchors(),
11822 self.selections.line_mode,
11823 self.cursor_shape,
11824 cx,
11825 );
11826 }
11827 });
11828 }
11829 }
11830
11831 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11832 cx.emit(EditorEvent::FocusedIn)
11833 }
11834
11835 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11836 if event.blurred != self.focus_handle {
11837 self.last_focused_descendant = Some(event.blurred);
11838 }
11839 }
11840
11841 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11842 self.blink_manager.update(cx, BlinkManager::disable);
11843 self.buffer
11844 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11845
11846 if let Some(blame) = self.blame.as_ref() {
11847 blame.update(cx, GitBlame::blur)
11848 }
11849 if !self.hover_state.focused(cx) {
11850 hide_hover(self, cx);
11851 }
11852
11853 self.hide_context_menu(cx);
11854 cx.emit(EditorEvent::Blurred);
11855 cx.notify();
11856 }
11857
11858 pub fn register_action<A: Action>(
11859 &mut self,
11860 listener: impl Fn(&A, &mut WindowContext) + 'static,
11861 ) -> Subscription {
11862 let id = self.next_editor_action_id.post_inc();
11863 let listener = Arc::new(listener);
11864 self.editor_actions.borrow_mut().insert(
11865 id,
11866 Box::new(move |cx| {
11867 let cx = cx.window_context();
11868 let listener = listener.clone();
11869 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11870 let action = action.downcast_ref().unwrap();
11871 if phase == DispatchPhase::Bubble {
11872 listener(action, cx)
11873 }
11874 })
11875 }),
11876 );
11877
11878 let editor_actions = self.editor_actions.clone();
11879 Subscription::new(move || {
11880 editor_actions.borrow_mut().remove(&id);
11881 })
11882 }
11883
11884 pub fn file_header_size(&self) -> u32 {
11885 self.file_header_size
11886 }
11887
11888 pub fn revert(
11889 &mut self,
11890 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
11891 cx: &mut ViewContext<Self>,
11892 ) {
11893 self.buffer().update(cx, |multi_buffer, cx| {
11894 for (buffer_id, changes) in revert_changes {
11895 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
11896 buffer.update(cx, |buffer, cx| {
11897 buffer.edit(
11898 changes.into_iter().map(|(range, text)| {
11899 (range, text.to_string().map(Arc::<str>::from))
11900 }),
11901 None,
11902 cx,
11903 );
11904 });
11905 }
11906 }
11907 });
11908 self.change_selections(None, cx, |selections| selections.refresh());
11909 }
11910
11911 pub fn to_pixel_point(
11912 &mut self,
11913 source: multi_buffer::Anchor,
11914 editor_snapshot: &EditorSnapshot,
11915 cx: &mut ViewContext<Self>,
11916 ) -> Option<gpui::Point<Pixels>> {
11917 let source_point = source.to_display_point(editor_snapshot);
11918 self.display_to_pixel_point(source_point, editor_snapshot, cx)
11919 }
11920
11921 pub fn display_to_pixel_point(
11922 &mut self,
11923 source: DisplayPoint,
11924 editor_snapshot: &EditorSnapshot,
11925 cx: &mut ViewContext<Self>,
11926 ) -> Option<gpui::Point<Pixels>> {
11927 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
11928 let text_layout_details = self.text_layout_details(cx);
11929 let scroll_top = text_layout_details
11930 .scroll_anchor
11931 .scroll_position(editor_snapshot)
11932 .y;
11933
11934 if source.row().as_f32() < scroll_top.floor() {
11935 return None;
11936 }
11937 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
11938 let source_y = line_height * (source.row().as_f32() - scroll_top);
11939 Some(gpui::Point::new(source_x, source_y))
11940 }
11941
11942 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
11943 let bounds = self.last_bounds?;
11944 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
11945 }
11946
11947 pub fn has_active_completions_menu(&self) -> bool {
11948 self.context_menu.read().as_ref().map_or(false, |menu| {
11949 menu.visible() && matches!(menu, ContextMenu::Completions(_))
11950 })
11951 }
11952
11953 pub fn register_addon<T: Addon>(&mut self, instance: T) {
11954 self.addons
11955 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
11956 }
11957
11958 pub fn unregister_addon<T: Addon>(&mut self) {
11959 self.addons.remove(&std::any::TypeId::of::<T>());
11960 }
11961
11962 pub fn addon<T: Addon>(&self) -> Option<&T> {
11963 let type_id = std::any::TypeId::of::<T>();
11964 self.addons
11965 .get(&type_id)
11966 .and_then(|item| item.to_any().downcast_ref::<T>())
11967 }
11968}
11969
11970fn hunks_for_selections(
11971 multi_buffer_snapshot: &MultiBufferSnapshot,
11972 selections: &[Selection<Anchor>],
11973) -> Vec<DiffHunk<MultiBufferRow>> {
11974 let buffer_rows_for_selections = selections.iter().map(|selection| {
11975 let head = selection.head();
11976 let tail = selection.tail();
11977 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11978 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11979 if start > end {
11980 end..start
11981 } else {
11982 start..end
11983 }
11984 });
11985
11986 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
11987}
11988
11989pub fn hunks_for_rows(
11990 rows: impl Iterator<Item = Range<MultiBufferRow>>,
11991 multi_buffer_snapshot: &MultiBufferSnapshot,
11992) -> Vec<DiffHunk<MultiBufferRow>> {
11993 let mut hunks = Vec::new();
11994 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11995 HashMap::default();
11996 for selected_multi_buffer_rows in rows {
11997 let query_rows =
11998 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11999 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12000 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12001 // when the caret is just above or just below the deleted hunk.
12002 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12003 let related_to_selection = if allow_adjacent {
12004 hunk.associated_range.overlaps(&query_rows)
12005 || hunk.associated_range.start == query_rows.end
12006 || hunk.associated_range.end == query_rows.start
12007 } else {
12008 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12009 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12010 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12011 || selected_multi_buffer_rows.end == hunk.associated_range.start
12012 };
12013 if related_to_selection {
12014 if !processed_buffer_rows
12015 .entry(hunk.buffer_id)
12016 .or_default()
12017 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12018 {
12019 continue;
12020 }
12021 hunks.push(hunk);
12022 }
12023 }
12024 }
12025
12026 hunks
12027}
12028
12029pub trait CollaborationHub {
12030 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12031 fn user_participant_indices<'a>(
12032 &self,
12033 cx: &'a AppContext,
12034 ) -> &'a HashMap<u64, ParticipantIndex>;
12035 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12036}
12037
12038impl CollaborationHub for Model<Project> {
12039 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12040 self.read(cx).collaborators()
12041 }
12042
12043 fn user_participant_indices<'a>(
12044 &self,
12045 cx: &'a AppContext,
12046 ) -> &'a HashMap<u64, ParticipantIndex> {
12047 self.read(cx).user_store().read(cx).participant_indices()
12048 }
12049
12050 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12051 let this = self.read(cx);
12052 let user_ids = this.collaborators().values().map(|c| c.user_id);
12053 this.user_store().read_with(cx, |user_store, cx| {
12054 user_store.participant_names(user_ids, cx)
12055 })
12056 }
12057}
12058
12059pub trait CompletionProvider {
12060 fn completions(
12061 &self,
12062 buffer: &Model<Buffer>,
12063 buffer_position: text::Anchor,
12064 trigger: CompletionContext,
12065 cx: &mut ViewContext<Editor>,
12066 ) -> Task<Result<Vec<Completion>>>;
12067
12068 fn resolve_completions(
12069 &self,
12070 buffer: Model<Buffer>,
12071 completion_indices: Vec<usize>,
12072 completions: Arc<RwLock<Box<[Completion]>>>,
12073 cx: &mut ViewContext<Editor>,
12074 ) -> Task<Result<bool>>;
12075
12076 fn apply_additional_edits_for_completion(
12077 &self,
12078 buffer: Model<Buffer>,
12079 completion: Completion,
12080 push_to_history: bool,
12081 cx: &mut ViewContext<Editor>,
12082 ) -> Task<Result<Option<language::Transaction>>>;
12083
12084 fn is_completion_trigger(
12085 &self,
12086 buffer: &Model<Buffer>,
12087 position: language::Anchor,
12088 text: &str,
12089 trigger_in_words: bool,
12090 cx: &mut ViewContext<Editor>,
12091 ) -> bool;
12092
12093 fn sort_completions(&self) -> bool {
12094 true
12095 }
12096}
12097
12098fn snippet_completions(
12099 project: &Project,
12100 buffer: &Model<Buffer>,
12101 buffer_position: text::Anchor,
12102 cx: &mut AppContext,
12103) -> Vec<Completion> {
12104 let language = buffer.read(cx).language_at(buffer_position);
12105 let language_name = language.as_ref().map(|language| language.lsp_id());
12106 let snippet_store = project.snippets().read(cx);
12107 let snippets = snippet_store.snippets_for(language_name, cx);
12108
12109 if snippets.is_empty() {
12110 return vec![];
12111 }
12112 let snapshot = buffer.read(cx).text_snapshot();
12113 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12114
12115 let mut lines = chunks.lines();
12116 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12117 return vec![];
12118 };
12119
12120 let scope = language.map(|language| language.default_scope());
12121 let mut last_word = line_at
12122 .chars()
12123 .rev()
12124 .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
12125 .collect::<String>();
12126 last_word = last_word.chars().rev().collect();
12127 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12128 let to_lsp = |point: &text::Anchor| {
12129 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12130 point_to_lsp(end)
12131 };
12132 let lsp_end = to_lsp(&buffer_position);
12133 snippets
12134 .into_iter()
12135 .filter_map(|snippet| {
12136 let matching_prefix = snippet
12137 .prefix
12138 .iter()
12139 .find(|prefix| prefix.starts_with(&last_word))?;
12140 let start = as_offset - last_word.len();
12141 let start = snapshot.anchor_before(start);
12142 let range = start..buffer_position;
12143 let lsp_start = to_lsp(&start);
12144 let lsp_range = lsp::Range {
12145 start: lsp_start,
12146 end: lsp_end,
12147 };
12148 Some(Completion {
12149 old_range: range,
12150 new_text: snippet.body.clone(),
12151 label: CodeLabel {
12152 text: matching_prefix.clone(),
12153 runs: vec![],
12154 filter_range: 0..matching_prefix.len(),
12155 },
12156 server_id: LanguageServerId(usize::MAX),
12157 documentation: snippet
12158 .description
12159 .clone()
12160 .map(|description| Documentation::SingleLine(description)),
12161 lsp_completion: lsp::CompletionItem {
12162 label: snippet.prefix.first().unwrap().clone(),
12163 kind: Some(CompletionItemKind::SNIPPET),
12164 label_details: snippet.description.as_ref().map(|description| {
12165 lsp::CompletionItemLabelDetails {
12166 detail: Some(description.clone()),
12167 description: None,
12168 }
12169 }),
12170 insert_text_format: Some(InsertTextFormat::SNIPPET),
12171 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12172 lsp::InsertReplaceEdit {
12173 new_text: snippet.body.clone(),
12174 insert: lsp_range,
12175 replace: lsp_range,
12176 },
12177 )),
12178 filter_text: Some(snippet.body.clone()),
12179 sort_text: Some(char::MAX.to_string()),
12180 ..Default::default()
12181 },
12182 confirm: None,
12183 })
12184 })
12185 .collect()
12186}
12187
12188impl CompletionProvider for Model<Project> {
12189 fn completions(
12190 &self,
12191 buffer: &Model<Buffer>,
12192 buffer_position: text::Anchor,
12193 options: CompletionContext,
12194 cx: &mut ViewContext<Editor>,
12195 ) -> Task<Result<Vec<Completion>>> {
12196 self.update(cx, |project, cx| {
12197 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12198 let project_completions = project.completions(&buffer, buffer_position, options, cx);
12199 cx.background_executor().spawn(async move {
12200 let mut completions = project_completions.await?;
12201 //let snippets = snippets.into_iter().;
12202 completions.extend(snippets);
12203 Ok(completions)
12204 })
12205 })
12206 }
12207
12208 fn resolve_completions(
12209 &self,
12210 buffer: Model<Buffer>,
12211 completion_indices: Vec<usize>,
12212 completions: Arc<RwLock<Box<[Completion]>>>,
12213 cx: &mut ViewContext<Editor>,
12214 ) -> Task<Result<bool>> {
12215 self.update(cx, |project, cx| {
12216 project.resolve_completions(buffer, completion_indices, completions, cx)
12217 })
12218 }
12219
12220 fn apply_additional_edits_for_completion(
12221 &self,
12222 buffer: Model<Buffer>,
12223 completion: Completion,
12224 push_to_history: bool,
12225 cx: &mut ViewContext<Editor>,
12226 ) -> Task<Result<Option<language::Transaction>>> {
12227 self.update(cx, |project, cx| {
12228 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12229 })
12230 }
12231
12232 fn is_completion_trigger(
12233 &self,
12234 buffer: &Model<Buffer>,
12235 position: language::Anchor,
12236 text: &str,
12237 trigger_in_words: bool,
12238 cx: &mut ViewContext<Editor>,
12239 ) -> bool {
12240 if !EditorSettings::get_global(cx).show_completions_on_input {
12241 return false;
12242 }
12243
12244 let mut chars = text.chars();
12245 let char = if let Some(char) = chars.next() {
12246 char
12247 } else {
12248 return false;
12249 };
12250 if chars.next().is_some() {
12251 return false;
12252 }
12253
12254 let buffer = buffer.read(cx);
12255 let scope = buffer.snapshot().language_scope_at(position);
12256 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12257 return true;
12258 }
12259
12260 buffer
12261 .completion_triggers()
12262 .iter()
12263 .any(|string| string == text)
12264 }
12265}
12266
12267fn inlay_hint_settings(
12268 location: Anchor,
12269 snapshot: &MultiBufferSnapshot,
12270 cx: &mut ViewContext<'_, Editor>,
12271) -> InlayHintSettings {
12272 let file = snapshot.file_at(location);
12273 let language = snapshot.language_at(location);
12274 let settings = all_language_settings(file, cx);
12275 settings
12276 .language(language.map(|l| l.name()).as_deref())
12277 .inlay_hints
12278}
12279
12280fn consume_contiguous_rows(
12281 contiguous_row_selections: &mut Vec<Selection<Point>>,
12282 selection: &Selection<Point>,
12283 display_map: &DisplaySnapshot,
12284 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12285) -> (MultiBufferRow, MultiBufferRow) {
12286 contiguous_row_selections.push(selection.clone());
12287 let start_row = MultiBufferRow(selection.start.row);
12288 let mut end_row = ending_row(selection, display_map);
12289
12290 while let Some(next_selection) = selections.peek() {
12291 if next_selection.start.row <= end_row.0 {
12292 end_row = ending_row(next_selection, display_map);
12293 contiguous_row_selections.push(selections.next().unwrap().clone());
12294 } else {
12295 break;
12296 }
12297 }
12298 (start_row, end_row)
12299}
12300
12301fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12302 if next_selection.end.column > 0 || next_selection.is_empty() {
12303 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12304 } else {
12305 MultiBufferRow(next_selection.end.row)
12306 }
12307}
12308
12309impl EditorSnapshot {
12310 pub fn remote_selections_in_range<'a>(
12311 &'a self,
12312 range: &'a Range<Anchor>,
12313 collaboration_hub: &dyn CollaborationHub,
12314 cx: &'a AppContext,
12315 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12316 let participant_names = collaboration_hub.user_names(cx);
12317 let participant_indices = collaboration_hub.user_participant_indices(cx);
12318 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12319 let collaborators_by_replica_id = collaborators_by_peer_id
12320 .iter()
12321 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12322 .collect::<HashMap<_, _>>();
12323 self.buffer_snapshot
12324 .selections_in_range(range, false)
12325 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12326 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12327 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12328 let user_name = participant_names.get(&collaborator.user_id).cloned();
12329 Some(RemoteSelection {
12330 replica_id,
12331 selection,
12332 cursor_shape,
12333 line_mode,
12334 participant_index,
12335 peer_id: collaborator.peer_id,
12336 user_name,
12337 })
12338 })
12339 }
12340
12341 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12342 self.display_snapshot.buffer_snapshot.language_at(position)
12343 }
12344
12345 pub fn is_focused(&self) -> bool {
12346 self.is_focused
12347 }
12348
12349 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12350 self.placeholder_text.as_ref()
12351 }
12352
12353 pub fn scroll_position(&self) -> gpui::Point<f32> {
12354 self.scroll_anchor.scroll_position(&self.display_snapshot)
12355 }
12356
12357 fn gutter_dimensions(
12358 &self,
12359 font_id: FontId,
12360 font_size: Pixels,
12361 em_width: Pixels,
12362 max_line_number_width: Pixels,
12363 cx: &AppContext,
12364 ) -> GutterDimensions {
12365 if !self.show_gutter {
12366 return GutterDimensions::default();
12367 }
12368 let descent = cx.text_system().descent(font_id, font_size);
12369
12370 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12371 matches!(
12372 ProjectSettings::get_global(cx).git.git_gutter,
12373 Some(GitGutterSetting::TrackedFiles)
12374 )
12375 });
12376 let gutter_settings = EditorSettings::get_global(cx).gutter;
12377 let show_line_numbers = self
12378 .show_line_numbers
12379 .unwrap_or(gutter_settings.line_numbers);
12380 let line_gutter_width = if show_line_numbers {
12381 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12382 let min_width_for_number_on_gutter = em_width * 4.0;
12383 max_line_number_width.max(min_width_for_number_on_gutter)
12384 } else {
12385 0.0.into()
12386 };
12387
12388 let show_code_actions = self
12389 .show_code_actions
12390 .unwrap_or(gutter_settings.code_actions);
12391
12392 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12393
12394 let git_blame_entries_width = self
12395 .render_git_blame_gutter
12396 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12397
12398 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12399 left_padding += if show_code_actions || show_runnables {
12400 em_width * 3.0
12401 } else if show_git_gutter && show_line_numbers {
12402 em_width * 2.0
12403 } else if show_git_gutter || show_line_numbers {
12404 em_width
12405 } else {
12406 px(0.)
12407 };
12408
12409 let right_padding = if gutter_settings.folds && show_line_numbers {
12410 em_width * 4.0
12411 } else if gutter_settings.folds {
12412 em_width * 3.0
12413 } else if show_line_numbers {
12414 em_width
12415 } else {
12416 px(0.)
12417 };
12418
12419 GutterDimensions {
12420 left_padding,
12421 right_padding,
12422 width: line_gutter_width + left_padding + right_padding,
12423 margin: -descent,
12424 git_blame_entries_width,
12425 }
12426 }
12427
12428 pub fn render_fold_toggle(
12429 &self,
12430 buffer_row: MultiBufferRow,
12431 row_contains_cursor: bool,
12432 editor: View<Editor>,
12433 cx: &mut WindowContext,
12434 ) -> Option<AnyElement> {
12435 let folded = self.is_line_folded(buffer_row);
12436
12437 if let Some(crease) = self
12438 .crease_snapshot
12439 .query_row(buffer_row, &self.buffer_snapshot)
12440 {
12441 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12442 if folded {
12443 editor.update(cx, |editor, cx| {
12444 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12445 });
12446 } else {
12447 editor.update(cx, |editor, cx| {
12448 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12449 });
12450 }
12451 });
12452
12453 Some((crease.render_toggle)(
12454 buffer_row,
12455 folded,
12456 toggle_callback,
12457 cx,
12458 ))
12459 } else if folded
12460 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12461 {
12462 Some(
12463 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12464 .selected(folded)
12465 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12466 if folded {
12467 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12468 } else {
12469 this.fold_at(&FoldAt { buffer_row }, cx);
12470 }
12471 }))
12472 .into_any_element(),
12473 )
12474 } else {
12475 None
12476 }
12477 }
12478
12479 pub fn render_crease_trailer(
12480 &self,
12481 buffer_row: MultiBufferRow,
12482 cx: &mut WindowContext,
12483 ) -> Option<AnyElement> {
12484 let folded = self.is_line_folded(buffer_row);
12485 let crease = self
12486 .crease_snapshot
12487 .query_row(buffer_row, &self.buffer_snapshot)?;
12488 Some((crease.render_trailer)(buffer_row, folded, cx))
12489 }
12490}
12491
12492impl Deref for EditorSnapshot {
12493 type Target = DisplaySnapshot;
12494
12495 fn deref(&self) -> &Self::Target {
12496 &self.display_snapshot
12497 }
12498}
12499
12500#[derive(Clone, Debug, PartialEq, Eq)]
12501pub enum EditorEvent {
12502 InputIgnored {
12503 text: Arc<str>,
12504 },
12505 InputHandled {
12506 utf16_range_to_replace: Option<Range<isize>>,
12507 text: Arc<str>,
12508 },
12509 ExcerptsAdded {
12510 buffer: Model<Buffer>,
12511 predecessor: ExcerptId,
12512 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12513 },
12514 ExcerptsRemoved {
12515 ids: Vec<ExcerptId>,
12516 },
12517 ExcerptsEdited {
12518 ids: Vec<ExcerptId>,
12519 },
12520 ExcerptsExpanded {
12521 ids: Vec<ExcerptId>,
12522 },
12523 BufferEdited,
12524 Edited {
12525 transaction_id: clock::Lamport,
12526 },
12527 Reparsed(BufferId),
12528 Focused,
12529 FocusedIn,
12530 Blurred,
12531 DirtyChanged,
12532 Saved,
12533 TitleChanged,
12534 DiffBaseChanged,
12535 SelectionsChanged {
12536 local: bool,
12537 },
12538 ScrollPositionChanged {
12539 local: bool,
12540 autoscroll: bool,
12541 },
12542 Closed,
12543 TransactionUndone {
12544 transaction_id: clock::Lamport,
12545 },
12546 TransactionBegun {
12547 transaction_id: clock::Lamport,
12548 },
12549}
12550
12551impl EventEmitter<EditorEvent> for Editor {}
12552
12553impl FocusableView for Editor {
12554 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12555 self.focus_handle.clone()
12556 }
12557}
12558
12559impl Render for Editor {
12560 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12561 let settings = ThemeSettings::get_global(cx);
12562
12563 let text_style = match self.mode {
12564 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12565 color: cx.theme().colors().editor_foreground,
12566 font_family: settings.ui_font.family.clone(),
12567 font_features: settings.ui_font.features.clone(),
12568 font_fallbacks: settings.ui_font.fallbacks.clone(),
12569 font_size: rems(0.875).into(),
12570 font_weight: settings.ui_font.weight,
12571 line_height: relative(settings.buffer_line_height.value()),
12572 ..Default::default()
12573 },
12574 EditorMode::Full => TextStyle {
12575 color: cx.theme().colors().editor_foreground,
12576 font_family: settings.buffer_font.family.clone(),
12577 font_features: settings.buffer_font.features.clone(),
12578 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12579 font_size: settings.buffer_font_size(cx).into(),
12580 font_weight: settings.buffer_font.weight,
12581 line_height: relative(settings.buffer_line_height.value()),
12582 ..Default::default()
12583 },
12584 };
12585
12586 let background = match self.mode {
12587 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12588 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12589 EditorMode::Full => cx.theme().colors().editor_background,
12590 };
12591
12592 EditorElement::new(
12593 cx.view(),
12594 EditorStyle {
12595 background,
12596 local_player: cx.theme().players().local(),
12597 text: text_style,
12598 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12599 syntax: cx.theme().syntax().clone(),
12600 status: cx.theme().status().clone(),
12601 inlay_hints_style: HighlightStyle {
12602 color: Some(cx.theme().status().hint),
12603 ..HighlightStyle::default()
12604 },
12605 suggestions_style: HighlightStyle {
12606 color: Some(cx.theme().status().predictive),
12607 ..HighlightStyle::default()
12608 },
12609 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
12610 },
12611 )
12612 }
12613}
12614
12615impl ViewInputHandler for Editor {
12616 fn text_for_range(
12617 &mut self,
12618 range_utf16: Range<usize>,
12619 cx: &mut ViewContext<Self>,
12620 ) -> Option<String> {
12621 Some(
12622 self.buffer
12623 .read(cx)
12624 .read(cx)
12625 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12626 .collect(),
12627 )
12628 }
12629
12630 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12631 // Prevent the IME menu from appearing when holding down an alphabetic key
12632 // while input is disabled.
12633 if !self.input_enabled {
12634 return None;
12635 }
12636
12637 let range = self.selections.newest::<OffsetUtf16>(cx).range();
12638 Some(range.start.0..range.end.0)
12639 }
12640
12641 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12642 let snapshot = self.buffer.read(cx).read(cx);
12643 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12644 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12645 }
12646
12647 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12648 self.clear_highlights::<InputComposition>(cx);
12649 self.ime_transaction.take();
12650 }
12651
12652 fn replace_text_in_range(
12653 &mut self,
12654 range_utf16: Option<Range<usize>>,
12655 text: &str,
12656 cx: &mut ViewContext<Self>,
12657 ) {
12658 if !self.input_enabled {
12659 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12660 return;
12661 }
12662
12663 self.transact(cx, |this, cx| {
12664 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12665 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12666 Some(this.selection_replacement_ranges(range_utf16, cx))
12667 } else {
12668 this.marked_text_ranges(cx)
12669 };
12670
12671 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12672 let newest_selection_id = this.selections.newest_anchor().id;
12673 this.selections
12674 .all::<OffsetUtf16>(cx)
12675 .iter()
12676 .zip(ranges_to_replace.iter())
12677 .find_map(|(selection, range)| {
12678 if selection.id == newest_selection_id {
12679 Some(
12680 (range.start.0 as isize - selection.head().0 as isize)
12681 ..(range.end.0 as isize - selection.head().0 as isize),
12682 )
12683 } else {
12684 None
12685 }
12686 })
12687 });
12688
12689 cx.emit(EditorEvent::InputHandled {
12690 utf16_range_to_replace: range_to_replace,
12691 text: text.into(),
12692 });
12693
12694 if let Some(new_selected_ranges) = new_selected_ranges {
12695 this.change_selections(None, cx, |selections| {
12696 selections.select_ranges(new_selected_ranges)
12697 });
12698 this.backspace(&Default::default(), cx);
12699 }
12700
12701 this.handle_input(text, cx);
12702 });
12703
12704 if let Some(transaction) = self.ime_transaction {
12705 self.buffer.update(cx, |buffer, cx| {
12706 buffer.group_until_transaction(transaction, cx);
12707 });
12708 }
12709
12710 self.unmark_text(cx);
12711 }
12712
12713 fn replace_and_mark_text_in_range(
12714 &mut self,
12715 range_utf16: Option<Range<usize>>,
12716 text: &str,
12717 new_selected_range_utf16: Option<Range<usize>>,
12718 cx: &mut ViewContext<Self>,
12719 ) {
12720 if !self.input_enabled {
12721 return;
12722 }
12723
12724 let transaction = self.transact(cx, |this, cx| {
12725 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12726 let snapshot = this.buffer.read(cx).read(cx);
12727 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12728 for marked_range in &mut marked_ranges {
12729 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12730 marked_range.start.0 += relative_range_utf16.start;
12731 marked_range.start =
12732 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12733 marked_range.end =
12734 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12735 }
12736 }
12737 Some(marked_ranges)
12738 } else if let Some(range_utf16) = range_utf16 {
12739 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12740 Some(this.selection_replacement_ranges(range_utf16, cx))
12741 } else {
12742 None
12743 };
12744
12745 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12746 let newest_selection_id = this.selections.newest_anchor().id;
12747 this.selections
12748 .all::<OffsetUtf16>(cx)
12749 .iter()
12750 .zip(ranges_to_replace.iter())
12751 .find_map(|(selection, range)| {
12752 if selection.id == newest_selection_id {
12753 Some(
12754 (range.start.0 as isize - selection.head().0 as isize)
12755 ..(range.end.0 as isize - selection.head().0 as isize),
12756 )
12757 } else {
12758 None
12759 }
12760 })
12761 });
12762
12763 cx.emit(EditorEvent::InputHandled {
12764 utf16_range_to_replace: range_to_replace,
12765 text: text.into(),
12766 });
12767
12768 if let Some(ranges) = ranges_to_replace {
12769 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12770 }
12771
12772 let marked_ranges = {
12773 let snapshot = this.buffer.read(cx).read(cx);
12774 this.selections
12775 .disjoint_anchors()
12776 .iter()
12777 .map(|selection| {
12778 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12779 })
12780 .collect::<Vec<_>>()
12781 };
12782
12783 if text.is_empty() {
12784 this.unmark_text(cx);
12785 } else {
12786 this.highlight_text::<InputComposition>(
12787 marked_ranges.clone(),
12788 HighlightStyle {
12789 underline: Some(UnderlineStyle {
12790 thickness: px(1.),
12791 color: None,
12792 wavy: false,
12793 }),
12794 ..Default::default()
12795 },
12796 cx,
12797 );
12798 }
12799
12800 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12801 let use_autoclose = this.use_autoclose;
12802 let use_auto_surround = this.use_auto_surround;
12803 this.set_use_autoclose(false);
12804 this.set_use_auto_surround(false);
12805 this.handle_input(text, cx);
12806 this.set_use_autoclose(use_autoclose);
12807 this.set_use_auto_surround(use_auto_surround);
12808
12809 if let Some(new_selected_range) = new_selected_range_utf16 {
12810 let snapshot = this.buffer.read(cx).read(cx);
12811 let new_selected_ranges = marked_ranges
12812 .into_iter()
12813 .map(|marked_range| {
12814 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12815 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12816 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12817 snapshot.clip_offset_utf16(new_start, Bias::Left)
12818 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12819 })
12820 .collect::<Vec<_>>();
12821
12822 drop(snapshot);
12823 this.change_selections(None, cx, |selections| {
12824 selections.select_ranges(new_selected_ranges)
12825 });
12826 }
12827 });
12828
12829 self.ime_transaction = self.ime_transaction.or(transaction);
12830 if let Some(transaction) = self.ime_transaction {
12831 self.buffer.update(cx, |buffer, cx| {
12832 buffer.group_until_transaction(transaction, cx);
12833 });
12834 }
12835
12836 if self.text_highlights::<InputComposition>(cx).is_none() {
12837 self.ime_transaction.take();
12838 }
12839 }
12840
12841 fn bounds_for_range(
12842 &mut self,
12843 range_utf16: Range<usize>,
12844 element_bounds: gpui::Bounds<Pixels>,
12845 cx: &mut ViewContext<Self>,
12846 ) -> Option<gpui::Bounds<Pixels>> {
12847 let text_layout_details = self.text_layout_details(cx);
12848 let style = &text_layout_details.editor_style;
12849 let font_id = cx.text_system().resolve_font(&style.text.font());
12850 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12851 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12852
12853 let em_width = cx
12854 .text_system()
12855 .typographic_bounds(font_id, font_size, 'm')
12856 .unwrap()
12857 .size
12858 .width;
12859
12860 let snapshot = self.snapshot(cx);
12861 let scroll_position = snapshot.scroll_position();
12862 let scroll_left = scroll_position.x * em_width;
12863
12864 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12865 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12866 + self.gutter_dimensions.width;
12867 let y = line_height * (start.row().as_f32() - scroll_position.y);
12868
12869 Some(Bounds {
12870 origin: element_bounds.origin + point(x, y),
12871 size: size(em_width, line_height),
12872 })
12873 }
12874}
12875
12876trait SelectionExt {
12877 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12878 fn spanned_rows(
12879 &self,
12880 include_end_if_at_line_start: bool,
12881 map: &DisplaySnapshot,
12882 ) -> Range<MultiBufferRow>;
12883}
12884
12885impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12886 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12887 let start = self
12888 .start
12889 .to_point(&map.buffer_snapshot)
12890 .to_display_point(map);
12891 let end = self
12892 .end
12893 .to_point(&map.buffer_snapshot)
12894 .to_display_point(map);
12895 if self.reversed {
12896 end..start
12897 } else {
12898 start..end
12899 }
12900 }
12901
12902 fn spanned_rows(
12903 &self,
12904 include_end_if_at_line_start: bool,
12905 map: &DisplaySnapshot,
12906 ) -> Range<MultiBufferRow> {
12907 let start = self.start.to_point(&map.buffer_snapshot);
12908 let mut end = self.end.to_point(&map.buffer_snapshot);
12909 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12910 end.row -= 1;
12911 }
12912
12913 let buffer_start = map.prev_line_boundary(start).0;
12914 let buffer_end = map.next_line_boundary(end).0;
12915 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12916 }
12917}
12918
12919impl<T: InvalidationRegion> InvalidationStack<T> {
12920 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12921 where
12922 S: Clone + ToOffset,
12923 {
12924 while let Some(region) = self.last() {
12925 let all_selections_inside_invalidation_ranges =
12926 if selections.len() == region.ranges().len() {
12927 selections
12928 .iter()
12929 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12930 .all(|(selection, invalidation_range)| {
12931 let head = selection.head().to_offset(buffer);
12932 invalidation_range.start <= head && invalidation_range.end >= head
12933 })
12934 } else {
12935 false
12936 };
12937
12938 if all_selections_inside_invalidation_ranges {
12939 break;
12940 } else {
12941 self.pop();
12942 }
12943 }
12944 }
12945}
12946
12947impl<T> Default for InvalidationStack<T> {
12948 fn default() -> Self {
12949 Self(Default::default())
12950 }
12951}
12952
12953impl<T> Deref for InvalidationStack<T> {
12954 type Target = Vec<T>;
12955
12956 fn deref(&self) -> &Self::Target {
12957 &self.0
12958 }
12959}
12960
12961impl<T> DerefMut for InvalidationStack<T> {
12962 fn deref_mut(&mut self) -> &mut Self::Target {
12963 &mut self.0
12964 }
12965}
12966
12967impl InvalidationRegion for SnippetState {
12968 fn ranges(&self) -> &[Range<Anchor>] {
12969 &self.ranges[self.active_index]
12970 }
12971}
12972
12973pub fn diagnostic_block_renderer(
12974 diagnostic: Diagnostic,
12975 max_message_rows: Option<u8>,
12976 allow_closing: bool,
12977 _is_valid: bool,
12978) -> RenderBlock {
12979 let (text_without_backticks, code_ranges) =
12980 highlight_diagnostic_message(&diagnostic, max_message_rows);
12981
12982 Box::new(move |cx: &mut BlockContext| {
12983 let group_id: SharedString = cx.block_id.to_string().into();
12984
12985 let mut text_style = cx.text_style().clone();
12986 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12987 let theme_settings = ThemeSettings::get_global(cx);
12988 text_style.font_family = theme_settings.buffer_font.family.clone();
12989 text_style.font_style = theme_settings.buffer_font.style;
12990 text_style.font_features = theme_settings.buffer_font.features.clone();
12991 text_style.font_weight = theme_settings.buffer_font.weight;
12992
12993 let multi_line_diagnostic = diagnostic.message.contains('\n');
12994
12995 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
12996 if multi_line_diagnostic {
12997 v_flex()
12998 } else {
12999 h_flex()
13000 }
13001 .when(allow_closing, |div| {
13002 div.children(diagnostic.is_primary.then(|| {
13003 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13004 .icon_color(Color::Muted)
13005 .size(ButtonSize::Compact)
13006 .style(ButtonStyle::Transparent)
13007 .visible_on_hover(group_id.clone())
13008 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13009 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13010 }))
13011 })
13012 .child(
13013 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13014 .icon_color(Color::Muted)
13015 .size(ButtonSize::Compact)
13016 .style(ButtonStyle::Transparent)
13017 .visible_on_hover(group_id.clone())
13018 .on_click({
13019 let message = diagnostic.message.clone();
13020 move |_click, cx| {
13021 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13022 }
13023 })
13024 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13025 )
13026 };
13027
13028 let icon_size = buttons(&diagnostic, cx.block_id)
13029 .into_any_element()
13030 .layout_as_root(AvailableSpace::min_size(), cx);
13031
13032 h_flex()
13033 .id(cx.block_id)
13034 .group(group_id.clone())
13035 .relative()
13036 .size_full()
13037 .pl(cx.gutter_dimensions.width)
13038 .w(cx.max_width + cx.gutter_dimensions.width)
13039 .child(
13040 div()
13041 .flex()
13042 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13043 .flex_shrink(),
13044 )
13045 .child(buttons(&diagnostic, cx.block_id))
13046 .child(div().flex().flex_shrink_0().child(
13047 StyledText::new(text_without_backticks.clone()).with_highlights(
13048 &text_style,
13049 code_ranges.iter().map(|range| {
13050 (
13051 range.clone(),
13052 HighlightStyle {
13053 font_weight: Some(FontWeight::BOLD),
13054 ..Default::default()
13055 },
13056 )
13057 }),
13058 ),
13059 ))
13060 .into_any_element()
13061 })
13062}
13063
13064pub fn highlight_diagnostic_message(
13065 diagnostic: &Diagnostic,
13066 mut max_message_rows: Option<u8>,
13067) -> (SharedString, Vec<Range<usize>>) {
13068 let mut text_without_backticks = String::new();
13069 let mut code_ranges = Vec::new();
13070
13071 if let Some(source) = &diagnostic.source {
13072 text_without_backticks.push_str(&source);
13073 code_ranges.push(0..source.len());
13074 text_without_backticks.push_str(": ");
13075 }
13076
13077 let mut prev_offset = 0;
13078 let mut in_code_block = false;
13079 let has_row_limit = max_message_rows.is_some();
13080 let mut newline_indices = diagnostic
13081 .message
13082 .match_indices('\n')
13083 .filter(|_| has_row_limit)
13084 .map(|(ix, _)| ix)
13085 .fuse()
13086 .peekable();
13087
13088 for (quote_ix, _) in diagnostic
13089 .message
13090 .match_indices('`')
13091 .chain([(diagnostic.message.len(), "")])
13092 {
13093 let mut first_newline_ix = None;
13094 let mut last_newline_ix = None;
13095 while let Some(newline_ix) = newline_indices.peek() {
13096 if *newline_ix < quote_ix {
13097 if first_newline_ix.is_none() {
13098 first_newline_ix = Some(*newline_ix);
13099 }
13100 last_newline_ix = Some(*newline_ix);
13101
13102 if let Some(rows_left) = &mut max_message_rows {
13103 if *rows_left == 0 {
13104 break;
13105 } else {
13106 *rows_left -= 1;
13107 }
13108 }
13109 let _ = newline_indices.next();
13110 } else {
13111 break;
13112 }
13113 }
13114 let prev_len = text_without_backticks.len();
13115 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13116 text_without_backticks.push_str(new_text);
13117 if in_code_block {
13118 code_ranges.push(prev_len..text_without_backticks.len());
13119 }
13120 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13121 in_code_block = !in_code_block;
13122 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13123 text_without_backticks.push_str("...");
13124 break;
13125 }
13126 }
13127
13128 (text_without_backticks.into(), code_ranges)
13129}
13130
13131fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13132 match severity {
13133 DiagnosticSeverity::ERROR => colors.error,
13134 DiagnosticSeverity::WARNING => colors.warning,
13135 DiagnosticSeverity::INFORMATION => colors.info,
13136 DiagnosticSeverity::HINT => colors.info,
13137 _ => colors.ignored,
13138 }
13139}
13140
13141pub fn styled_runs_for_code_label<'a>(
13142 label: &'a CodeLabel,
13143 syntax_theme: &'a theme::SyntaxTheme,
13144) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13145 let fade_out = HighlightStyle {
13146 fade_out: Some(0.35),
13147 ..Default::default()
13148 };
13149
13150 let mut prev_end = label.filter_range.end;
13151 label
13152 .runs
13153 .iter()
13154 .enumerate()
13155 .flat_map(move |(ix, (range, highlight_id))| {
13156 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13157 style
13158 } else {
13159 return Default::default();
13160 };
13161 let mut muted_style = style;
13162 muted_style.highlight(fade_out);
13163
13164 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13165 if range.start >= label.filter_range.end {
13166 if range.start > prev_end {
13167 runs.push((prev_end..range.start, fade_out));
13168 }
13169 runs.push((range.clone(), muted_style));
13170 } else if range.end <= label.filter_range.end {
13171 runs.push((range.clone(), style));
13172 } else {
13173 runs.push((range.start..label.filter_range.end, style));
13174 runs.push((label.filter_range.end..range.end, muted_style));
13175 }
13176 prev_end = cmp::max(prev_end, range.end);
13177
13178 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13179 runs.push((prev_end..label.text.len(), fade_out));
13180 }
13181
13182 runs
13183 })
13184}
13185
13186pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13187 let mut prev_index = 0;
13188 let mut prev_codepoint: Option<char> = None;
13189 text.char_indices()
13190 .chain([(text.len(), '\0')])
13191 .filter_map(move |(index, codepoint)| {
13192 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13193 let is_boundary = index == text.len()
13194 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13195 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13196 if is_boundary {
13197 let chunk = &text[prev_index..index];
13198 prev_index = index;
13199 Some(chunk)
13200 } else {
13201 None
13202 }
13203 })
13204}
13205
13206pub trait RangeToAnchorExt: Sized {
13207 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13208
13209 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13210 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13211 anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13212 }
13213}
13214
13215impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13216 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13217 let start_offset = self.start.to_offset(snapshot);
13218 let end_offset = self.end.to_offset(snapshot);
13219 if start_offset == end_offset {
13220 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13221 } else {
13222 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13223 }
13224 }
13225}
13226
13227pub trait RowExt {
13228 fn as_f32(&self) -> f32;
13229
13230 fn next_row(&self) -> Self;
13231
13232 fn previous_row(&self) -> Self;
13233
13234 fn minus(&self, other: Self) -> u32;
13235}
13236
13237impl RowExt for DisplayRow {
13238 fn as_f32(&self) -> f32 {
13239 self.0 as f32
13240 }
13241
13242 fn next_row(&self) -> Self {
13243 Self(self.0 + 1)
13244 }
13245
13246 fn previous_row(&self) -> Self {
13247 Self(self.0.saturating_sub(1))
13248 }
13249
13250 fn minus(&self, other: Self) -> u32 {
13251 self.0 - other.0
13252 }
13253}
13254
13255impl RowExt for MultiBufferRow {
13256 fn as_f32(&self) -> f32 {
13257 self.0 as f32
13258 }
13259
13260 fn next_row(&self) -> Self {
13261 Self(self.0 + 1)
13262 }
13263
13264 fn previous_row(&self) -> Self {
13265 Self(self.0.saturating_sub(1))
13266 }
13267
13268 fn minus(&self, other: Self) -> u32 {
13269 self.0 - other.0
13270 }
13271}
13272
13273trait RowRangeExt {
13274 type Row;
13275
13276 fn len(&self) -> usize;
13277
13278 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13279}
13280
13281impl RowRangeExt for Range<MultiBufferRow> {
13282 type Row = MultiBufferRow;
13283
13284 fn len(&self) -> usize {
13285 (self.end.0 - self.start.0) as usize
13286 }
13287
13288 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13289 (self.start.0..self.end.0).map(MultiBufferRow)
13290 }
13291}
13292
13293impl RowRangeExt for Range<DisplayRow> {
13294 type Row = DisplayRow;
13295
13296 fn len(&self) -> usize {
13297 (self.end.0 - self.start.0) as usize
13298 }
13299
13300 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13301 (self.start.0..self.end.0).map(DisplayRow)
13302 }
13303}
13304
13305fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13306 if hunk.diff_base_byte_range.is_empty() {
13307 DiffHunkStatus::Added
13308 } else if hunk.associated_range.is_empty() {
13309 DiffHunkStatus::Removed
13310 } else {
13311 DiffHunkStatus::Modified
13312 }
13313}
13314
13315/// If select range has more than one line, we
13316/// just point the cursor to range.start.
13317fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13318 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13319 range
13320 } else {
13321 range.start..range.start
13322 }
13323}