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 debounced_delay;
19pub mod display_map;
20mod editor_settings;
21mod editor_settings_controls;
22mod element;
23mod git;
24mod highlight_matching_bracket;
25mod hover_links;
26mod hover_popover;
27mod hunk_diff;
28mod indent_guides;
29mod inlay_hint_cache;
30mod inline_completion_provider;
31pub mod items;
32mod linked_editing_ranges;
33mod mouse_context_menu;
34pub mod movement;
35mod persistence;
36mod rust_analyzer_ext;
37pub mod scroll;
38mod selections_collection;
39pub mod tasks;
40
41#[cfg(test)]
42mod editor_tests;
43mod signature_help;
44#[cfg(any(test, feature = "test-support"))]
45pub mod test;
46
47use ::git::diff::{DiffHunk, DiffHunkStatus};
48use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
49pub(crate) use actions::*;
50use aho_corasick::AhoCorasick;
51use anyhow::{anyhow, Context as _, Result};
52use blink_manager::BlinkManager;
53use client::{Collaborator, ParticipantIndex};
54use clock::ReplicaId;
55use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
56use convert_case::{Case, Casing};
57use debounced_delay::DebouncedDelay;
58use display_map::*;
59pub use display_map::{DisplayPoint, FoldPlaceholder};
60pub use editor_settings::{CurrentLineHighlight, EditorSettings};
61pub use editor_settings_controls::*;
62use element::LineWithInvisibles;
63pub use element::{
64 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
65};
66use futures::FutureExt;
67use fuzzy::{StringMatch, StringMatchCandidate};
68use git::blame::GitBlame;
69use git::diff_hunk_to_display;
70use gpui::{
71 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
72 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
73 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
74 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
75 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
76 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
77 UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext,
78 WeakFocusHandle, WeakView, WindowContext,
79};
80use highlight_matching_bracket::refresh_matching_bracket_highlights;
81use hover_popover::{hide_hover, HoverState};
82use hunk_diff::ExpandedHunks;
83pub(crate) use hunk_diff::HoveredHunk;
84use indent_guides::ActiveIndentGuidesState;
85use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
86pub use inline_completion_provider::*;
87pub use items::MAX_TAB_TITLE_LEN;
88use itertools::Itertools;
89use language::{
90 char_kind,
91 language_settings::{self, all_language_settings, InlayHintSettings},
92 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
93 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
94 Point, Selection, SelectionGoal, TransactionId,
95};
96use language::{point_to_lsp, BufferRow, Runnable, RunnableRange};
97use linked_editing_ranges::refresh_linked_ranges;
98use task::{ResolvedTask, TaskTemplate, TaskVariables};
99
100use hover_links::{HoverLink, HoveredLinkState, InlayHighlight};
101pub use lsp::CompletionContext;
102use lsp::{
103 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
104 LanguageServerId,
105};
106use mouse_context_menu::MouseContextMenu;
107use movement::TextLayoutDetails;
108pub use multi_buffer::{
109 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
110 ToPoint,
111};
112use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
113use ordered_float::OrderedFloat;
114use parking_lot::{Mutex, RwLock};
115use project::project_settings::{GitGutterSetting, ProjectSettings};
116use project::{
117 CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
118 ProjectTransaction, TaskSourceKind, WorktreeId,
119};
120use rand::prelude::*;
121use rpc::{proto::*, ErrorExt};
122use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
123use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
124use serde::{Deserialize, Serialize};
125use settings::{update_settings_file, Settings, SettingsStore};
126use smallvec::SmallVec;
127use snippet::Snippet;
128use std::{
129 any::TypeId,
130 borrow::Cow,
131 cell::RefCell,
132 cmp::{self, Ordering, Reverse},
133 mem,
134 num::NonZeroU32,
135 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
136 path::{Path, PathBuf},
137 rc::Rc,
138 sync::Arc,
139 time::{Duration, Instant},
140};
141pub use sum_tree::Bias;
142use sum_tree::TreeMap;
143use text::{BufferId, OffsetUtf16, Rope};
144use theme::{
145 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
146 ThemeColors, ThemeSettings,
147};
148use ui::{
149 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
150 ListItem, Popover, Tooltip,
151};
152use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
153use workspace::item::{ItemHandle, PreviewTabsSettings};
154use workspace::notifications::{DetachAndPromptErr, NotificationId};
155use workspace::{
156 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
157};
158use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
159
160use crate::hover_links::find_url;
161use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
162
163pub const FILE_HEADER_HEIGHT: u32 = 1;
164pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
165pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
166pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
167const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
168const MAX_LINE_LEN: usize = 1024;
169const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
170const MAX_SELECTION_HISTORY_LEN: usize = 1024;
171pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
172#[doc(hidden)]
173pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
174#[doc(hidden)]
175pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
176
177pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
178pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
179
180pub fn render_parsed_markdown(
181 element_id: impl Into<ElementId>,
182 parsed: &language::ParsedMarkdown,
183 editor_style: &EditorStyle,
184 workspace: Option<WeakView<Workspace>>,
185 cx: &mut WindowContext,
186) -> InteractiveText {
187 let code_span_background_color = cx
188 .theme()
189 .colors()
190 .editor_document_highlight_read_background;
191
192 let highlights = gpui::combine_highlights(
193 parsed.highlights.iter().filter_map(|(range, highlight)| {
194 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
195 Some((range.clone(), highlight))
196 }),
197 parsed
198 .regions
199 .iter()
200 .zip(&parsed.region_ranges)
201 .filter_map(|(region, range)| {
202 if region.code {
203 Some((
204 range.clone(),
205 HighlightStyle {
206 background_color: Some(code_span_background_color),
207 ..Default::default()
208 },
209 ))
210 } else {
211 None
212 }
213 }),
214 );
215
216 let mut links = Vec::new();
217 let mut link_ranges = Vec::new();
218 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
219 if let Some(link) = region.link.clone() {
220 links.push(link);
221 link_ranges.push(range.clone());
222 }
223 }
224
225 InteractiveText::new(
226 element_id,
227 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
228 )
229 .on_click(link_ranges, move |clicked_range_ix, cx| {
230 match &links[clicked_range_ix] {
231 markdown::Link::Web { url } => cx.open_url(url),
232 markdown::Link::Path { path } => {
233 if let Some(workspace) = &workspace {
234 _ = workspace.update(cx, |workspace, cx| {
235 workspace.open_abs_path(path.clone(), false, cx).detach();
236 });
237 }
238 }
239 }
240 })
241}
242
243#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
244pub(crate) enum InlayId {
245 Suggestion(usize),
246 Hint(usize),
247}
248
249impl InlayId {
250 fn id(&self) -> usize {
251 match self {
252 Self::Suggestion(id) => *id,
253 Self::Hint(id) => *id,
254 }
255 }
256}
257
258enum DiffRowHighlight {}
259enum DocumentHighlightRead {}
260enum DocumentHighlightWrite {}
261enum InputComposition {}
262
263#[derive(Copy, Clone, PartialEq, Eq)]
264pub enum Direction {
265 Prev,
266 Next,
267}
268
269#[derive(Debug, Copy, Clone, PartialEq, Eq)]
270pub enum Navigated {
271 Yes,
272 No,
273}
274
275impl Navigated {
276 pub fn from_bool(yes: bool) -> Navigated {
277 if yes {
278 Navigated::Yes
279 } else {
280 Navigated::No
281 }
282 }
283}
284
285pub fn init_settings(cx: &mut AppContext) {
286 EditorSettings::register(cx);
287}
288
289pub fn init(cx: &mut AppContext) {
290 init_settings(cx);
291
292 workspace::register_project_item::<Editor>(cx);
293 workspace::FollowableViewRegistry::register::<Editor>(cx);
294 workspace::register_serializable_item::<Editor>(cx);
295
296 cx.observe_new_views(
297 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
298 workspace.register_action(Editor::new_file);
299 workspace.register_action(Editor::new_file_in_direction);
300 },
301 )
302 .detach();
303
304 cx.on_action(move |_: &workspace::NewFile, cx| {
305 let app_state = workspace::AppState::global(cx);
306 if let Some(app_state) = app_state.upgrade() {
307 workspace::open_new(app_state, cx, |workspace, cx| {
308 Editor::new_file(workspace, &Default::default(), cx)
309 })
310 .detach();
311 }
312 });
313 cx.on_action(move |_: &workspace::NewWindow, cx| {
314 let app_state = workspace::AppState::global(cx);
315 if let Some(app_state) = app_state.upgrade() {
316 workspace::open_new(app_state, cx, |workspace, cx| {
317 Editor::new_file(workspace, &Default::default(), cx)
318 })
319 .detach();
320 }
321 });
322}
323
324pub struct SearchWithinRange;
325
326trait InvalidationRegion {
327 fn ranges(&self) -> &[Range<Anchor>];
328}
329
330#[derive(Clone, Debug, PartialEq)]
331pub enum SelectPhase {
332 Begin {
333 position: DisplayPoint,
334 add: bool,
335 click_count: usize,
336 },
337 BeginColumnar {
338 position: DisplayPoint,
339 reset: bool,
340 goal_column: u32,
341 },
342 Extend {
343 position: DisplayPoint,
344 click_count: usize,
345 },
346 Update {
347 position: DisplayPoint,
348 goal_column: u32,
349 scroll_delta: gpui::Point<f32>,
350 },
351 End,
352}
353
354#[derive(Clone, Debug)]
355pub enum SelectMode {
356 Character,
357 Word(Range<Anchor>),
358 Line(Range<Anchor>),
359 All,
360}
361
362#[derive(Copy, Clone, PartialEq, Eq, Debug)]
363pub enum EditorMode {
364 SingleLine { auto_width: bool },
365 AutoHeight { max_lines: usize },
366 Full,
367}
368
369#[derive(Clone, Debug)]
370pub enum SoftWrap {
371 None,
372 PreferLine,
373 EditorWidth,
374 Column(u32),
375}
376
377#[derive(Clone)]
378pub struct EditorStyle {
379 pub background: Hsla,
380 pub local_player: PlayerColor,
381 pub text: TextStyle,
382 pub scrollbar_width: Pixels,
383 pub syntax: Arc<SyntaxTheme>,
384 pub status: StatusColors,
385 pub inlay_hints_style: HighlightStyle,
386 pub suggestions_style: HighlightStyle,
387}
388
389impl Default for EditorStyle {
390 fn default() -> Self {
391 Self {
392 background: Hsla::default(),
393 local_player: PlayerColor::default(),
394 text: TextStyle::default(),
395 scrollbar_width: Pixels::default(),
396 syntax: Default::default(),
397 // HACK: Status colors don't have a real default.
398 // We should look into removing the status colors from the editor
399 // style and retrieve them directly from the theme.
400 status: StatusColors::dark(),
401 inlay_hints_style: HighlightStyle::default(),
402 suggestions_style: HighlightStyle::default(),
403 }
404 }
405}
406
407type CompletionId = usize;
408
409#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
410struct EditorActionId(usize);
411
412impl EditorActionId {
413 pub fn post_inc(&mut self) -> Self {
414 let answer = self.0;
415
416 *self = Self(answer + 1);
417
418 Self(answer)
419 }
420}
421
422// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
423// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
424
425type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
426type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
427
428#[derive(Default)]
429struct ScrollbarMarkerState {
430 scrollbar_size: Size<Pixels>,
431 dirty: bool,
432 markers: Arc<[PaintQuad]>,
433 pending_refresh: Option<Task<Result<()>>>,
434}
435
436impl ScrollbarMarkerState {
437 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
438 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
439 }
440}
441
442#[derive(Clone, Debug)]
443struct RunnableTasks {
444 templates: Vec<(TaskSourceKind, TaskTemplate)>,
445 offset: MultiBufferOffset,
446 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
447 column: u32,
448 // Values of all named captures, including those starting with '_'
449 extra_variables: HashMap<String, String>,
450 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
451 context_range: Range<BufferOffset>,
452}
453
454#[derive(Clone)]
455struct ResolvedTasks {
456 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
457 position: Anchor,
458}
459#[derive(Copy, Clone, Debug)]
460struct MultiBufferOffset(usize);
461#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
462struct BufferOffset(usize);
463/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
464///
465/// See the [module level documentation](self) for more information.
466pub struct Editor {
467 focus_handle: FocusHandle,
468 last_focused_descendant: Option<WeakFocusHandle>,
469 /// The text buffer being edited
470 buffer: Model<MultiBuffer>,
471 /// Map of how text in the buffer should be displayed.
472 /// Handles soft wraps, folds, fake inlay text insertions, etc.
473 pub display_map: Model<DisplayMap>,
474 pub selections: SelectionsCollection,
475 pub scroll_manager: ScrollManager,
476 /// When inline assist editors are linked, they all render cursors because
477 /// typing enters text into each of them, even the ones that aren't focused.
478 pub(crate) show_cursor_when_unfocused: bool,
479 columnar_selection_tail: Option<Anchor>,
480 add_selections_state: Option<AddSelectionsState>,
481 select_next_state: Option<SelectNextState>,
482 select_prev_state: Option<SelectNextState>,
483 selection_history: SelectionHistory,
484 autoclose_regions: Vec<AutocloseRegion>,
485 snippet_stack: InvalidationStack<SnippetState>,
486 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
487 ime_transaction: Option<TransactionId>,
488 active_diagnostics: Option<ActiveDiagnosticGroup>,
489 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
490 project: Option<Model<Project>>,
491 completion_provider: Option<Box<dyn CompletionProvider>>,
492 collaboration_hub: Option<Box<dyn CollaborationHub>>,
493 blink_manager: Model<BlinkManager>,
494 show_cursor_names: bool,
495 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
496 pub show_local_selections: bool,
497 mode: EditorMode,
498 show_breadcrumbs: bool,
499 show_gutter: bool,
500 show_line_numbers: Option<bool>,
501 show_git_diff_gutter: Option<bool>,
502 show_code_actions: Option<bool>,
503 show_runnables: Option<bool>,
504 show_wrap_guides: Option<bool>,
505 show_indent_guides: Option<bool>,
506 placeholder_text: Option<Arc<str>>,
507 highlight_order: usize,
508 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
509 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
510 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
511 scrollbar_marker_state: ScrollbarMarkerState,
512 active_indent_guides_state: ActiveIndentGuidesState,
513 nav_history: Option<ItemNavHistory>,
514 context_menu: RwLock<Option<ContextMenu>>,
515 mouse_context_menu: Option<MouseContextMenu>,
516 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
517 signature_help_state: SignatureHelpState,
518 auto_signature_help: Option<bool>,
519 find_all_references_task_sources: Vec<Anchor>,
520 next_completion_id: CompletionId,
521 completion_documentation_pre_resolve_debounce: DebouncedDelay,
522 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
523 code_actions_task: Option<Task<()>>,
524 document_highlights_task: Option<Task<()>>,
525 linked_editing_range_task: Option<Task<Option<()>>>,
526 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
527 pending_rename: Option<RenameState>,
528 searchable: bool,
529 cursor_shape: CursorShape,
530 current_line_highlight: Option<CurrentLineHighlight>,
531 collapse_matches: bool,
532 autoindent_mode: Option<AutoindentMode>,
533 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
534 keymap_context_layers: BTreeMap<TypeId, KeyContext>,
535 input_enabled: bool,
536 use_modal_editing: bool,
537 read_only: bool,
538 leader_peer_id: Option<PeerId>,
539 remote_id: Option<ViewId>,
540 hover_state: HoverState,
541 gutter_hovered: bool,
542 hovered_link_state: Option<HoveredLinkState>,
543 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
544 active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
545 show_inline_completions: bool,
546 inlay_hint_cache: InlayHintCache,
547 expanded_hunks: ExpandedHunks,
548 next_inlay_id: usize,
549 _subscriptions: Vec<Subscription>,
550 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
551 gutter_dimensions: GutterDimensions,
552 pub vim_replace_map: HashMap<Range<usize>, String>,
553 style: Option<EditorStyle>,
554 next_editor_action_id: EditorActionId,
555 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
556 use_autoclose: bool,
557 use_auto_surround: bool,
558 auto_replace_emoji_shortcode: bool,
559 show_git_blame_gutter: bool,
560 show_git_blame_inline: bool,
561 show_git_blame_inline_delay_task: Option<Task<()>>,
562 git_blame_inline_enabled: bool,
563 serialize_dirty_buffers: bool,
564 show_selection_menu: Option<bool>,
565 blame: Option<Model<GitBlame>>,
566 blame_subscription: Option<Subscription>,
567 custom_context_menu: Option<
568 Box<
569 dyn 'static
570 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
571 >,
572 >,
573 last_bounds: Option<Bounds<Pixels>>,
574 expect_bounds_change: Option<Bounds<Pixels>>,
575 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
576 tasks_update_task: Option<Task<()>>,
577 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
578 file_header_size: u32,
579 breadcrumb_header: Option<String>,
580 focused_block: Option<FocusedBlock>,
581 next_scroll_position: NextScrollCursorCenterTopBottom,
582 _scroll_cursor_center_top_bottom_task: Task<()>,
583}
584
585#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
586enum NextScrollCursorCenterTopBottom {
587 #[default]
588 Center,
589 Top,
590 Bottom,
591}
592
593impl NextScrollCursorCenterTopBottom {
594 fn next(&self) -> Self {
595 match self {
596 Self::Center => Self::Top,
597 Self::Top => Self::Bottom,
598 Self::Bottom => Self::Center,
599 }
600 }
601}
602
603#[derive(Clone)]
604pub struct EditorSnapshot {
605 pub mode: EditorMode,
606 show_gutter: bool,
607 show_line_numbers: Option<bool>,
608 show_git_diff_gutter: Option<bool>,
609 show_code_actions: Option<bool>,
610 show_runnables: Option<bool>,
611 render_git_blame_gutter: bool,
612 pub display_snapshot: DisplaySnapshot,
613 pub placeholder_text: Option<Arc<str>>,
614 is_focused: bool,
615 scroll_anchor: ScrollAnchor,
616 ongoing_scroll: OngoingScroll,
617 current_line_highlight: CurrentLineHighlight,
618 gutter_hovered: bool,
619}
620
621const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
622
623#[derive(Default, Debug, Clone, Copy)]
624pub struct GutterDimensions {
625 pub left_padding: Pixels,
626 pub right_padding: Pixels,
627 pub width: Pixels,
628 pub margin: Pixels,
629 pub git_blame_entries_width: Option<Pixels>,
630}
631
632impl GutterDimensions {
633 /// The full width of the space taken up by the gutter.
634 pub fn full_width(&self) -> Pixels {
635 self.margin + self.width
636 }
637
638 /// The width of the space reserved for the fold indicators,
639 /// use alongside 'justify_end' and `gutter_width` to
640 /// right align content with the line numbers
641 pub fn fold_area_width(&self) -> Pixels {
642 self.margin + self.right_padding
643 }
644}
645
646#[derive(Debug)]
647pub struct RemoteSelection {
648 pub replica_id: ReplicaId,
649 pub selection: Selection<Anchor>,
650 pub cursor_shape: CursorShape,
651 pub peer_id: PeerId,
652 pub line_mode: bool,
653 pub participant_index: Option<ParticipantIndex>,
654 pub user_name: Option<SharedString>,
655}
656
657#[derive(Clone, Debug)]
658struct SelectionHistoryEntry {
659 selections: Arc<[Selection<Anchor>]>,
660 select_next_state: Option<SelectNextState>,
661 select_prev_state: Option<SelectNextState>,
662 add_selections_state: Option<AddSelectionsState>,
663}
664
665enum SelectionHistoryMode {
666 Normal,
667 Undoing,
668 Redoing,
669}
670
671#[derive(Clone, PartialEq, Eq, Hash)]
672struct HoveredCursor {
673 replica_id: u16,
674 selection_id: usize,
675}
676
677impl Default for SelectionHistoryMode {
678 fn default() -> Self {
679 Self::Normal
680 }
681}
682
683#[derive(Default)]
684struct SelectionHistory {
685 #[allow(clippy::type_complexity)]
686 selections_by_transaction:
687 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
688 mode: SelectionHistoryMode,
689 undo_stack: VecDeque<SelectionHistoryEntry>,
690 redo_stack: VecDeque<SelectionHistoryEntry>,
691}
692
693impl SelectionHistory {
694 fn insert_transaction(
695 &mut self,
696 transaction_id: TransactionId,
697 selections: Arc<[Selection<Anchor>]>,
698 ) {
699 self.selections_by_transaction
700 .insert(transaction_id, (selections, None));
701 }
702
703 #[allow(clippy::type_complexity)]
704 fn transaction(
705 &self,
706 transaction_id: TransactionId,
707 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
708 self.selections_by_transaction.get(&transaction_id)
709 }
710
711 #[allow(clippy::type_complexity)]
712 fn transaction_mut(
713 &mut self,
714 transaction_id: TransactionId,
715 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
716 self.selections_by_transaction.get_mut(&transaction_id)
717 }
718
719 fn push(&mut self, entry: SelectionHistoryEntry) {
720 if !entry.selections.is_empty() {
721 match self.mode {
722 SelectionHistoryMode::Normal => {
723 self.push_undo(entry);
724 self.redo_stack.clear();
725 }
726 SelectionHistoryMode::Undoing => self.push_redo(entry),
727 SelectionHistoryMode::Redoing => self.push_undo(entry),
728 }
729 }
730 }
731
732 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
733 if self
734 .undo_stack
735 .back()
736 .map_or(true, |e| e.selections != entry.selections)
737 {
738 self.undo_stack.push_back(entry);
739 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
740 self.undo_stack.pop_front();
741 }
742 }
743 }
744
745 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
746 if self
747 .redo_stack
748 .back()
749 .map_or(true, |e| e.selections != entry.selections)
750 {
751 self.redo_stack.push_back(entry);
752 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
753 self.redo_stack.pop_front();
754 }
755 }
756 }
757}
758
759struct RowHighlight {
760 index: usize,
761 range: RangeInclusive<Anchor>,
762 color: Option<Hsla>,
763 should_autoscroll: bool,
764}
765
766#[derive(Clone, Debug)]
767struct AddSelectionsState {
768 above: bool,
769 stack: Vec<usize>,
770}
771
772#[derive(Clone)]
773struct SelectNextState {
774 query: AhoCorasick,
775 wordwise: bool,
776 done: bool,
777}
778
779impl std::fmt::Debug for SelectNextState {
780 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
781 f.debug_struct(std::any::type_name::<Self>())
782 .field("wordwise", &self.wordwise)
783 .field("done", &self.done)
784 .finish()
785 }
786}
787
788#[derive(Debug)]
789struct AutocloseRegion {
790 selection_id: usize,
791 range: Range<Anchor>,
792 pair: BracketPair,
793}
794
795#[derive(Debug)]
796struct SnippetState {
797 ranges: Vec<Vec<Range<Anchor>>>,
798 active_index: usize,
799}
800
801#[doc(hidden)]
802pub struct RenameState {
803 pub range: Range<Anchor>,
804 pub old_name: Arc<str>,
805 pub editor: View<Editor>,
806 block_id: CustomBlockId,
807}
808
809struct InvalidationStack<T>(Vec<T>);
810
811struct RegisteredInlineCompletionProvider {
812 provider: Arc<dyn InlineCompletionProviderHandle>,
813 _subscription: Subscription,
814}
815
816enum ContextMenu {
817 Completions(CompletionsMenu),
818 CodeActions(CodeActionsMenu),
819}
820
821impl ContextMenu {
822 fn select_first(
823 &mut self,
824 project: Option<&Model<Project>>,
825 cx: &mut ViewContext<Editor>,
826 ) -> bool {
827 if self.visible() {
828 match self {
829 ContextMenu::Completions(menu) => menu.select_first(project, cx),
830 ContextMenu::CodeActions(menu) => menu.select_first(cx),
831 }
832 true
833 } else {
834 false
835 }
836 }
837
838 fn select_prev(
839 &mut self,
840 project: Option<&Model<Project>>,
841 cx: &mut ViewContext<Editor>,
842 ) -> bool {
843 if self.visible() {
844 match self {
845 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
846 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
847 }
848 true
849 } else {
850 false
851 }
852 }
853
854 fn select_next(
855 &mut self,
856 project: Option<&Model<Project>>,
857 cx: &mut ViewContext<Editor>,
858 ) -> bool {
859 if self.visible() {
860 match self {
861 ContextMenu::Completions(menu) => menu.select_next(project, cx),
862 ContextMenu::CodeActions(menu) => menu.select_next(cx),
863 }
864 true
865 } else {
866 false
867 }
868 }
869
870 fn select_last(
871 &mut self,
872 project: Option<&Model<Project>>,
873 cx: &mut ViewContext<Editor>,
874 ) -> bool {
875 if self.visible() {
876 match self {
877 ContextMenu::Completions(menu) => menu.select_last(project, cx),
878 ContextMenu::CodeActions(menu) => menu.select_last(cx),
879 }
880 true
881 } else {
882 false
883 }
884 }
885
886 fn visible(&self) -> bool {
887 match self {
888 ContextMenu::Completions(menu) => menu.visible(),
889 ContextMenu::CodeActions(menu) => menu.visible(),
890 }
891 }
892
893 fn render(
894 &self,
895 cursor_position: DisplayPoint,
896 style: &EditorStyle,
897 max_height: Pixels,
898 workspace: Option<WeakView<Workspace>>,
899 cx: &mut ViewContext<Editor>,
900 ) -> (ContextMenuOrigin, AnyElement) {
901 match self {
902 ContextMenu::Completions(menu) => (
903 ContextMenuOrigin::EditorPoint(cursor_position),
904 menu.render(style, max_height, workspace, cx),
905 ),
906 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
907 }
908 }
909}
910
911enum ContextMenuOrigin {
912 EditorPoint(DisplayPoint),
913 GutterIndicator(DisplayRow),
914}
915
916#[derive(Clone)]
917struct CompletionsMenu {
918 id: CompletionId,
919 sort_completions: bool,
920 initial_position: Anchor,
921 buffer: Model<Buffer>,
922 completions: Arc<RwLock<Box<[Completion]>>>,
923 match_candidates: Arc<[StringMatchCandidate]>,
924 matches: Arc<[StringMatch]>,
925 selected_item: usize,
926 scroll_handle: UniformListScrollHandle,
927 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
928}
929
930impl CompletionsMenu {
931 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
932 self.selected_item = 0;
933 self.scroll_handle.scroll_to_item(self.selected_item);
934 self.attempt_resolve_selected_completion_documentation(project, cx);
935 cx.notify();
936 }
937
938 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
939 if self.selected_item > 0 {
940 self.selected_item -= 1;
941 } else {
942 self.selected_item = self.matches.len() - 1;
943 }
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_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
950 if self.selected_item + 1 < self.matches.len() {
951 self.selected_item += 1;
952 } else {
953 self.selected_item = 0;
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_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
961 self.selected_item = self.matches.len() - 1;
962 self.scroll_handle.scroll_to_item(self.selected_item);
963 self.attempt_resolve_selected_completion_documentation(project, cx);
964 cx.notify();
965 }
966
967 fn pre_resolve_completion_documentation(
968 buffer: Model<Buffer>,
969 completions: Arc<RwLock<Box<[Completion]>>>,
970 matches: Arc<[StringMatch]>,
971 editor: &Editor,
972 cx: &mut ViewContext<Editor>,
973 ) -> Task<()> {
974 let settings = EditorSettings::get_global(cx);
975 if !settings.show_completion_documentation {
976 return Task::ready(());
977 }
978
979 let Some(provider) = editor.completion_provider.as_ref() else {
980 return Task::ready(());
981 };
982
983 let resolve_task = provider.resolve_completions(
984 buffer,
985 matches.iter().map(|m| m.candidate_id).collect(),
986 completions.clone(),
987 cx,
988 );
989
990 return cx.spawn(move |this, mut cx| async move {
991 if let Some(true) = resolve_task.await.log_err() {
992 this.update(&mut cx, |_, cx| cx.notify()).ok();
993 }
994 });
995 }
996
997 fn attempt_resolve_selected_completion_documentation(
998 &mut self,
999 project: Option<&Model<Project>>,
1000 cx: &mut ViewContext<Editor>,
1001 ) {
1002 let settings = EditorSettings::get_global(cx);
1003 if !settings.show_completion_documentation {
1004 return;
1005 }
1006
1007 let completion_index = self.matches[self.selected_item].candidate_id;
1008 let Some(project) = project else {
1009 return;
1010 };
1011
1012 let resolve_task = project.update(cx, |project, cx| {
1013 project.resolve_completions(
1014 self.buffer.clone(),
1015 vec![completion_index],
1016 self.completions.clone(),
1017 cx,
1018 )
1019 });
1020
1021 let delay_ms =
1022 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1023 let delay = Duration::from_millis(delay_ms);
1024
1025 self.selected_completion_documentation_resolve_debounce
1026 .lock()
1027 .fire_new(delay, cx, |_, cx| {
1028 cx.spawn(move |this, mut cx| async move {
1029 if let Some(true) = resolve_task.await.log_err() {
1030 this.update(&mut cx, |_, cx| cx.notify()).ok();
1031 }
1032 })
1033 });
1034 }
1035
1036 fn visible(&self) -> bool {
1037 !self.matches.is_empty()
1038 }
1039
1040 fn render(
1041 &self,
1042 style: &EditorStyle,
1043 max_height: Pixels,
1044 workspace: Option<WeakView<Workspace>>,
1045 cx: &mut ViewContext<Editor>,
1046 ) -> AnyElement {
1047 let settings = EditorSettings::get_global(cx);
1048 let show_completion_documentation = settings.show_completion_documentation;
1049
1050 let widest_completion_ix = self
1051 .matches
1052 .iter()
1053 .enumerate()
1054 .max_by_key(|(_, mat)| {
1055 let completions = self.completions.read();
1056 let completion = &completions[mat.candidate_id];
1057 let documentation = &completion.documentation;
1058
1059 let mut len = completion.label.text.chars().count();
1060 if let Some(Documentation::SingleLine(text)) = documentation {
1061 if show_completion_documentation {
1062 len += text.chars().count();
1063 }
1064 }
1065
1066 len
1067 })
1068 .map(|(ix, _)| ix);
1069
1070 let completions = self.completions.clone();
1071 let matches = self.matches.clone();
1072 let selected_item = self.selected_item;
1073 let style = style.clone();
1074
1075 let multiline_docs = if show_completion_documentation {
1076 let mat = &self.matches[selected_item];
1077 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1078 Some(Documentation::MultiLinePlainText(text)) => {
1079 Some(div().child(SharedString::from(text.clone())))
1080 }
1081 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1082 Some(div().child(render_parsed_markdown(
1083 "completions_markdown",
1084 parsed,
1085 &style,
1086 workspace,
1087 cx,
1088 )))
1089 }
1090 _ => None,
1091 };
1092 multiline_docs.map(|div| {
1093 div.id("multiline_docs")
1094 .max_h(max_height)
1095 .flex_1()
1096 .px_1p5()
1097 .py_1()
1098 .min_w(px(260.))
1099 .max_w(px(640.))
1100 .w(px(500.))
1101 .overflow_y_scroll()
1102 .occlude()
1103 })
1104 } else {
1105 None
1106 };
1107
1108 let list = uniform_list(
1109 cx.view().clone(),
1110 "completions",
1111 matches.len(),
1112 move |_editor, range, cx| {
1113 let start_ix = range.start;
1114 let completions_guard = completions.read();
1115
1116 matches[range]
1117 .iter()
1118 .enumerate()
1119 .map(|(ix, mat)| {
1120 let item_ix = start_ix + ix;
1121 let candidate_id = mat.candidate_id;
1122 let completion = &completions_guard[candidate_id];
1123
1124 let documentation = if show_completion_documentation {
1125 &completion.documentation
1126 } else {
1127 &None
1128 };
1129
1130 let highlights = gpui::combine_highlights(
1131 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1132 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1133 |(range, mut highlight)| {
1134 // Ignore font weight for syntax highlighting, as we'll use it
1135 // for fuzzy matches.
1136 highlight.font_weight = None;
1137
1138 if completion.lsp_completion.deprecated.unwrap_or(false) {
1139 highlight.strikethrough = Some(StrikethroughStyle {
1140 thickness: 1.0.into(),
1141 ..Default::default()
1142 });
1143 highlight.color = Some(cx.theme().colors().text_muted);
1144 }
1145
1146 (range, highlight)
1147 },
1148 ),
1149 );
1150 let completion_label = StyledText::new(completion.label.text.clone())
1151 .with_highlights(&style.text, highlights);
1152 let documentation_label =
1153 if let Some(Documentation::SingleLine(text)) = documentation {
1154 if text.trim().is_empty() {
1155 None
1156 } else {
1157 Some(
1158 Label::new(text.clone())
1159 .ml_4()
1160 .size(LabelSize::Small)
1161 .color(Color::Muted),
1162 )
1163 }
1164 } else {
1165 None
1166 };
1167
1168 div().min_w(px(220.)).max_w(px(540.)).child(
1169 ListItem::new(mat.candidate_id)
1170 .inset(true)
1171 .selected(item_ix == selected_item)
1172 .on_click(cx.listener(move |editor, _event, cx| {
1173 cx.stop_propagation();
1174 if let Some(task) = editor.confirm_completion(
1175 &ConfirmCompletion {
1176 item_ix: Some(item_ix),
1177 },
1178 cx,
1179 ) {
1180 task.detach_and_log_err(cx)
1181 }
1182 }))
1183 .child(h_flex().overflow_hidden().child(completion_label))
1184 .end_slot::<Label>(documentation_label),
1185 )
1186 })
1187 .collect()
1188 },
1189 )
1190 .occlude()
1191 .max_h(max_height)
1192 .track_scroll(self.scroll_handle.clone())
1193 .with_width_from_item(widest_completion_ix)
1194 .with_sizing_behavior(ListSizingBehavior::Infer);
1195
1196 Popover::new()
1197 .child(list)
1198 .when_some(multiline_docs, |popover, multiline_docs| {
1199 popover.aside(multiline_docs)
1200 })
1201 .into_any_element()
1202 }
1203
1204 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1205 let mut matches = if let Some(query) = query {
1206 fuzzy::match_strings(
1207 &self.match_candidates,
1208 query,
1209 query.chars().any(|c| c.is_uppercase()),
1210 100,
1211 &Default::default(),
1212 executor,
1213 )
1214 .await
1215 } else {
1216 self.match_candidates
1217 .iter()
1218 .enumerate()
1219 .map(|(candidate_id, candidate)| StringMatch {
1220 candidate_id,
1221 score: Default::default(),
1222 positions: Default::default(),
1223 string: candidate.string.clone(),
1224 })
1225 .collect()
1226 };
1227
1228 // Remove all candidates where the query's start does not match the start of any word in the candidate
1229 if let Some(query) = query {
1230 if let Some(query_start) = query.chars().next() {
1231 matches.retain(|string_match| {
1232 split_words(&string_match.string).any(|word| {
1233 // Check that the first codepoint of the word as lowercase matches the first
1234 // codepoint of the query as lowercase
1235 word.chars()
1236 .flat_map(|codepoint| codepoint.to_lowercase())
1237 .zip(query_start.to_lowercase())
1238 .all(|(word_cp, query_cp)| word_cp == query_cp)
1239 })
1240 });
1241 }
1242 }
1243
1244 let completions = self.completions.read();
1245 if self.sort_completions {
1246 matches.sort_unstable_by_key(|mat| {
1247 // We do want to strike a balance here between what the language server tells us
1248 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1249 // `Creat` and there is a local variable called `CreateComponent`).
1250 // So what we do is: we bucket all matches into two buckets
1251 // - Strong matches
1252 // - Weak matches
1253 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1254 // and the Weak matches are the rest.
1255 //
1256 // For the strong matches, we sort by the language-servers score first and for the weak
1257 // matches, we prefer our fuzzy finder first.
1258 //
1259 // The thinking behind that: it's useless to take the sort_text the language-server gives
1260 // us into account when it's obviously a bad match.
1261
1262 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1263 enum MatchScore<'a> {
1264 Strong {
1265 sort_text: Option<&'a str>,
1266 score: Reverse<OrderedFloat<f64>>,
1267 sort_key: (usize, &'a str),
1268 },
1269 Weak {
1270 score: Reverse<OrderedFloat<f64>>,
1271 sort_text: Option<&'a str>,
1272 sort_key: (usize, &'a str),
1273 },
1274 }
1275
1276 let completion = &completions[mat.candidate_id];
1277 let sort_key = completion.sort_key();
1278 let sort_text = completion.lsp_completion.sort_text.as_deref();
1279 let score = Reverse(OrderedFloat(mat.score));
1280
1281 if mat.score >= 0.2 {
1282 MatchScore::Strong {
1283 sort_text,
1284 score,
1285 sort_key,
1286 }
1287 } else {
1288 MatchScore::Weak {
1289 score,
1290 sort_text,
1291 sort_key,
1292 }
1293 }
1294 });
1295 }
1296
1297 for mat in &mut matches {
1298 let completion = &completions[mat.candidate_id];
1299 mat.string.clone_from(&completion.label.text);
1300 for position in &mut mat.positions {
1301 *position += completion.label.filter_range.start;
1302 }
1303 }
1304 drop(completions);
1305
1306 self.matches = matches.into();
1307 self.selected_item = 0;
1308 }
1309}
1310
1311#[derive(Clone)]
1312struct CodeActionContents {
1313 tasks: Option<Arc<ResolvedTasks>>,
1314 actions: Option<Arc<[CodeAction]>>,
1315}
1316
1317impl CodeActionContents {
1318 fn len(&self) -> usize {
1319 match (&self.tasks, &self.actions) {
1320 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1321 (Some(tasks), None) => tasks.templates.len(),
1322 (None, Some(actions)) => actions.len(),
1323 (None, None) => 0,
1324 }
1325 }
1326
1327 fn is_empty(&self) -> bool {
1328 match (&self.tasks, &self.actions) {
1329 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1330 (Some(tasks), None) => tasks.templates.is_empty(),
1331 (None, Some(actions)) => actions.is_empty(),
1332 (None, None) => true,
1333 }
1334 }
1335
1336 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1337 self.tasks
1338 .iter()
1339 .flat_map(|tasks| {
1340 tasks
1341 .templates
1342 .iter()
1343 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1344 })
1345 .chain(self.actions.iter().flat_map(|actions| {
1346 actions
1347 .iter()
1348 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1349 }))
1350 }
1351 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1352 match (&self.tasks, &self.actions) {
1353 (Some(tasks), Some(actions)) => {
1354 if index < tasks.templates.len() {
1355 tasks
1356 .templates
1357 .get(index)
1358 .cloned()
1359 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1360 } else {
1361 actions
1362 .get(index - tasks.templates.len())
1363 .cloned()
1364 .map(CodeActionsItem::CodeAction)
1365 }
1366 }
1367 (Some(tasks), None) => tasks
1368 .templates
1369 .get(index)
1370 .cloned()
1371 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1372 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1373 (None, None) => None,
1374 }
1375 }
1376}
1377
1378#[allow(clippy::large_enum_variant)]
1379#[derive(Clone)]
1380enum CodeActionsItem {
1381 Task(TaskSourceKind, ResolvedTask),
1382 CodeAction(CodeAction),
1383}
1384
1385impl CodeActionsItem {
1386 fn as_task(&self) -> Option<&ResolvedTask> {
1387 let Self::Task(_, task) = self else {
1388 return None;
1389 };
1390 Some(task)
1391 }
1392 fn as_code_action(&self) -> Option<&CodeAction> {
1393 let Self::CodeAction(action) = self else {
1394 return None;
1395 };
1396 Some(action)
1397 }
1398 fn label(&self) -> String {
1399 match self {
1400 Self::CodeAction(action) => action.lsp_action.title.clone(),
1401 Self::Task(_, task) => task.resolved_label.clone(),
1402 }
1403 }
1404}
1405
1406struct CodeActionsMenu {
1407 actions: CodeActionContents,
1408 buffer: Model<Buffer>,
1409 selected_item: usize,
1410 scroll_handle: UniformListScrollHandle,
1411 deployed_from_indicator: Option<DisplayRow>,
1412}
1413
1414impl CodeActionsMenu {
1415 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1416 self.selected_item = 0;
1417 self.scroll_handle.scroll_to_item(self.selected_item);
1418 cx.notify()
1419 }
1420
1421 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1422 if self.selected_item > 0 {
1423 self.selected_item -= 1;
1424 } else {
1425 self.selected_item = self.actions.len() - 1;
1426 }
1427 self.scroll_handle.scroll_to_item(self.selected_item);
1428 cx.notify();
1429 }
1430
1431 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1432 if self.selected_item + 1 < self.actions.len() {
1433 self.selected_item += 1;
1434 } else {
1435 self.selected_item = 0;
1436 }
1437 self.scroll_handle.scroll_to_item(self.selected_item);
1438 cx.notify();
1439 }
1440
1441 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1442 self.selected_item = self.actions.len() - 1;
1443 self.scroll_handle.scroll_to_item(self.selected_item);
1444 cx.notify()
1445 }
1446
1447 fn visible(&self) -> bool {
1448 !self.actions.is_empty()
1449 }
1450
1451 fn render(
1452 &self,
1453 cursor_position: DisplayPoint,
1454 _style: &EditorStyle,
1455 max_height: Pixels,
1456 cx: &mut ViewContext<Editor>,
1457 ) -> (ContextMenuOrigin, AnyElement) {
1458 let actions = self.actions.clone();
1459 let selected_item = self.selected_item;
1460 let element = uniform_list(
1461 cx.view().clone(),
1462 "code_actions_menu",
1463 self.actions.len(),
1464 move |_this, range, cx| {
1465 actions
1466 .iter()
1467 .skip(range.start)
1468 .take(range.end - range.start)
1469 .enumerate()
1470 .map(|(ix, action)| {
1471 let item_ix = range.start + ix;
1472 let selected = selected_item == item_ix;
1473 let colors = cx.theme().colors();
1474 div()
1475 .px_2()
1476 .text_color(colors.text)
1477 .when(selected, |style| {
1478 style
1479 .bg(colors.element_active)
1480 .text_color(colors.text_accent)
1481 })
1482 .hover(|style| {
1483 style
1484 .bg(colors.element_hover)
1485 .text_color(colors.text_accent)
1486 })
1487 .whitespace_nowrap()
1488 .when_some(action.as_code_action(), |this, action| {
1489 this.on_mouse_down(
1490 MouseButton::Left,
1491 cx.listener(move |editor, _, cx| {
1492 cx.stop_propagation();
1493 if let Some(task) = editor.confirm_code_action(
1494 &ConfirmCodeAction {
1495 item_ix: Some(item_ix),
1496 },
1497 cx,
1498 ) {
1499 task.detach_and_log_err(cx)
1500 }
1501 }),
1502 )
1503 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1504 .child(SharedString::from(action.lsp_action.title.clone()))
1505 })
1506 .when_some(action.as_task(), |this, task| {
1507 this.on_mouse_down(
1508 MouseButton::Left,
1509 cx.listener(move |editor, _, cx| {
1510 cx.stop_propagation();
1511 if let Some(task) = editor.confirm_code_action(
1512 &ConfirmCodeAction {
1513 item_ix: Some(item_ix),
1514 },
1515 cx,
1516 ) {
1517 task.detach_and_log_err(cx)
1518 }
1519 }),
1520 )
1521 .child(SharedString::from(task.resolved_label.clone()))
1522 })
1523 })
1524 .collect()
1525 },
1526 )
1527 .elevation_1(cx)
1528 .px_2()
1529 .py_1()
1530 .max_h(max_height)
1531 .occlude()
1532 .track_scroll(self.scroll_handle.clone())
1533 .with_width_from_item(
1534 self.actions
1535 .iter()
1536 .enumerate()
1537 .max_by_key(|(_, action)| match action {
1538 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1539 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1540 })
1541 .map(|(ix, _)| ix),
1542 )
1543 .with_sizing_behavior(ListSizingBehavior::Infer)
1544 .into_any_element();
1545
1546 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1547 ContextMenuOrigin::GutterIndicator(row)
1548 } else {
1549 ContextMenuOrigin::EditorPoint(cursor_position)
1550 };
1551
1552 (cursor_position, element)
1553 }
1554}
1555
1556#[derive(Debug)]
1557struct ActiveDiagnosticGroup {
1558 primary_range: Range<Anchor>,
1559 primary_message: String,
1560 group_id: usize,
1561 blocks: HashMap<CustomBlockId, Diagnostic>,
1562 is_valid: bool,
1563}
1564
1565#[derive(Serialize, Deserialize, Clone, Debug)]
1566pub struct ClipboardSelection {
1567 pub len: usize,
1568 pub is_entire_line: bool,
1569 pub first_line_indent: u32,
1570}
1571
1572#[derive(Debug)]
1573pub(crate) struct NavigationData {
1574 cursor_anchor: Anchor,
1575 cursor_position: Point,
1576 scroll_anchor: ScrollAnchor,
1577 scroll_top_row: u32,
1578}
1579
1580#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1581enum GotoDefinitionKind {
1582 Symbol,
1583 Declaration,
1584 Type,
1585 Implementation,
1586}
1587
1588#[derive(Debug, Clone)]
1589enum InlayHintRefreshReason {
1590 Toggle(bool),
1591 SettingsChange(InlayHintSettings),
1592 NewLinesShown,
1593 BufferEdited(HashSet<Arc<Language>>),
1594 RefreshRequested,
1595 ExcerptsRemoved(Vec<ExcerptId>),
1596}
1597
1598impl InlayHintRefreshReason {
1599 fn description(&self) -> &'static str {
1600 match self {
1601 Self::Toggle(_) => "toggle",
1602 Self::SettingsChange(_) => "settings change",
1603 Self::NewLinesShown => "new lines shown",
1604 Self::BufferEdited(_) => "buffer edited",
1605 Self::RefreshRequested => "refresh requested",
1606 Self::ExcerptsRemoved(_) => "excerpts removed",
1607 }
1608 }
1609}
1610
1611pub(crate) struct FocusedBlock {
1612 id: BlockId,
1613 focus_handle: WeakFocusHandle,
1614}
1615
1616impl Editor {
1617 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1618 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1619 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1620 Self::new(
1621 EditorMode::SingleLine { auto_width: false },
1622 buffer,
1623 None,
1624 false,
1625 cx,
1626 )
1627 }
1628
1629 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1630 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1631 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1632 Self::new(EditorMode::Full, buffer, None, false, cx)
1633 }
1634
1635 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1636 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1637 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1638 Self::new(
1639 EditorMode::SingleLine { auto_width: true },
1640 buffer,
1641 None,
1642 false,
1643 cx,
1644 )
1645 }
1646
1647 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1648 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1649 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1650 Self::new(
1651 EditorMode::AutoHeight { max_lines },
1652 buffer,
1653 None,
1654 false,
1655 cx,
1656 )
1657 }
1658
1659 pub fn for_buffer(
1660 buffer: Model<Buffer>,
1661 project: Option<Model<Project>>,
1662 cx: &mut ViewContext<Self>,
1663 ) -> Self {
1664 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1665 Self::new(EditorMode::Full, buffer, project, false, cx)
1666 }
1667
1668 pub fn for_multibuffer(
1669 buffer: Model<MultiBuffer>,
1670 project: Option<Model<Project>>,
1671 show_excerpt_controls: bool,
1672 cx: &mut ViewContext<Self>,
1673 ) -> Self {
1674 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1675 }
1676
1677 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1678 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1679 let mut clone = Self::new(
1680 self.mode,
1681 self.buffer.clone(),
1682 self.project.clone(),
1683 show_excerpt_controls,
1684 cx,
1685 );
1686 self.display_map.update(cx, |display_map, cx| {
1687 let snapshot = display_map.snapshot(cx);
1688 clone.display_map.update(cx, |display_map, cx| {
1689 display_map.set_state(&snapshot, cx);
1690 });
1691 });
1692 clone.selections.clone_state(&self.selections);
1693 clone.scroll_manager.clone_state(&self.scroll_manager);
1694 clone.searchable = self.searchable;
1695 clone
1696 }
1697
1698 pub fn new(
1699 mode: EditorMode,
1700 buffer: Model<MultiBuffer>,
1701 project: Option<Model<Project>>,
1702 show_excerpt_controls: bool,
1703 cx: &mut ViewContext<Self>,
1704 ) -> Self {
1705 let style = cx.text_style();
1706 let font_size = style.font_size.to_pixels(cx.rem_size());
1707 let editor = cx.view().downgrade();
1708 let fold_placeholder = FoldPlaceholder {
1709 constrain_width: true,
1710 render: Arc::new(move |fold_id, fold_range, cx| {
1711 let editor = editor.clone();
1712 div()
1713 .id(fold_id)
1714 .bg(cx.theme().colors().ghost_element_background)
1715 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1716 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1717 .rounded_sm()
1718 .size_full()
1719 .cursor_pointer()
1720 .child("⋯")
1721 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1722 .on_click(move |_, cx| {
1723 editor
1724 .update(cx, |editor, cx| {
1725 editor.unfold_ranges(
1726 [fold_range.start..fold_range.end],
1727 true,
1728 false,
1729 cx,
1730 );
1731 cx.stop_propagation();
1732 })
1733 .ok();
1734 })
1735 .into_any()
1736 }),
1737 merge_adjacent: true,
1738 };
1739 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1740 let display_map = cx.new_model(|cx| {
1741 DisplayMap::new(
1742 buffer.clone(),
1743 style.font(),
1744 font_size,
1745 None,
1746 show_excerpt_controls,
1747 file_header_size,
1748 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1749 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1750 fold_placeholder,
1751 cx,
1752 )
1753 });
1754
1755 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1756
1757 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1758
1759 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1760 .then(|| language_settings::SoftWrap::PreferLine);
1761
1762 let mut project_subscriptions = Vec::new();
1763 if mode == EditorMode::Full {
1764 if let Some(project) = project.as_ref() {
1765 if buffer.read(cx).is_singleton() {
1766 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1767 cx.emit(EditorEvent::TitleChanged);
1768 }));
1769 }
1770 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1771 if let project::Event::RefreshInlayHints = event {
1772 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1773 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1774 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1775 let focus_handle = editor.focus_handle(cx);
1776 if focus_handle.is_focused(cx) {
1777 let snapshot = buffer.read(cx).snapshot();
1778 for (range, snippet) in snippet_edits {
1779 let editor_range =
1780 language::range_from_lsp(*range).to_offset(&snapshot);
1781 editor
1782 .insert_snippet(&[editor_range], snippet.clone(), cx)
1783 .ok();
1784 }
1785 }
1786 }
1787 }
1788 }));
1789 let task_inventory = project.read(cx).task_inventory().clone();
1790 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1791 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1792 }));
1793 }
1794 }
1795
1796 let inlay_hint_settings = inlay_hint_settings(
1797 selections.newest_anchor().head(),
1798 &buffer.read(cx).snapshot(cx),
1799 cx,
1800 );
1801 let focus_handle = cx.focus_handle();
1802 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1803 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1804 .detach();
1805 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1806 .detach();
1807 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1808
1809 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1810 Some(false)
1811 } else {
1812 None
1813 };
1814
1815 let mut this = Self {
1816 focus_handle,
1817 show_cursor_when_unfocused: false,
1818 last_focused_descendant: None,
1819 buffer: buffer.clone(),
1820 display_map: display_map.clone(),
1821 selections,
1822 scroll_manager: ScrollManager::new(cx),
1823 columnar_selection_tail: None,
1824 add_selections_state: None,
1825 select_next_state: None,
1826 select_prev_state: None,
1827 selection_history: Default::default(),
1828 autoclose_regions: Default::default(),
1829 snippet_stack: Default::default(),
1830 select_larger_syntax_node_stack: Vec::new(),
1831 ime_transaction: Default::default(),
1832 active_diagnostics: None,
1833 soft_wrap_mode_override,
1834 completion_provider: project.clone().map(|project| Box::new(project) as _),
1835 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1836 project,
1837 blink_manager: blink_manager.clone(),
1838 show_local_selections: true,
1839 mode,
1840 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1841 show_gutter: mode == EditorMode::Full,
1842 show_line_numbers: None,
1843 show_git_diff_gutter: None,
1844 show_code_actions: None,
1845 show_runnables: None,
1846 show_wrap_guides: None,
1847 show_indent_guides,
1848 placeholder_text: None,
1849 highlight_order: 0,
1850 highlighted_rows: HashMap::default(),
1851 background_highlights: Default::default(),
1852 gutter_highlights: TreeMap::default(),
1853 scrollbar_marker_state: ScrollbarMarkerState::default(),
1854 active_indent_guides_state: ActiveIndentGuidesState::default(),
1855 nav_history: None,
1856 context_menu: RwLock::new(None),
1857 mouse_context_menu: None,
1858 completion_tasks: Default::default(),
1859 signature_help_state: SignatureHelpState::default(),
1860 auto_signature_help: None,
1861 find_all_references_task_sources: Vec::new(),
1862 next_completion_id: 0,
1863 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1864 next_inlay_id: 0,
1865 available_code_actions: Default::default(),
1866 code_actions_task: Default::default(),
1867 document_highlights_task: Default::default(),
1868 linked_editing_range_task: Default::default(),
1869 pending_rename: Default::default(),
1870 searchable: true,
1871 cursor_shape: Default::default(),
1872 current_line_highlight: None,
1873 autoindent_mode: Some(AutoindentMode::EachLine),
1874 collapse_matches: false,
1875 workspace: None,
1876 keymap_context_layers: Default::default(),
1877 input_enabled: true,
1878 use_modal_editing: mode == EditorMode::Full,
1879 read_only: false,
1880 use_autoclose: true,
1881 use_auto_surround: true,
1882 auto_replace_emoji_shortcode: false,
1883 leader_peer_id: None,
1884 remote_id: None,
1885 hover_state: Default::default(),
1886 hovered_link_state: Default::default(),
1887 inline_completion_provider: None,
1888 active_inline_completion: None,
1889 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1890 expanded_hunks: ExpandedHunks::default(),
1891 gutter_hovered: false,
1892 pixel_position_of_newest_cursor: None,
1893 last_bounds: None,
1894 expect_bounds_change: None,
1895 gutter_dimensions: GutterDimensions::default(),
1896 style: None,
1897 show_cursor_names: false,
1898 hovered_cursors: Default::default(),
1899 next_editor_action_id: EditorActionId::default(),
1900 editor_actions: Rc::default(),
1901 vim_replace_map: Default::default(),
1902 show_inline_completions: mode == EditorMode::Full,
1903 custom_context_menu: None,
1904 show_git_blame_gutter: false,
1905 show_git_blame_inline: false,
1906 show_selection_menu: None,
1907 show_git_blame_inline_delay_task: None,
1908 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1909 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1910 .session
1911 .restore_unsaved_buffers,
1912 blame: None,
1913 blame_subscription: None,
1914 file_header_size,
1915 tasks: Default::default(),
1916 _subscriptions: vec![
1917 cx.observe(&buffer, Self::on_buffer_changed),
1918 cx.subscribe(&buffer, Self::on_buffer_event),
1919 cx.observe(&display_map, Self::on_display_map_changed),
1920 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1921 cx.observe_global::<SettingsStore>(Self::settings_changed),
1922 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1923 cx.observe_window_activation(|editor, cx| {
1924 let active = cx.is_window_active();
1925 editor.blink_manager.update(cx, |blink_manager, cx| {
1926 if active {
1927 blink_manager.enable(cx);
1928 } else {
1929 blink_manager.disable(cx);
1930 }
1931 });
1932 }),
1933 ],
1934 tasks_update_task: None,
1935 linked_edit_ranges: Default::default(),
1936 previous_search_ranges: None,
1937 breadcrumb_header: None,
1938 focused_block: None,
1939 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1940 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1941 };
1942 this.tasks_update_task = Some(this.refresh_runnables(cx));
1943 this._subscriptions.extend(project_subscriptions);
1944
1945 this.end_selection(cx);
1946 this.scroll_manager.show_scrollbar(cx);
1947
1948 if mode == EditorMode::Full {
1949 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1950 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1951
1952 if this.git_blame_inline_enabled {
1953 this.git_blame_inline_enabled = true;
1954 this.start_git_blame_inline(false, cx);
1955 }
1956 }
1957
1958 this.report_editor_event("open", None, cx);
1959 this
1960 }
1961
1962 pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
1963 self.mouse_context_menu
1964 .as_ref()
1965 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1966 }
1967
1968 fn key_context(&self, cx: &AppContext) -> KeyContext {
1969 let mut key_context = KeyContext::new_with_defaults();
1970 key_context.add("Editor");
1971 let mode = match self.mode {
1972 EditorMode::SingleLine { .. } => "single_line",
1973 EditorMode::AutoHeight { .. } => "auto_height",
1974 EditorMode::Full => "full",
1975 };
1976
1977 if EditorSettings::jupyter_enabled(cx) {
1978 key_context.add("jupyter");
1979 }
1980
1981 key_context.set("mode", mode);
1982 if self.pending_rename.is_some() {
1983 key_context.add("renaming");
1984 }
1985 if self.context_menu_visible() {
1986 match self.context_menu.read().as_ref() {
1987 Some(ContextMenu::Completions(_)) => {
1988 key_context.add("menu");
1989 key_context.add("showing_completions")
1990 }
1991 Some(ContextMenu::CodeActions(_)) => {
1992 key_context.add("menu");
1993 key_context.add("showing_code_actions")
1994 }
1995 None => {}
1996 }
1997 }
1998
1999 for layer in self.keymap_context_layers.values() {
2000 key_context.extend(layer);
2001 }
2002
2003 if let Some(extension) = self
2004 .buffer
2005 .read(cx)
2006 .as_singleton()
2007 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2008 {
2009 key_context.set("extension", extension.to_string());
2010 }
2011
2012 if self.has_active_inline_completion(cx) {
2013 key_context.add("copilot_suggestion");
2014 key_context.add("inline_completion");
2015 }
2016
2017 key_context
2018 }
2019
2020 pub fn new_file(
2021 workspace: &mut Workspace,
2022 _: &workspace::NewFile,
2023 cx: &mut ViewContext<Workspace>,
2024 ) {
2025 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2026 "Failed to create buffer",
2027 cx,
2028 |e, _| match e.error_code() {
2029 ErrorCode::RemoteUpgradeRequired => Some(format!(
2030 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2031 e.error_tag("required").unwrap_or("the latest version")
2032 )),
2033 _ => None,
2034 },
2035 );
2036 }
2037
2038 pub fn new_in_workspace(
2039 workspace: &mut Workspace,
2040 cx: &mut ViewContext<Workspace>,
2041 ) -> Task<Result<View<Editor>>> {
2042 let project = workspace.project().clone();
2043 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2044
2045 cx.spawn(|workspace, mut cx| async move {
2046 let buffer = create.await?;
2047 workspace.update(&mut cx, |workspace, cx| {
2048 let editor =
2049 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2050 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2051 editor
2052 })
2053 })
2054 }
2055
2056 pub fn new_file_in_direction(
2057 workspace: &mut Workspace,
2058 action: &workspace::NewFileInDirection,
2059 cx: &mut ViewContext<Workspace>,
2060 ) {
2061 let project = workspace.project().clone();
2062 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2063 let direction = action.0;
2064
2065 cx.spawn(|workspace, mut cx| async move {
2066 let buffer = create.await?;
2067 workspace.update(&mut cx, move |workspace, cx| {
2068 workspace.split_item(
2069 direction,
2070 Box::new(
2071 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2072 ),
2073 cx,
2074 )
2075 })?;
2076 anyhow::Ok(())
2077 })
2078 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2079 ErrorCode::RemoteUpgradeRequired => Some(format!(
2080 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2081 e.error_tag("required").unwrap_or("the latest version")
2082 )),
2083 _ => None,
2084 });
2085 }
2086
2087 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2088 self.buffer.read(cx).replica_id()
2089 }
2090
2091 pub fn leader_peer_id(&self) -> Option<PeerId> {
2092 self.leader_peer_id
2093 }
2094
2095 pub fn buffer(&self) -> &Model<MultiBuffer> {
2096 &self.buffer
2097 }
2098
2099 pub fn workspace(&self) -> Option<View<Workspace>> {
2100 self.workspace.as_ref()?.0.upgrade()
2101 }
2102
2103 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2104 self.buffer().read(cx).title(cx)
2105 }
2106
2107 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2108 EditorSnapshot {
2109 mode: self.mode,
2110 show_gutter: self.show_gutter,
2111 show_line_numbers: self.show_line_numbers,
2112 show_git_diff_gutter: self.show_git_diff_gutter,
2113 show_code_actions: self.show_code_actions,
2114 show_runnables: self.show_runnables,
2115 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2116 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2117 scroll_anchor: self.scroll_manager.anchor(),
2118 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2119 placeholder_text: self.placeholder_text.clone(),
2120 is_focused: self.focus_handle.is_focused(cx),
2121 current_line_highlight: self
2122 .current_line_highlight
2123 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2124 gutter_hovered: self.gutter_hovered,
2125 }
2126 }
2127
2128 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2129 self.buffer.read(cx).language_at(point, cx)
2130 }
2131
2132 pub fn file_at<T: ToOffset>(
2133 &self,
2134 point: T,
2135 cx: &AppContext,
2136 ) -> Option<Arc<dyn language::File>> {
2137 self.buffer.read(cx).read(cx).file_at(point).cloned()
2138 }
2139
2140 pub fn active_excerpt(
2141 &self,
2142 cx: &AppContext,
2143 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2144 self.buffer
2145 .read(cx)
2146 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2147 }
2148
2149 pub fn mode(&self) -> EditorMode {
2150 self.mode
2151 }
2152
2153 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2154 self.collaboration_hub.as_deref()
2155 }
2156
2157 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2158 self.collaboration_hub = Some(hub);
2159 }
2160
2161 pub fn set_custom_context_menu(
2162 &mut self,
2163 f: impl 'static
2164 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2165 ) {
2166 self.custom_context_menu = Some(Box::new(f))
2167 }
2168
2169 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2170 self.completion_provider = Some(provider);
2171 }
2172
2173 pub fn set_inline_completion_provider<T>(
2174 &mut self,
2175 provider: Option<Model<T>>,
2176 cx: &mut ViewContext<Self>,
2177 ) where
2178 T: InlineCompletionProvider,
2179 {
2180 self.inline_completion_provider =
2181 provider.map(|provider| RegisteredInlineCompletionProvider {
2182 _subscription: cx.observe(&provider, |this, _, cx| {
2183 if this.focus_handle.is_focused(cx) {
2184 this.update_visible_inline_completion(cx);
2185 }
2186 }),
2187 provider: Arc::new(provider),
2188 });
2189 self.refresh_inline_completion(false, cx);
2190 }
2191
2192 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2193 self.placeholder_text.as_deref()
2194 }
2195
2196 pub fn set_placeholder_text(
2197 &mut self,
2198 placeholder_text: impl Into<Arc<str>>,
2199 cx: &mut ViewContext<Self>,
2200 ) {
2201 let placeholder_text = Some(placeholder_text.into());
2202 if self.placeholder_text != placeholder_text {
2203 self.placeholder_text = placeholder_text;
2204 cx.notify();
2205 }
2206 }
2207
2208 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2209 self.cursor_shape = cursor_shape;
2210
2211 // Disrupt blink for immediate user feedback that the cursor shape has changed
2212 self.blink_manager.update(cx, BlinkManager::show_cursor);
2213
2214 cx.notify();
2215 }
2216
2217 pub fn set_current_line_highlight(
2218 &mut self,
2219 current_line_highlight: Option<CurrentLineHighlight>,
2220 ) {
2221 self.current_line_highlight = current_line_highlight;
2222 }
2223
2224 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2225 self.collapse_matches = collapse_matches;
2226 }
2227
2228 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2229 if self.collapse_matches {
2230 return range.start..range.start;
2231 }
2232 range.clone()
2233 }
2234
2235 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2236 if self.display_map.read(cx).clip_at_line_ends != clip {
2237 self.display_map
2238 .update(cx, |map, _| map.clip_at_line_ends = clip);
2239 }
2240 }
2241
2242 pub fn set_keymap_context_layer<Tag: 'static>(
2243 &mut self,
2244 context: KeyContext,
2245 cx: &mut ViewContext<Self>,
2246 ) {
2247 self.keymap_context_layers
2248 .insert(TypeId::of::<Tag>(), context);
2249 cx.notify();
2250 }
2251
2252 pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
2253 self.keymap_context_layers.remove(&TypeId::of::<Tag>());
2254 cx.notify();
2255 }
2256
2257 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2258 self.input_enabled = input_enabled;
2259 }
2260
2261 pub fn set_autoindent(&mut self, autoindent: bool) {
2262 if autoindent {
2263 self.autoindent_mode = Some(AutoindentMode::EachLine);
2264 } else {
2265 self.autoindent_mode = None;
2266 }
2267 }
2268
2269 pub fn read_only(&self, cx: &AppContext) -> bool {
2270 self.read_only || self.buffer.read(cx).read_only()
2271 }
2272
2273 pub fn set_read_only(&mut self, read_only: bool) {
2274 self.read_only = read_only;
2275 }
2276
2277 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2278 self.use_autoclose = autoclose;
2279 }
2280
2281 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2282 self.use_auto_surround = auto_surround;
2283 }
2284
2285 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2286 self.auto_replace_emoji_shortcode = auto_replace;
2287 }
2288
2289 pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
2290 self.show_inline_completions = show_inline_completions;
2291 }
2292
2293 pub fn set_use_modal_editing(&mut self, to: bool) {
2294 self.use_modal_editing = to;
2295 }
2296
2297 pub fn use_modal_editing(&self) -> bool {
2298 self.use_modal_editing
2299 }
2300
2301 fn selections_did_change(
2302 &mut self,
2303 local: bool,
2304 old_cursor_position: &Anchor,
2305 show_completions: bool,
2306 cx: &mut ViewContext<Self>,
2307 ) {
2308 // Copy selections to primary selection buffer
2309 #[cfg(target_os = "linux")]
2310 if local {
2311 let selections = self.selections.all::<usize>(cx);
2312 let buffer_handle = self.buffer.read(cx).read(cx);
2313
2314 let mut text = String::new();
2315 for (index, selection) in selections.iter().enumerate() {
2316 let text_for_selection = buffer_handle
2317 .text_for_range(selection.start..selection.end)
2318 .collect::<String>();
2319
2320 text.push_str(&text_for_selection);
2321 if index != selections.len() - 1 {
2322 text.push('\n');
2323 }
2324 }
2325
2326 if !text.is_empty() {
2327 cx.write_to_primary(ClipboardItem::new_string(text));
2328 }
2329 }
2330
2331 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2332 self.buffer.update(cx, |buffer, cx| {
2333 buffer.set_active_selections(
2334 &self.selections.disjoint_anchors(),
2335 self.selections.line_mode,
2336 self.cursor_shape,
2337 cx,
2338 )
2339 });
2340 }
2341 let display_map = self
2342 .display_map
2343 .update(cx, |display_map, cx| display_map.snapshot(cx));
2344 let buffer = &display_map.buffer_snapshot;
2345 self.add_selections_state = None;
2346 self.select_next_state = None;
2347 self.select_prev_state = None;
2348 self.select_larger_syntax_node_stack.clear();
2349 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2350 self.snippet_stack
2351 .invalidate(&self.selections.disjoint_anchors(), buffer);
2352 self.take_rename(false, cx);
2353
2354 let new_cursor_position = self.selections.newest_anchor().head();
2355
2356 self.push_to_nav_history(
2357 *old_cursor_position,
2358 Some(new_cursor_position.to_point(buffer)),
2359 cx,
2360 );
2361
2362 if local {
2363 let new_cursor_position = self.selections.newest_anchor().head();
2364 let mut context_menu = self.context_menu.write();
2365 let completion_menu = match context_menu.as_ref() {
2366 Some(ContextMenu::Completions(menu)) => Some(menu),
2367
2368 _ => {
2369 *context_menu = None;
2370 None
2371 }
2372 };
2373
2374 if let Some(completion_menu) = completion_menu {
2375 let cursor_position = new_cursor_position.to_offset(buffer);
2376 let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
2377 if kind == Some(CharKind::Word)
2378 && word_range.to_inclusive().contains(&cursor_position)
2379 {
2380 let mut completion_menu = completion_menu.clone();
2381 drop(context_menu);
2382
2383 let query = Self::completion_query(buffer, cursor_position);
2384 cx.spawn(move |this, mut cx| async move {
2385 completion_menu
2386 .filter(query.as_deref(), cx.background_executor().clone())
2387 .await;
2388
2389 this.update(&mut cx, |this, cx| {
2390 let mut context_menu = this.context_menu.write();
2391 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2392 return;
2393 };
2394
2395 if menu.id > completion_menu.id {
2396 return;
2397 }
2398
2399 *context_menu = Some(ContextMenu::Completions(completion_menu));
2400 drop(context_menu);
2401 cx.notify();
2402 })
2403 })
2404 .detach();
2405
2406 if show_completions {
2407 self.show_completions(&ShowCompletions { trigger: None }, cx);
2408 }
2409 } else {
2410 drop(context_menu);
2411 self.hide_context_menu(cx);
2412 }
2413 } else {
2414 drop(context_menu);
2415 }
2416
2417 hide_hover(self, cx);
2418
2419 if old_cursor_position.to_display_point(&display_map).row()
2420 != new_cursor_position.to_display_point(&display_map).row()
2421 {
2422 self.available_code_actions.take();
2423 }
2424 self.refresh_code_actions(cx);
2425 self.refresh_document_highlights(cx);
2426 refresh_matching_bracket_highlights(self, cx);
2427 self.discard_inline_completion(false, cx);
2428 linked_editing_ranges::refresh_linked_ranges(self, cx);
2429 if self.git_blame_inline_enabled {
2430 self.start_inline_blame_timer(cx);
2431 }
2432 }
2433
2434 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2435 cx.emit(EditorEvent::SelectionsChanged { local });
2436
2437 if self.selections.disjoint_anchors().len() == 1 {
2438 cx.emit(SearchEvent::ActiveMatchChanged)
2439 }
2440 cx.notify();
2441 }
2442
2443 pub fn change_selections<R>(
2444 &mut self,
2445 autoscroll: Option<Autoscroll>,
2446 cx: &mut ViewContext<Self>,
2447 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2448 ) -> R {
2449 self.change_selections_inner(autoscroll, true, cx, change)
2450 }
2451
2452 pub fn change_selections_inner<R>(
2453 &mut self,
2454 autoscroll: Option<Autoscroll>,
2455 request_completions: bool,
2456 cx: &mut ViewContext<Self>,
2457 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2458 ) -> R {
2459 let old_cursor_position = self.selections.newest_anchor().head();
2460 self.push_to_selection_history();
2461
2462 let (changed, result) = self.selections.change_with(cx, change);
2463
2464 if changed {
2465 if let Some(autoscroll) = autoscroll {
2466 self.request_autoscroll(autoscroll, cx);
2467 }
2468 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2469
2470 if self.should_open_signature_help_automatically(
2471 &old_cursor_position,
2472 self.signature_help_state.backspace_pressed(),
2473 cx,
2474 ) {
2475 self.show_signature_help(&ShowSignatureHelp, cx);
2476 }
2477 self.signature_help_state.set_backspace_pressed(false);
2478 }
2479
2480 result
2481 }
2482
2483 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2484 where
2485 I: IntoIterator<Item = (Range<S>, T)>,
2486 S: ToOffset,
2487 T: Into<Arc<str>>,
2488 {
2489 if self.read_only(cx) {
2490 return;
2491 }
2492
2493 self.buffer
2494 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2495 }
2496
2497 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2498 where
2499 I: IntoIterator<Item = (Range<S>, T)>,
2500 S: ToOffset,
2501 T: Into<Arc<str>>,
2502 {
2503 if self.read_only(cx) {
2504 return;
2505 }
2506
2507 self.buffer.update(cx, |buffer, cx| {
2508 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2509 });
2510 }
2511
2512 pub fn edit_with_block_indent<I, S, T>(
2513 &mut self,
2514 edits: I,
2515 original_indent_columns: Vec<u32>,
2516 cx: &mut ViewContext<Self>,
2517 ) where
2518 I: IntoIterator<Item = (Range<S>, T)>,
2519 S: ToOffset,
2520 T: Into<Arc<str>>,
2521 {
2522 if self.read_only(cx) {
2523 return;
2524 }
2525
2526 self.buffer.update(cx, |buffer, cx| {
2527 buffer.edit(
2528 edits,
2529 Some(AutoindentMode::Block {
2530 original_indent_columns,
2531 }),
2532 cx,
2533 )
2534 });
2535 }
2536
2537 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2538 self.hide_context_menu(cx);
2539
2540 match phase {
2541 SelectPhase::Begin {
2542 position,
2543 add,
2544 click_count,
2545 } => self.begin_selection(position, add, click_count, cx),
2546 SelectPhase::BeginColumnar {
2547 position,
2548 goal_column,
2549 reset,
2550 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2551 SelectPhase::Extend {
2552 position,
2553 click_count,
2554 } => self.extend_selection(position, click_count, cx),
2555 SelectPhase::Update {
2556 position,
2557 goal_column,
2558 scroll_delta,
2559 } => self.update_selection(position, goal_column, scroll_delta, cx),
2560 SelectPhase::End => self.end_selection(cx),
2561 }
2562 }
2563
2564 fn extend_selection(
2565 &mut self,
2566 position: DisplayPoint,
2567 click_count: usize,
2568 cx: &mut ViewContext<Self>,
2569 ) {
2570 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2571 let tail = self.selections.newest::<usize>(cx).tail();
2572 self.begin_selection(position, false, click_count, cx);
2573
2574 let position = position.to_offset(&display_map, Bias::Left);
2575 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2576
2577 let mut pending_selection = self
2578 .selections
2579 .pending_anchor()
2580 .expect("extend_selection not called with pending selection");
2581 if position >= tail {
2582 pending_selection.start = tail_anchor;
2583 } else {
2584 pending_selection.end = tail_anchor;
2585 pending_selection.reversed = true;
2586 }
2587
2588 let mut pending_mode = self.selections.pending_mode().unwrap();
2589 match &mut pending_mode {
2590 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2591 _ => {}
2592 }
2593
2594 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2595 s.set_pending(pending_selection, pending_mode)
2596 });
2597 }
2598
2599 fn begin_selection(
2600 &mut self,
2601 position: DisplayPoint,
2602 add: bool,
2603 click_count: usize,
2604 cx: &mut ViewContext<Self>,
2605 ) {
2606 if !self.focus_handle.is_focused(cx) {
2607 self.last_focused_descendant = None;
2608 cx.focus(&self.focus_handle);
2609 }
2610
2611 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2612 let buffer = &display_map.buffer_snapshot;
2613 let newest_selection = self.selections.newest_anchor().clone();
2614 let position = display_map.clip_point(position, Bias::Left);
2615
2616 let start;
2617 let end;
2618 let mode;
2619 let auto_scroll;
2620 match click_count {
2621 1 => {
2622 start = buffer.anchor_before(position.to_point(&display_map));
2623 end = start;
2624 mode = SelectMode::Character;
2625 auto_scroll = true;
2626 }
2627 2 => {
2628 let range = movement::surrounding_word(&display_map, position);
2629 start = buffer.anchor_before(range.start.to_point(&display_map));
2630 end = buffer.anchor_before(range.end.to_point(&display_map));
2631 mode = SelectMode::Word(start..end);
2632 auto_scroll = true;
2633 }
2634 3 => {
2635 let position = display_map
2636 .clip_point(position, Bias::Left)
2637 .to_point(&display_map);
2638 let line_start = display_map.prev_line_boundary(position).0;
2639 let next_line_start = buffer.clip_point(
2640 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2641 Bias::Left,
2642 );
2643 start = buffer.anchor_before(line_start);
2644 end = buffer.anchor_before(next_line_start);
2645 mode = SelectMode::Line(start..end);
2646 auto_scroll = true;
2647 }
2648 _ => {
2649 start = buffer.anchor_before(0);
2650 end = buffer.anchor_before(buffer.len());
2651 mode = SelectMode::All;
2652 auto_scroll = false;
2653 }
2654 }
2655
2656 let point_to_delete: Option<usize> = {
2657 let selected_points: Vec<Selection<Point>> =
2658 self.selections.disjoint_in_range(start..end, cx);
2659
2660 if !add || click_count > 1 {
2661 None
2662 } else if selected_points.len() > 0 {
2663 Some(selected_points[0].id)
2664 } else {
2665 let clicked_point_already_selected =
2666 self.selections.disjoint.iter().find(|selection| {
2667 selection.start.to_point(buffer) == start.to_point(buffer)
2668 || selection.end.to_point(buffer) == end.to_point(buffer)
2669 });
2670
2671 if let Some(selection) = clicked_point_already_selected {
2672 Some(selection.id)
2673 } else {
2674 None
2675 }
2676 }
2677 };
2678
2679 let selections_count = self.selections.count();
2680
2681 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2682 if let Some(point_to_delete) = point_to_delete {
2683 s.delete(point_to_delete);
2684
2685 if selections_count == 1 {
2686 s.set_pending_anchor_range(start..end, mode);
2687 }
2688 } else {
2689 if !add {
2690 s.clear_disjoint();
2691 } else if click_count > 1 {
2692 s.delete(newest_selection.id)
2693 }
2694
2695 s.set_pending_anchor_range(start..end, mode);
2696 }
2697 });
2698 }
2699
2700 fn begin_columnar_selection(
2701 &mut self,
2702 position: DisplayPoint,
2703 goal_column: u32,
2704 reset: bool,
2705 cx: &mut ViewContext<Self>,
2706 ) {
2707 if !self.focus_handle.is_focused(cx) {
2708 self.last_focused_descendant = None;
2709 cx.focus(&self.focus_handle);
2710 }
2711
2712 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2713
2714 if reset {
2715 let pointer_position = display_map
2716 .buffer_snapshot
2717 .anchor_before(position.to_point(&display_map));
2718
2719 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2720 s.clear_disjoint();
2721 s.set_pending_anchor_range(
2722 pointer_position..pointer_position,
2723 SelectMode::Character,
2724 );
2725 });
2726 }
2727
2728 let tail = self.selections.newest::<Point>(cx).tail();
2729 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2730
2731 if !reset {
2732 self.select_columns(
2733 tail.to_display_point(&display_map),
2734 position,
2735 goal_column,
2736 &display_map,
2737 cx,
2738 );
2739 }
2740 }
2741
2742 fn update_selection(
2743 &mut self,
2744 position: DisplayPoint,
2745 goal_column: u32,
2746 scroll_delta: gpui::Point<f32>,
2747 cx: &mut ViewContext<Self>,
2748 ) {
2749 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2750
2751 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2752 let tail = tail.to_display_point(&display_map);
2753 self.select_columns(tail, position, goal_column, &display_map, cx);
2754 } else if let Some(mut pending) = self.selections.pending_anchor() {
2755 let buffer = self.buffer.read(cx).snapshot(cx);
2756 let head;
2757 let tail;
2758 let mode = self.selections.pending_mode().unwrap();
2759 match &mode {
2760 SelectMode::Character => {
2761 head = position.to_point(&display_map);
2762 tail = pending.tail().to_point(&buffer);
2763 }
2764 SelectMode::Word(original_range) => {
2765 let original_display_range = original_range.start.to_display_point(&display_map)
2766 ..original_range.end.to_display_point(&display_map);
2767 let original_buffer_range = original_display_range.start.to_point(&display_map)
2768 ..original_display_range.end.to_point(&display_map);
2769 if movement::is_inside_word(&display_map, position)
2770 || original_display_range.contains(&position)
2771 {
2772 let word_range = movement::surrounding_word(&display_map, position);
2773 if word_range.start < original_display_range.start {
2774 head = word_range.start.to_point(&display_map);
2775 } else {
2776 head = word_range.end.to_point(&display_map);
2777 }
2778 } else {
2779 head = position.to_point(&display_map);
2780 }
2781
2782 if head <= original_buffer_range.start {
2783 tail = original_buffer_range.end;
2784 } else {
2785 tail = original_buffer_range.start;
2786 }
2787 }
2788 SelectMode::Line(original_range) => {
2789 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2790
2791 let position = display_map
2792 .clip_point(position, Bias::Left)
2793 .to_point(&display_map);
2794 let line_start = display_map.prev_line_boundary(position).0;
2795 let next_line_start = buffer.clip_point(
2796 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2797 Bias::Left,
2798 );
2799
2800 if line_start < original_range.start {
2801 head = line_start
2802 } else {
2803 head = next_line_start
2804 }
2805
2806 if head <= original_range.start {
2807 tail = original_range.end;
2808 } else {
2809 tail = original_range.start;
2810 }
2811 }
2812 SelectMode::All => {
2813 return;
2814 }
2815 };
2816
2817 if head < tail {
2818 pending.start = buffer.anchor_before(head);
2819 pending.end = buffer.anchor_before(tail);
2820 pending.reversed = true;
2821 } else {
2822 pending.start = buffer.anchor_before(tail);
2823 pending.end = buffer.anchor_before(head);
2824 pending.reversed = false;
2825 }
2826
2827 self.change_selections(None, cx, |s| {
2828 s.set_pending(pending, mode);
2829 });
2830 } else {
2831 log::error!("update_selection dispatched with no pending selection");
2832 return;
2833 }
2834
2835 self.apply_scroll_delta(scroll_delta, cx);
2836 cx.notify();
2837 }
2838
2839 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2840 self.columnar_selection_tail.take();
2841 if self.selections.pending_anchor().is_some() {
2842 let selections = self.selections.all::<usize>(cx);
2843 self.change_selections(None, cx, |s| {
2844 s.select(selections);
2845 s.clear_pending();
2846 });
2847 }
2848 }
2849
2850 fn select_columns(
2851 &mut self,
2852 tail: DisplayPoint,
2853 head: DisplayPoint,
2854 goal_column: u32,
2855 display_map: &DisplaySnapshot,
2856 cx: &mut ViewContext<Self>,
2857 ) {
2858 let start_row = cmp::min(tail.row(), head.row());
2859 let end_row = cmp::max(tail.row(), head.row());
2860 let start_column = cmp::min(tail.column(), goal_column);
2861 let end_column = cmp::max(tail.column(), goal_column);
2862 let reversed = start_column < tail.column();
2863
2864 let selection_ranges = (start_row.0..=end_row.0)
2865 .map(DisplayRow)
2866 .filter_map(|row| {
2867 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2868 let start = display_map
2869 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2870 .to_point(display_map);
2871 let end = display_map
2872 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2873 .to_point(display_map);
2874 if reversed {
2875 Some(end..start)
2876 } else {
2877 Some(start..end)
2878 }
2879 } else {
2880 None
2881 }
2882 })
2883 .collect::<Vec<_>>();
2884
2885 self.change_selections(None, cx, |s| {
2886 s.select_ranges(selection_ranges);
2887 });
2888 cx.notify();
2889 }
2890
2891 pub fn has_pending_nonempty_selection(&self) -> bool {
2892 let pending_nonempty_selection = match self.selections.pending_anchor() {
2893 Some(Selection { start, end, .. }) => start != end,
2894 None => false,
2895 };
2896
2897 pending_nonempty_selection
2898 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2899 }
2900
2901 pub fn has_pending_selection(&self) -> bool {
2902 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2903 }
2904
2905 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2906 if self.clear_clicked_diff_hunks(cx) {
2907 cx.notify();
2908 return;
2909 }
2910 if self.dismiss_menus_and_popups(true, cx) {
2911 return;
2912 }
2913
2914 if self.mode == EditorMode::Full {
2915 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2916 return;
2917 }
2918 }
2919
2920 cx.propagate();
2921 }
2922
2923 pub fn dismiss_menus_and_popups(
2924 &mut self,
2925 should_report_inline_completion_event: bool,
2926 cx: &mut ViewContext<Self>,
2927 ) -> bool {
2928 if self.take_rename(false, cx).is_some() {
2929 return true;
2930 }
2931
2932 if hide_hover(self, cx) {
2933 return true;
2934 }
2935
2936 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2937 return true;
2938 }
2939
2940 if self.hide_context_menu(cx).is_some() {
2941 return true;
2942 }
2943
2944 if self.mouse_context_menu.take().is_some() {
2945 return true;
2946 }
2947
2948 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2949 return true;
2950 }
2951
2952 if self.snippet_stack.pop().is_some() {
2953 return true;
2954 }
2955
2956 if self.mode == EditorMode::Full {
2957 if self.active_diagnostics.is_some() {
2958 self.dismiss_diagnostics(cx);
2959 return true;
2960 }
2961 }
2962
2963 false
2964 }
2965
2966 fn linked_editing_ranges_for(
2967 &self,
2968 selection: Range<text::Anchor>,
2969 cx: &AppContext,
2970 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2971 if self.linked_edit_ranges.is_empty() {
2972 return None;
2973 }
2974 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2975 selection.end.buffer_id.and_then(|end_buffer_id| {
2976 if selection.start.buffer_id != Some(end_buffer_id) {
2977 return None;
2978 }
2979 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2980 let snapshot = buffer.read(cx).snapshot();
2981 self.linked_edit_ranges
2982 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2983 .map(|ranges| (ranges, snapshot, buffer))
2984 })?;
2985 use text::ToOffset as TO;
2986 // find offset from the start of current range to current cursor position
2987 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2988
2989 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2990 let start_difference = start_offset - start_byte_offset;
2991 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2992 let end_difference = end_offset - start_byte_offset;
2993 // Current range has associated linked ranges.
2994 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2995 for range in linked_ranges.iter() {
2996 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2997 let end_offset = start_offset + end_difference;
2998 let start_offset = start_offset + start_difference;
2999 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3000 continue;
3001 }
3002 let start = buffer_snapshot.anchor_after(start_offset);
3003 let end = buffer_snapshot.anchor_after(end_offset);
3004 linked_edits
3005 .entry(buffer.clone())
3006 .or_default()
3007 .push(start..end);
3008 }
3009 Some(linked_edits)
3010 }
3011
3012 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3013 let text: Arc<str> = text.into();
3014
3015 if self.read_only(cx) {
3016 return;
3017 }
3018
3019 let selections = self.selections.all_adjusted(cx);
3020 let mut bracket_inserted = false;
3021 let mut edits = Vec::new();
3022 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3023 let mut new_selections = Vec::with_capacity(selections.len());
3024 let mut new_autoclose_regions = Vec::new();
3025 let snapshot = self.buffer.read(cx).read(cx);
3026
3027 for (selection, autoclose_region) in
3028 self.selections_with_autoclose_regions(selections, &snapshot)
3029 {
3030 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3031 // Determine if the inserted text matches the opening or closing
3032 // bracket of any of this language's bracket pairs.
3033 let mut bracket_pair = None;
3034 let mut is_bracket_pair_start = false;
3035 let mut is_bracket_pair_end = false;
3036 if !text.is_empty() {
3037 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3038 // and they are removing the character that triggered IME popup.
3039 for (pair, enabled) in scope.brackets() {
3040 if !pair.close && !pair.surround {
3041 continue;
3042 }
3043
3044 if enabled && pair.start.ends_with(text.as_ref()) {
3045 bracket_pair = Some(pair.clone());
3046 is_bracket_pair_start = true;
3047 break;
3048 }
3049 if pair.end.as_str() == text.as_ref() {
3050 bracket_pair = Some(pair.clone());
3051 is_bracket_pair_end = true;
3052 break;
3053 }
3054 }
3055 }
3056
3057 if let Some(bracket_pair) = bracket_pair {
3058 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3059 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3060 let auto_surround =
3061 self.use_auto_surround && snapshot_settings.use_auto_surround;
3062 if selection.is_empty() {
3063 if is_bracket_pair_start {
3064 let prefix_len = bracket_pair.start.len() - text.len();
3065
3066 // If the inserted text is a suffix of an opening bracket and the
3067 // selection is preceded by the rest of the opening bracket, then
3068 // insert the closing bracket.
3069 let following_text_allows_autoclose = snapshot
3070 .chars_at(selection.start)
3071 .next()
3072 .map_or(true, |c| scope.should_autoclose_before(c));
3073 let preceding_text_matches_prefix = prefix_len == 0
3074 || (selection.start.column >= (prefix_len as u32)
3075 && snapshot.contains_str_at(
3076 Point::new(
3077 selection.start.row,
3078 selection.start.column - (prefix_len as u32),
3079 ),
3080 &bracket_pair.start[..prefix_len],
3081 ));
3082
3083 if autoclose
3084 && bracket_pair.close
3085 && following_text_allows_autoclose
3086 && preceding_text_matches_prefix
3087 {
3088 let anchor = snapshot.anchor_before(selection.end);
3089 new_selections.push((selection.map(|_| anchor), text.len()));
3090 new_autoclose_regions.push((
3091 anchor,
3092 text.len(),
3093 selection.id,
3094 bracket_pair.clone(),
3095 ));
3096 edits.push((
3097 selection.range(),
3098 format!("{}{}", text, bracket_pair.end).into(),
3099 ));
3100 bracket_inserted = true;
3101 continue;
3102 }
3103 }
3104
3105 if let Some(region) = autoclose_region {
3106 // If the selection is followed by an auto-inserted closing bracket,
3107 // then don't insert that closing bracket again; just move the selection
3108 // past the closing bracket.
3109 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3110 && text.as_ref() == region.pair.end.as_str();
3111 if should_skip {
3112 let anchor = snapshot.anchor_after(selection.end);
3113 new_selections
3114 .push((selection.map(|_| anchor), region.pair.end.len()));
3115 continue;
3116 }
3117 }
3118
3119 let always_treat_brackets_as_autoclosed = snapshot
3120 .settings_at(selection.start, cx)
3121 .always_treat_brackets_as_autoclosed;
3122 if always_treat_brackets_as_autoclosed
3123 && is_bracket_pair_end
3124 && snapshot.contains_str_at(selection.end, text.as_ref())
3125 {
3126 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3127 // and the inserted text is a closing bracket and the selection is followed
3128 // by the closing bracket then move the selection past the closing bracket.
3129 let anchor = snapshot.anchor_after(selection.end);
3130 new_selections.push((selection.map(|_| anchor), text.len()));
3131 continue;
3132 }
3133 }
3134 // If an opening bracket is 1 character long and is typed while
3135 // text is selected, then surround that text with the bracket pair.
3136 else if auto_surround
3137 && bracket_pair.surround
3138 && is_bracket_pair_start
3139 && bracket_pair.start.chars().count() == 1
3140 {
3141 edits.push((selection.start..selection.start, text.clone()));
3142 edits.push((
3143 selection.end..selection.end,
3144 bracket_pair.end.as_str().into(),
3145 ));
3146 bracket_inserted = true;
3147 new_selections.push((
3148 Selection {
3149 id: selection.id,
3150 start: snapshot.anchor_after(selection.start),
3151 end: snapshot.anchor_before(selection.end),
3152 reversed: selection.reversed,
3153 goal: selection.goal,
3154 },
3155 0,
3156 ));
3157 continue;
3158 }
3159 }
3160 }
3161
3162 if self.auto_replace_emoji_shortcode
3163 && selection.is_empty()
3164 && text.as_ref().ends_with(':')
3165 {
3166 if let Some(possible_emoji_short_code) =
3167 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3168 {
3169 if !possible_emoji_short_code.is_empty() {
3170 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3171 let emoji_shortcode_start = Point::new(
3172 selection.start.row,
3173 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3174 );
3175
3176 // Remove shortcode from buffer
3177 edits.push((
3178 emoji_shortcode_start..selection.start,
3179 "".to_string().into(),
3180 ));
3181 new_selections.push((
3182 Selection {
3183 id: selection.id,
3184 start: snapshot.anchor_after(emoji_shortcode_start),
3185 end: snapshot.anchor_before(selection.start),
3186 reversed: selection.reversed,
3187 goal: selection.goal,
3188 },
3189 0,
3190 ));
3191
3192 // Insert emoji
3193 let selection_start_anchor = snapshot.anchor_after(selection.start);
3194 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3195 edits.push((selection.start..selection.end, emoji.to_string().into()));
3196
3197 continue;
3198 }
3199 }
3200 }
3201 }
3202
3203 // If not handling any auto-close operation, then just replace the selected
3204 // text with the given input and move the selection to the end of the
3205 // newly inserted text.
3206 let anchor = snapshot.anchor_after(selection.end);
3207 if !self.linked_edit_ranges.is_empty() {
3208 let start_anchor = snapshot.anchor_before(selection.start);
3209
3210 let is_word_char = text.chars().next().map_or(true, |char| {
3211 let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
3212 let kind = char_kind(&scope, char);
3213
3214 kind == CharKind::Word
3215 });
3216
3217 if is_word_char {
3218 if let Some(ranges) = self
3219 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3220 {
3221 for (buffer, edits) in ranges {
3222 linked_edits
3223 .entry(buffer.clone())
3224 .or_default()
3225 .extend(edits.into_iter().map(|range| (range, text.clone())));
3226 }
3227 }
3228 }
3229 }
3230
3231 new_selections.push((selection.map(|_| anchor), 0));
3232 edits.push((selection.start..selection.end, text.clone()));
3233 }
3234
3235 drop(snapshot);
3236
3237 self.transact(cx, |this, cx| {
3238 this.buffer.update(cx, |buffer, cx| {
3239 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3240 });
3241 for (buffer, edits) in linked_edits {
3242 buffer.update(cx, |buffer, cx| {
3243 let snapshot = buffer.snapshot();
3244 let edits = edits
3245 .into_iter()
3246 .map(|(range, text)| {
3247 use text::ToPoint as TP;
3248 let end_point = TP::to_point(&range.end, &snapshot);
3249 let start_point = TP::to_point(&range.start, &snapshot);
3250 (start_point..end_point, text)
3251 })
3252 .sorted_by_key(|(range, _)| range.start)
3253 .collect::<Vec<_>>();
3254 buffer.edit(edits, None, cx);
3255 })
3256 }
3257 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3258 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3259 let snapshot = this.buffer.read(cx).read(cx);
3260 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3261 .zip(new_selection_deltas)
3262 .map(|(selection, delta)| Selection {
3263 id: selection.id,
3264 start: selection.start + delta,
3265 end: selection.end + delta,
3266 reversed: selection.reversed,
3267 goal: SelectionGoal::None,
3268 })
3269 .collect::<Vec<_>>();
3270
3271 let mut i = 0;
3272 for (position, delta, selection_id, pair) in new_autoclose_regions {
3273 let position = position.to_offset(&snapshot) + delta;
3274 let start = snapshot.anchor_before(position);
3275 let end = snapshot.anchor_after(position);
3276 while let Some(existing_state) = this.autoclose_regions.get(i) {
3277 match existing_state.range.start.cmp(&start, &snapshot) {
3278 Ordering::Less => i += 1,
3279 Ordering::Greater => break,
3280 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3281 Ordering::Less => i += 1,
3282 Ordering::Equal => break,
3283 Ordering::Greater => break,
3284 },
3285 }
3286 }
3287 this.autoclose_regions.insert(
3288 i,
3289 AutocloseRegion {
3290 selection_id,
3291 range: start..end,
3292 pair,
3293 },
3294 );
3295 }
3296
3297 drop(snapshot);
3298 let had_active_inline_completion = this.has_active_inline_completion(cx);
3299 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3300 s.select(new_selections)
3301 });
3302
3303 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3304 if let Some(on_type_format_task) =
3305 this.trigger_on_type_formatting(text.to_string(), cx)
3306 {
3307 on_type_format_task.detach_and_log_err(cx);
3308 }
3309 }
3310
3311 let editor_settings = EditorSettings::get_global(cx);
3312 if bracket_inserted
3313 && (editor_settings.auto_signature_help
3314 || editor_settings.show_signature_help_after_edits)
3315 {
3316 this.show_signature_help(&ShowSignatureHelp, cx);
3317 }
3318
3319 let trigger_in_words = !had_active_inline_completion;
3320 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3321 linked_editing_ranges::refresh_linked_ranges(this, cx);
3322 this.refresh_inline_completion(true, cx);
3323 });
3324 }
3325
3326 fn find_possible_emoji_shortcode_at_position(
3327 snapshot: &MultiBufferSnapshot,
3328 position: Point,
3329 ) -> Option<String> {
3330 let mut chars = Vec::new();
3331 let mut found_colon = false;
3332 for char in snapshot.reversed_chars_at(position).take(100) {
3333 // Found a possible emoji shortcode in the middle of the buffer
3334 if found_colon {
3335 if char.is_whitespace() {
3336 chars.reverse();
3337 return Some(chars.iter().collect());
3338 }
3339 // If the previous character is not a whitespace, we are in the middle of a word
3340 // and we only want to complete the shortcode if the word is made up of other emojis
3341 let mut containing_word = String::new();
3342 for ch in snapshot
3343 .reversed_chars_at(position)
3344 .skip(chars.len() + 1)
3345 .take(100)
3346 {
3347 if ch.is_whitespace() {
3348 break;
3349 }
3350 containing_word.push(ch);
3351 }
3352 let containing_word = containing_word.chars().rev().collect::<String>();
3353 if util::word_consists_of_emojis(containing_word.as_str()) {
3354 chars.reverse();
3355 return Some(chars.iter().collect());
3356 }
3357 }
3358
3359 if char.is_whitespace() || !char.is_ascii() {
3360 return None;
3361 }
3362 if char == ':' {
3363 found_colon = true;
3364 } else {
3365 chars.push(char);
3366 }
3367 }
3368 // Found a possible emoji shortcode at the beginning of the buffer
3369 chars.reverse();
3370 Some(chars.iter().collect())
3371 }
3372
3373 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3374 self.transact(cx, |this, cx| {
3375 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3376 let selections = this.selections.all::<usize>(cx);
3377 let multi_buffer = this.buffer.read(cx);
3378 let buffer = multi_buffer.snapshot(cx);
3379 selections
3380 .iter()
3381 .map(|selection| {
3382 let start_point = selection.start.to_point(&buffer);
3383 let mut indent =
3384 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3385 indent.len = cmp::min(indent.len, start_point.column);
3386 let start = selection.start;
3387 let end = selection.end;
3388 let selection_is_empty = start == end;
3389 let language_scope = buffer.language_scope_at(start);
3390 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3391 &language_scope
3392 {
3393 let leading_whitespace_len = buffer
3394 .reversed_chars_at(start)
3395 .take_while(|c| c.is_whitespace() && *c != '\n')
3396 .map(|c| c.len_utf8())
3397 .sum::<usize>();
3398
3399 let trailing_whitespace_len = buffer
3400 .chars_at(end)
3401 .take_while(|c| c.is_whitespace() && *c != '\n')
3402 .map(|c| c.len_utf8())
3403 .sum::<usize>();
3404
3405 let insert_extra_newline =
3406 language.brackets().any(|(pair, enabled)| {
3407 let pair_start = pair.start.trim_end();
3408 let pair_end = pair.end.trim_start();
3409
3410 enabled
3411 && pair.newline
3412 && buffer.contains_str_at(
3413 end + trailing_whitespace_len,
3414 pair_end,
3415 )
3416 && buffer.contains_str_at(
3417 (start - leading_whitespace_len)
3418 .saturating_sub(pair_start.len()),
3419 pair_start,
3420 )
3421 });
3422
3423 // Comment extension on newline is allowed only for cursor selections
3424 let comment_delimiter = maybe!({
3425 if !selection_is_empty {
3426 return None;
3427 }
3428
3429 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3430 return None;
3431 }
3432
3433 let delimiters = language.line_comment_prefixes();
3434 let max_len_of_delimiter =
3435 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3436 let (snapshot, range) =
3437 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3438
3439 let mut index_of_first_non_whitespace = 0;
3440 let comment_candidate = snapshot
3441 .chars_for_range(range)
3442 .skip_while(|c| {
3443 let should_skip = c.is_whitespace();
3444 if should_skip {
3445 index_of_first_non_whitespace += 1;
3446 }
3447 should_skip
3448 })
3449 .take(max_len_of_delimiter)
3450 .collect::<String>();
3451 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3452 comment_candidate.starts_with(comment_prefix.as_ref())
3453 })?;
3454 let cursor_is_placed_after_comment_marker =
3455 index_of_first_non_whitespace + comment_prefix.len()
3456 <= start_point.column as usize;
3457 if cursor_is_placed_after_comment_marker {
3458 Some(comment_prefix.clone())
3459 } else {
3460 None
3461 }
3462 });
3463 (comment_delimiter, insert_extra_newline)
3464 } else {
3465 (None, false)
3466 };
3467
3468 let capacity_for_delimiter = comment_delimiter
3469 .as_deref()
3470 .map(str::len)
3471 .unwrap_or_default();
3472 let mut new_text =
3473 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3474 new_text.push_str("\n");
3475 new_text.extend(indent.chars());
3476 if let Some(delimiter) = &comment_delimiter {
3477 new_text.push_str(&delimiter);
3478 }
3479 if insert_extra_newline {
3480 new_text = new_text.repeat(2);
3481 }
3482
3483 let anchor = buffer.anchor_after(end);
3484 let new_selection = selection.map(|_| anchor);
3485 (
3486 (start..end, new_text),
3487 (insert_extra_newline, new_selection),
3488 )
3489 })
3490 .unzip()
3491 };
3492
3493 this.edit_with_autoindent(edits, cx);
3494 let buffer = this.buffer.read(cx).snapshot(cx);
3495 let new_selections = selection_fixup_info
3496 .into_iter()
3497 .map(|(extra_newline_inserted, new_selection)| {
3498 let mut cursor = new_selection.end.to_point(&buffer);
3499 if extra_newline_inserted {
3500 cursor.row -= 1;
3501 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3502 }
3503 new_selection.map(|_| cursor)
3504 })
3505 .collect();
3506
3507 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3508 this.refresh_inline_completion(true, cx);
3509 });
3510 }
3511
3512 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3513 let buffer = self.buffer.read(cx);
3514 let snapshot = buffer.snapshot(cx);
3515
3516 let mut edits = Vec::new();
3517 let mut rows = Vec::new();
3518
3519 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3520 let cursor = selection.head();
3521 let row = cursor.row;
3522
3523 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3524
3525 let newline = "\n".to_string();
3526 edits.push((start_of_line..start_of_line, newline));
3527
3528 rows.push(row + rows_inserted as u32);
3529 }
3530
3531 self.transact(cx, |editor, cx| {
3532 editor.edit(edits, cx);
3533
3534 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3535 let mut index = 0;
3536 s.move_cursors_with(|map, _, _| {
3537 let row = rows[index];
3538 index += 1;
3539
3540 let point = Point::new(row, 0);
3541 let boundary = map.next_line_boundary(point).1;
3542 let clipped = map.clip_point(boundary, Bias::Left);
3543
3544 (clipped, SelectionGoal::None)
3545 });
3546 });
3547
3548 let mut indent_edits = Vec::new();
3549 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3550 for row in rows {
3551 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3552 for (row, indent) in indents {
3553 if indent.len == 0 {
3554 continue;
3555 }
3556
3557 let text = match indent.kind {
3558 IndentKind::Space => " ".repeat(indent.len as usize),
3559 IndentKind::Tab => "\t".repeat(indent.len as usize),
3560 };
3561 let point = Point::new(row.0, 0);
3562 indent_edits.push((point..point, text));
3563 }
3564 }
3565 editor.edit(indent_edits, cx);
3566 });
3567 }
3568
3569 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3570 let buffer = self.buffer.read(cx);
3571 let snapshot = buffer.snapshot(cx);
3572
3573 let mut edits = Vec::new();
3574 let mut rows = Vec::new();
3575 let mut rows_inserted = 0;
3576
3577 for selection in self.selections.all_adjusted(cx) {
3578 let cursor = selection.head();
3579 let row = cursor.row;
3580
3581 let point = Point::new(row + 1, 0);
3582 let start_of_line = snapshot.clip_point(point, Bias::Left);
3583
3584 let newline = "\n".to_string();
3585 edits.push((start_of_line..start_of_line, newline));
3586
3587 rows_inserted += 1;
3588 rows.push(row + rows_inserted);
3589 }
3590
3591 self.transact(cx, |editor, cx| {
3592 editor.edit(edits, cx);
3593
3594 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3595 let mut index = 0;
3596 s.move_cursors_with(|map, _, _| {
3597 let row = rows[index];
3598 index += 1;
3599
3600 let point = Point::new(row, 0);
3601 let boundary = map.next_line_boundary(point).1;
3602 let clipped = map.clip_point(boundary, Bias::Left);
3603
3604 (clipped, SelectionGoal::None)
3605 });
3606 });
3607
3608 let mut indent_edits = Vec::new();
3609 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3610 for row in rows {
3611 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3612 for (row, indent) in indents {
3613 if indent.len == 0 {
3614 continue;
3615 }
3616
3617 let text = match indent.kind {
3618 IndentKind::Space => " ".repeat(indent.len as usize),
3619 IndentKind::Tab => "\t".repeat(indent.len as usize),
3620 };
3621 let point = Point::new(row.0, 0);
3622 indent_edits.push((point..point, text));
3623 }
3624 }
3625 editor.edit(indent_edits, cx);
3626 });
3627 }
3628
3629 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3630 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3631 original_indent_columns: Vec::new(),
3632 });
3633 self.insert_with_autoindent_mode(text, autoindent, cx);
3634 }
3635
3636 fn insert_with_autoindent_mode(
3637 &mut self,
3638 text: &str,
3639 autoindent_mode: Option<AutoindentMode>,
3640 cx: &mut ViewContext<Self>,
3641 ) {
3642 if self.read_only(cx) {
3643 return;
3644 }
3645
3646 let text: Arc<str> = text.into();
3647 self.transact(cx, |this, cx| {
3648 let old_selections = this.selections.all_adjusted(cx);
3649 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3650 let anchors = {
3651 let snapshot = buffer.read(cx);
3652 old_selections
3653 .iter()
3654 .map(|s| {
3655 let anchor = snapshot.anchor_after(s.head());
3656 s.map(|_| anchor)
3657 })
3658 .collect::<Vec<_>>()
3659 };
3660 buffer.edit(
3661 old_selections
3662 .iter()
3663 .map(|s| (s.start..s.end, text.clone())),
3664 autoindent_mode,
3665 cx,
3666 );
3667 anchors
3668 });
3669
3670 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3671 s.select_anchors(selection_anchors);
3672 })
3673 });
3674 }
3675
3676 fn trigger_completion_on_input(
3677 &mut self,
3678 text: &str,
3679 trigger_in_words: bool,
3680 cx: &mut ViewContext<Self>,
3681 ) {
3682 if self.is_completion_trigger(text, trigger_in_words, cx) {
3683 self.show_completions(
3684 &ShowCompletions {
3685 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3686 },
3687 cx,
3688 );
3689 } else {
3690 self.hide_context_menu(cx);
3691 }
3692 }
3693
3694 fn is_completion_trigger(
3695 &self,
3696 text: &str,
3697 trigger_in_words: bool,
3698 cx: &mut ViewContext<Self>,
3699 ) -> bool {
3700 let position = self.selections.newest_anchor().head();
3701 let multibuffer = self.buffer.read(cx);
3702 let Some(buffer) = position
3703 .buffer_id
3704 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3705 else {
3706 return false;
3707 };
3708
3709 if let Some(completion_provider) = &self.completion_provider {
3710 completion_provider.is_completion_trigger(
3711 &buffer,
3712 position.text_anchor,
3713 text,
3714 trigger_in_words,
3715 cx,
3716 )
3717 } else {
3718 false
3719 }
3720 }
3721
3722 /// If any empty selections is touching the start of its innermost containing autoclose
3723 /// region, expand it to select the brackets.
3724 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3725 let selections = self.selections.all::<usize>(cx);
3726 let buffer = self.buffer.read(cx).read(cx);
3727 let new_selections = self
3728 .selections_with_autoclose_regions(selections, &buffer)
3729 .map(|(mut selection, region)| {
3730 if !selection.is_empty() {
3731 return selection;
3732 }
3733
3734 if let Some(region) = region {
3735 let mut range = region.range.to_offset(&buffer);
3736 if selection.start == range.start && range.start >= region.pair.start.len() {
3737 range.start -= region.pair.start.len();
3738 if buffer.contains_str_at(range.start, ®ion.pair.start)
3739 && buffer.contains_str_at(range.end, ®ion.pair.end)
3740 {
3741 range.end += region.pair.end.len();
3742 selection.start = range.start;
3743 selection.end = range.end;
3744
3745 return selection;
3746 }
3747 }
3748 }
3749
3750 let always_treat_brackets_as_autoclosed = buffer
3751 .settings_at(selection.start, cx)
3752 .always_treat_brackets_as_autoclosed;
3753
3754 if !always_treat_brackets_as_autoclosed {
3755 return selection;
3756 }
3757
3758 if let Some(scope) = buffer.language_scope_at(selection.start) {
3759 for (pair, enabled) in scope.brackets() {
3760 if !enabled || !pair.close {
3761 continue;
3762 }
3763
3764 if buffer.contains_str_at(selection.start, &pair.end) {
3765 let pair_start_len = pair.start.len();
3766 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3767 {
3768 selection.start -= pair_start_len;
3769 selection.end += pair.end.len();
3770
3771 return selection;
3772 }
3773 }
3774 }
3775 }
3776
3777 selection
3778 })
3779 .collect();
3780
3781 drop(buffer);
3782 self.change_selections(None, cx, |selections| selections.select(new_selections));
3783 }
3784
3785 /// Iterate the given selections, and for each one, find the smallest surrounding
3786 /// autoclose region. This uses the ordering of the selections and the autoclose
3787 /// regions to avoid repeated comparisons.
3788 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3789 &'a self,
3790 selections: impl IntoIterator<Item = Selection<D>>,
3791 buffer: &'a MultiBufferSnapshot,
3792 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3793 let mut i = 0;
3794 let mut regions = self.autoclose_regions.as_slice();
3795 selections.into_iter().map(move |selection| {
3796 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3797
3798 let mut enclosing = None;
3799 while let Some(pair_state) = regions.get(i) {
3800 if pair_state.range.end.to_offset(buffer) < range.start {
3801 regions = ®ions[i + 1..];
3802 i = 0;
3803 } else if pair_state.range.start.to_offset(buffer) > range.end {
3804 break;
3805 } else {
3806 if pair_state.selection_id == selection.id {
3807 enclosing = Some(pair_state);
3808 }
3809 i += 1;
3810 }
3811 }
3812
3813 (selection.clone(), enclosing)
3814 })
3815 }
3816
3817 /// Remove any autoclose regions that no longer contain their selection.
3818 fn invalidate_autoclose_regions(
3819 &mut self,
3820 mut selections: &[Selection<Anchor>],
3821 buffer: &MultiBufferSnapshot,
3822 ) {
3823 self.autoclose_regions.retain(|state| {
3824 let mut i = 0;
3825 while let Some(selection) = selections.get(i) {
3826 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3827 selections = &selections[1..];
3828 continue;
3829 }
3830 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3831 break;
3832 }
3833 if selection.id == state.selection_id {
3834 return true;
3835 } else {
3836 i += 1;
3837 }
3838 }
3839 false
3840 });
3841 }
3842
3843 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3844 let offset = position.to_offset(buffer);
3845 let (word_range, kind) = buffer.surrounding_word(offset);
3846 if offset > word_range.start && kind == Some(CharKind::Word) {
3847 Some(
3848 buffer
3849 .text_for_range(word_range.start..offset)
3850 .collect::<String>(),
3851 )
3852 } else {
3853 None
3854 }
3855 }
3856
3857 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3858 self.refresh_inlay_hints(
3859 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3860 cx,
3861 );
3862 }
3863
3864 pub fn inlay_hints_enabled(&self) -> bool {
3865 self.inlay_hint_cache.enabled
3866 }
3867
3868 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3869 if self.project.is_none() || self.mode != EditorMode::Full {
3870 return;
3871 }
3872
3873 let reason_description = reason.description();
3874 let ignore_debounce = matches!(
3875 reason,
3876 InlayHintRefreshReason::SettingsChange(_)
3877 | InlayHintRefreshReason::Toggle(_)
3878 | InlayHintRefreshReason::ExcerptsRemoved(_)
3879 );
3880 let (invalidate_cache, required_languages) = match reason {
3881 InlayHintRefreshReason::Toggle(enabled) => {
3882 self.inlay_hint_cache.enabled = enabled;
3883 if enabled {
3884 (InvalidationStrategy::RefreshRequested, None)
3885 } else {
3886 self.inlay_hint_cache.clear();
3887 self.splice_inlays(
3888 self.visible_inlay_hints(cx)
3889 .iter()
3890 .map(|inlay| inlay.id)
3891 .collect(),
3892 Vec::new(),
3893 cx,
3894 );
3895 return;
3896 }
3897 }
3898 InlayHintRefreshReason::SettingsChange(new_settings) => {
3899 match self.inlay_hint_cache.update_settings(
3900 &self.buffer,
3901 new_settings,
3902 self.visible_inlay_hints(cx),
3903 cx,
3904 ) {
3905 ControlFlow::Break(Some(InlaySplice {
3906 to_remove,
3907 to_insert,
3908 })) => {
3909 self.splice_inlays(to_remove, to_insert, cx);
3910 return;
3911 }
3912 ControlFlow::Break(None) => return,
3913 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3914 }
3915 }
3916 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3917 if let Some(InlaySplice {
3918 to_remove,
3919 to_insert,
3920 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3921 {
3922 self.splice_inlays(to_remove, to_insert, cx);
3923 }
3924 return;
3925 }
3926 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3927 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3928 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3929 }
3930 InlayHintRefreshReason::RefreshRequested => {
3931 (InvalidationStrategy::RefreshRequested, None)
3932 }
3933 };
3934
3935 if let Some(InlaySplice {
3936 to_remove,
3937 to_insert,
3938 }) = self.inlay_hint_cache.spawn_hint_refresh(
3939 reason_description,
3940 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3941 invalidate_cache,
3942 ignore_debounce,
3943 cx,
3944 ) {
3945 self.splice_inlays(to_remove, to_insert, cx);
3946 }
3947 }
3948
3949 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3950 self.display_map
3951 .read(cx)
3952 .current_inlays()
3953 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3954 .cloned()
3955 .collect()
3956 }
3957
3958 pub fn excerpts_for_inlay_hints_query(
3959 &self,
3960 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3961 cx: &mut ViewContext<Editor>,
3962 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3963 let Some(project) = self.project.as_ref() else {
3964 return HashMap::default();
3965 };
3966 let project = project.read(cx);
3967 let multi_buffer = self.buffer().read(cx);
3968 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3969 let multi_buffer_visible_start = self
3970 .scroll_manager
3971 .anchor()
3972 .anchor
3973 .to_point(&multi_buffer_snapshot);
3974 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3975 multi_buffer_visible_start
3976 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3977 Bias::Left,
3978 );
3979 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3980 multi_buffer
3981 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3982 .into_iter()
3983 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3984 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3985 let buffer = buffer_handle.read(cx);
3986 let buffer_file = project::File::from_dyn(buffer.file())?;
3987 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3988 let worktree_entry = buffer_worktree
3989 .read(cx)
3990 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3991 if worktree_entry.is_ignored {
3992 return None;
3993 }
3994
3995 let language = buffer.language()?;
3996 if let Some(restrict_to_languages) = restrict_to_languages {
3997 if !restrict_to_languages.contains(language) {
3998 return None;
3999 }
4000 }
4001 Some((
4002 excerpt_id,
4003 (
4004 buffer_handle,
4005 buffer.version().clone(),
4006 excerpt_visible_range,
4007 ),
4008 ))
4009 })
4010 .collect()
4011 }
4012
4013 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4014 TextLayoutDetails {
4015 text_system: cx.text_system().clone(),
4016 editor_style: self.style.clone().unwrap(),
4017 rem_size: cx.rem_size(),
4018 scroll_anchor: self.scroll_manager.anchor(),
4019 visible_rows: self.visible_line_count(),
4020 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4021 }
4022 }
4023
4024 fn splice_inlays(
4025 &self,
4026 to_remove: Vec<InlayId>,
4027 to_insert: Vec<Inlay>,
4028 cx: &mut ViewContext<Self>,
4029 ) {
4030 self.display_map.update(cx, |display_map, cx| {
4031 display_map.splice_inlays(to_remove, to_insert, cx);
4032 });
4033 cx.notify();
4034 }
4035
4036 fn trigger_on_type_formatting(
4037 &self,
4038 input: String,
4039 cx: &mut ViewContext<Self>,
4040 ) -> Option<Task<Result<()>>> {
4041 if input.len() != 1 {
4042 return None;
4043 }
4044
4045 let project = self.project.as_ref()?;
4046 let position = self.selections.newest_anchor().head();
4047 let (buffer, buffer_position) = self
4048 .buffer
4049 .read(cx)
4050 .text_anchor_for_position(position, cx)?;
4051
4052 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4053 // hence we do LSP request & edit on host side only — add formats to host's history.
4054 let push_to_lsp_host_history = true;
4055 // If this is not the host, append its history with new edits.
4056 let push_to_client_history = project.read(cx).is_remote();
4057
4058 let on_type_formatting = project.update(cx, |project, cx| {
4059 project.on_type_format(
4060 buffer.clone(),
4061 buffer_position,
4062 input,
4063 push_to_lsp_host_history,
4064 cx,
4065 )
4066 });
4067 Some(cx.spawn(|editor, mut cx| async move {
4068 if let Some(transaction) = on_type_formatting.await? {
4069 if push_to_client_history {
4070 buffer
4071 .update(&mut cx, |buffer, _| {
4072 buffer.push_transaction(transaction, Instant::now());
4073 })
4074 .ok();
4075 }
4076 editor.update(&mut cx, |editor, cx| {
4077 editor.refresh_document_highlights(cx);
4078 })?;
4079 }
4080 Ok(())
4081 }))
4082 }
4083
4084 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4085 if self.pending_rename.is_some() {
4086 return;
4087 }
4088
4089 let Some(provider) = self.completion_provider.as_ref() else {
4090 return;
4091 };
4092
4093 let position = self.selections.newest_anchor().head();
4094 let (buffer, buffer_position) =
4095 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4096 output
4097 } else {
4098 return;
4099 };
4100
4101 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4102 let is_followup_invoke = {
4103 let context_menu_state = self.context_menu.read();
4104 matches!(
4105 context_menu_state.deref(),
4106 Some(ContextMenu::Completions(_))
4107 )
4108 };
4109 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4110 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4111 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
4112 CompletionTriggerKind::TRIGGER_CHARACTER
4113 }
4114
4115 _ => CompletionTriggerKind::INVOKED,
4116 };
4117 let completion_context = CompletionContext {
4118 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4119 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4120 Some(String::from(trigger))
4121 } else {
4122 None
4123 }
4124 }),
4125 trigger_kind,
4126 };
4127 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4128 let sort_completions = provider.sort_completions();
4129
4130 let id = post_inc(&mut self.next_completion_id);
4131 let task = cx.spawn(|this, mut cx| {
4132 async move {
4133 this.update(&mut cx, |this, _| {
4134 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4135 })?;
4136 let completions = completions.await.log_err();
4137 let menu = if let Some(completions) = completions {
4138 let mut menu = CompletionsMenu {
4139 id,
4140 sort_completions,
4141 initial_position: position,
4142 match_candidates: completions
4143 .iter()
4144 .enumerate()
4145 .map(|(id, completion)| {
4146 StringMatchCandidate::new(
4147 id,
4148 completion.label.text[completion.label.filter_range.clone()]
4149 .into(),
4150 )
4151 })
4152 .collect(),
4153 buffer: buffer.clone(),
4154 completions: Arc::new(RwLock::new(completions.into())),
4155 matches: Vec::new().into(),
4156 selected_item: 0,
4157 scroll_handle: UniformListScrollHandle::new(),
4158 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4159 DebouncedDelay::new(),
4160 )),
4161 };
4162 menu.filter(query.as_deref(), cx.background_executor().clone())
4163 .await;
4164
4165 if menu.matches.is_empty() {
4166 None
4167 } else {
4168 this.update(&mut cx, |editor, cx| {
4169 let completions = menu.completions.clone();
4170 let matches = menu.matches.clone();
4171
4172 let delay_ms = EditorSettings::get_global(cx)
4173 .completion_documentation_secondary_query_debounce;
4174 let delay = Duration::from_millis(delay_ms);
4175 editor
4176 .completion_documentation_pre_resolve_debounce
4177 .fire_new(delay, cx, |editor, cx| {
4178 CompletionsMenu::pre_resolve_completion_documentation(
4179 buffer,
4180 completions,
4181 matches,
4182 editor,
4183 cx,
4184 )
4185 });
4186 })
4187 .ok();
4188 Some(menu)
4189 }
4190 } else {
4191 None
4192 };
4193
4194 this.update(&mut cx, |this, cx| {
4195 let mut context_menu = this.context_menu.write();
4196 match context_menu.as_ref() {
4197 None => {}
4198
4199 Some(ContextMenu::Completions(prev_menu)) => {
4200 if prev_menu.id > id {
4201 return;
4202 }
4203 }
4204
4205 _ => return,
4206 }
4207
4208 if this.focus_handle.is_focused(cx) && menu.is_some() {
4209 let menu = menu.unwrap();
4210 *context_menu = Some(ContextMenu::Completions(menu));
4211 drop(context_menu);
4212 this.discard_inline_completion(false, cx);
4213 cx.notify();
4214 } else if this.completion_tasks.len() <= 1 {
4215 // If there are no more completion tasks and the last menu was
4216 // empty, we should hide it. If it was already hidden, we should
4217 // also show the copilot completion when available.
4218 drop(context_menu);
4219 if this.hide_context_menu(cx).is_none() {
4220 this.update_visible_inline_completion(cx);
4221 }
4222 }
4223 })?;
4224
4225 Ok::<_, anyhow::Error>(())
4226 }
4227 .log_err()
4228 });
4229
4230 self.completion_tasks.push((id, task));
4231 }
4232
4233 pub fn confirm_completion(
4234 &mut self,
4235 action: &ConfirmCompletion,
4236 cx: &mut ViewContext<Self>,
4237 ) -> Option<Task<Result<()>>> {
4238 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4239 }
4240
4241 pub fn compose_completion(
4242 &mut self,
4243 action: &ComposeCompletion,
4244 cx: &mut ViewContext<Self>,
4245 ) -> Option<Task<Result<()>>> {
4246 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4247 }
4248
4249 fn do_completion(
4250 &mut self,
4251 item_ix: Option<usize>,
4252 intent: CompletionIntent,
4253 cx: &mut ViewContext<Editor>,
4254 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4255 use language::ToOffset as _;
4256
4257 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4258 menu
4259 } else {
4260 return None;
4261 };
4262
4263 let mat = completions_menu
4264 .matches
4265 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4266 let buffer_handle = completions_menu.buffer;
4267 let completions = completions_menu.completions.read();
4268 let completion = completions.get(mat.candidate_id)?;
4269 cx.stop_propagation();
4270
4271 let snippet;
4272 let text;
4273
4274 if completion.is_snippet() {
4275 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4276 text = snippet.as_ref().unwrap().text.clone();
4277 } else {
4278 snippet = None;
4279 text = completion.new_text.clone();
4280 };
4281 let selections = self.selections.all::<usize>(cx);
4282 let buffer = buffer_handle.read(cx);
4283 let old_range = completion.old_range.to_offset(buffer);
4284 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4285
4286 let newest_selection = self.selections.newest_anchor();
4287 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4288 return None;
4289 }
4290
4291 let lookbehind = newest_selection
4292 .start
4293 .text_anchor
4294 .to_offset(buffer)
4295 .saturating_sub(old_range.start);
4296 let lookahead = old_range
4297 .end
4298 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4299 let mut common_prefix_len = old_text
4300 .bytes()
4301 .zip(text.bytes())
4302 .take_while(|(a, b)| a == b)
4303 .count();
4304
4305 let snapshot = self.buffer.read(cx).snapshot(cx);
4306 let mut range_to_replace: Option<Range<isize>> = None;
4307 let mut ranges = Vec::new();
4308 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4309 for selection in &selections {
4310 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4311 let start = selection.start.saturating_sub(lookbehind);
4312 let end = selection.end + lookahead;
4313 if selection.id == newest_selection.id {
4314 range_to_replace = Some(
4315 ((start + common_prefix_len) as isize - selection.start as isize)
4316 ..(end as isize - selection.start as isize),
4317 );
4318 }
4319 ranges.push(start + common_prefix_len..end);
4320 } else {
4321 common_prefix_len = 0;
4322 ranges.clear();
4323 ranges.extend(selections.iter().map(|s| {
4324 if s.id == newest_selection.id {
4325 range_to_replace = Some(
4326 old_range.start.to_offset_utf16(&snapshot).0 as isize
4327 - selection.start as isize
4328 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4329 - selection.start as isize,
4330 );
4331 old_range.clone()
4332 } else {
4333 s.start..s.end
4334 }
4335 }));
4336 break;
4337 }
4338 if !self.linked_edit_ranges.is_empty() {
4339 let start_anchor = snapshot.anchor_before(selection.head());
4340 let end_anchor = snapshot.anchor_after(selection.tail());
4341 if let Some(ranges) = self
4342 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4343 {
4344 for (buffer, edits) in ranges {
4345 linked_edits.entry(buffer.clone()).or_default().extend(
4346 edits
4347 .into_iter()
4348 .map(|range| (range, text[common_prefix_len..].to_owned())),
4349 );
4350 }
4351 }
4352 }
4353 }
4354 let text = &text[common_prefix_len..];
4355
4356 cx.emit(EditorEvent::InputHandled {
4357 utf16_range_to_replace: range_to_replace,
4358 text: text.into(),
4359 });
4360
4361 self.transact(cx, |this, cx| {
4362 if let Some(mut snippet) = snippet {
4363 snippet.text = text.to_string();
4364 for tabstop in snippet.tabstops.iter_mut().flatten() {
4365 tabstop.start -= common_prefix_len as isize;
4366 tabstop.end -= common_prefix_len as isize;
4367 }
4368
4369 this.insert_snippet(&ranges, snippet, cx).log_err();
4370 } else {
4371 this.buffer.update(cx, |buffer, cx| {
4372 buffer.edit(
4373 ranges.iter().map(|range| (range.clone(), text)),
4374 this.autoindent_mode.clone(),
4375 cx,
4376 );
4377 });
4378 }
4379 for (buffer, edits) in linked_edits {
4380 buffer.update(cx, |buffer, cx| {
4381 let snapshot = buffer.snapshot();
4382 let edits = edits
4383 .into_iter()
4384 .map(|(range, text)| {
4385 use text::ToPoint as TP;
4386 let end_point = TP::to_point(&range.end, &snapshot);
4387 let start_point = TP::to_point(&range.start, &snapshot);
4388 (start_point..end_point, text)
4389 })
4390 .sorted_by_key(|(range, _)| range.start)
4391 .collect::<Vec<_>>();
4392 buffer.edit(edits, None, cx);
4393 })
4394 }
4395
4396 this.refresh_inline_completion(true, cx);
4397 });
4398
4399 let show_new_completions_on_confirm = completion
4400 .confirm
4401 .as_ref()
4402 .map_or(false, |confirm| confirm(intent, cx));
4403 if show_new_completions_on_confirm {
4404 self.show_completions(&ShowCompletions { trigger: None }, cx);
4405 }
4406
4407 let provider = self.completion_provider.as_ref()?;
4408 let apply_edits = provider.apply_additional_edits_for_completion(
4409 buffer_handle,
4410 completion.clone(),
4411 true,
4412 cx,
4413 );
4414
4415 let editor_settings = EditorSettings::get_global(cx);
4416 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4417 // After the code completion is finished, users often want to know what signatures are needed.
4418 // so we should automatically call signature_help
4419 self.show_signature_help(&ShowSignatureHelp, cx);
4420 }
4421
4422 Some(cx.foreground_executor().spawn(async move {
4423 apply_edits.await?;
4424 Ok(())
4425 }))
4426 }
4427
4428 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4429 let mut context_menu = self.context_menu.write();
4430 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4431 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4432 // Toggle if we're selecting the same one
4433 *context_menu = None;
4434 cx.notify();
4435 return;
4436 } else {
4437 // Otherwise, clear it and start a new one
4438 *context_menu = None;
4439 cx.notify();
4440 }
4441 }
4442 drop(context_menu);
4443 let snapshot = self.snapshot(cx);
4444 let deployed_from_indicator = action.deployed_from_indicator;
4445 let mut task = self.code_actions_task.take();
4446 let action = action.clone();
4447 cx.spawn(|editor, mut cx| async move {
4448 while let Some(prev_task) = task {
4449 prev_task.await;
4450 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4451 }
4452
4453 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4454 if editor.focus_handle.is_focused(cx) {
4455 let multibuffer_point = action
4456 .deployed_from_indicator
4457 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4458 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4459 let (buffer, buffer_row) = snapshot
4460 .buffer_snapshot
4461 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4462 .and_then(|(buffer_snapshot, range)| {
4463 editor
4464 .buffer
4465 .read(cx)
4466 .buffer(buffer_snapshot.remote_id())
4467 .map(|buffer| (buffer, range.start.row))
4468 })?;
4469 let (_, code_actions) = editor
4470 .available_code_actions
4471 .clone()
4472 .and_then(|(location, code_actions)| {
4473 let snapshot = location.buffer.read(cx).snapshot();
4474 let point_range = location.range.to_point(&snapshot);
4475 let point_range = point_range.start.row..=point_range.end.row;
4476 if point_range.contains(&buffer_row) {
4477 Some((location, code_actions))
4478 } else {
4479 None
4480 }
4481 })
4482 .unzip();
4483 let buffer_id = buffer.read(cx).remote_id();
4484 let tasks = editor
4485 .tasks
4486 .get(&(buffer_id, buffer_row))
4487 .map(|t| Arc::new(t.to_owned()));
4488 if tasks.is_none() && code_actions.is_none() {
4489 return None;
4490 }
4491
4492 editor.completion_tasks.clear();
4493 editor.discard_inline_completion(false, cx);
4494 let task_context =
4495 tasks
4496 .as_ref()
4497 .zip(editor.project.clone())
4498 .map(|(tasks, project)| {
4499 let position = Point::new(buffer_row, tasks.column);
4500 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4501 let location = Location {
4502 buffer: buffer.clone(),
4503 range: range_start..range_start,
4504 };
4505 // Fill in the environmental variables from the tree-sitter captures
4506 let mut captured_task_variables = TaskVariables::default();
4507 for (capture_name, value) in tasks.extra_variables.clone() {
4508 captured_task_variables.insert(
4509 task::VariableName::Custom(capture_name.into()),
4510 value.clone(),
4511 );
4512 }
4513 project.update(cx, |project, cx| {
4514 project.task_context_for_location(
4515 captured_task_variables,
4516 location,
4517 cx,
4518 )
4519 })
4520 });
4521
4522 Some(cx.spawn(|editor, mut cx| async move {
4523 let task_context = match task_context {
4524 Some(task_context) => task_context.await,
4525 None => None,
4526 };
4527 let resolved_tasks =
4528 tasks.zip(task_context).map(|(tasks, task_context)| {
4529 Arc::new(ResolvedTasks {
4530 templates: tasks
4531 .templates
4532 .iter()
4533 .filter_map(|(kind, template)| {
4534 template
4535 .resolve_task(&kind.to_id_base(), &task_context)
4536 .map(|task| (kind.clone(), task))
4537 })
4538 .collect(),
4539 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4540 multibuffer_point.row,
4541 tasks.column,
4542 )),
4543 })
4544 });
4545 let spawn_straight_away = resolved_tasks
4546 .as_ref()
4547 .map_or(false, |tasks| tasks.templates.len() == 1)
4548 && code_actions
4549 .as_ref()
4550 .map_or(true, |actions| actions.is_empty());
4551 if let Some(task) = editor
4552 .update(&mut cx, |editor, cx| {
4553 *editor.context_menu.write() =
4554 Some(ContextMenu::CodeActions(CodeActionsMenu {
4555 buffer,
4556 actions: CodeActionContents {
4557 tasks: resolved_tasks,
4558 actions: code_actions,
4559 },
4560 selected_item: Default::default(),
4561 scroll_handle: UniformListScrollHandle::default(),
4562 deployed_from_indicator,
4563 }));
4564 if spawn_straight_away {
4565 if let Some(task) = editor.confirm_code_action(
4566 &ConfirmCodeAction { item_ix: Some(0) },
4567 cx,
4568 ) {
4569 cx.notify();
4570 return task;
4571 }
4572 }
4573 cx.notify();
4574 Task::ready(Ok(()))
4575 })
4576 .ok()
4577 {
4578 task.await
4579 } else {
4580 Ok(())
4581 }
4582 }))
4583 } else {
4584 Some(Task::ready(Ok(())))
4585 }
4586 })?;
4587 if let Some(task) = spawned_test_task {
4588 task.await?;
4589 }
4590
4591 Ok::<_, anyhow::Error>(())
4592 })
4593 .detach_and_log_err(cx);
4594 }
4595
4596 pub fn confirm_code_action(
4597 &mut self,
4598 action: &ConfirmCodeAction,
4599 cx: &mut ViewContext<Self>,
4600 ) -> Option<Task<Result<()>>> {
4601 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4602 menu
4603 } else {
4604 return None;
4605 };
4606 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4607 let action = actions_menu.actions.get(action_ix)?;
4608 let title = action.label();
4609 let buffer = actions_menu.buffer;
4610 let workspace = self.workspace()?;
4611
4612 match action {
4613 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4614 workspace.update(cx, |workspace, cx| {
4615 workspace::tasks::schedule_resolved_task(
4616 workspace,
4617 task_source_kind,
4618 resolved_task,
4619 false,
4620 cx,
4621 );
4622
4623 Some(Task::ready(Ok(())))
4624 })
4625 }
4626 CodeActionsItem::CodeAction(action) => {
4627 let apply_code_actions = workspace
4628 .read(cx)
4629 .project()
4630 .clone()
4631 .update(cx, |project, cx| {
4632 project.apply_code_action(buffer, action, true, cx)
4633 });
4634 let workspace = workspace.downgrade();
4635 Some(cx.spawn(|editor, cx| async move {
4636 let project_transaction = apply_code_actions.await?;
4637 Self::open_project_transaction(
4638 &editor,
4639 workspace,
4640 project_transaction,
4641 title,
4642 cx,
4643 )
4644 .await
4645 }))
4646 }
4647 }
4648 }
4649
4650 pub async fn open_project_transaction(
4651 this: &WeakView<Editor>,
4652 workspace: WeakView<Workspace>,
4653 transaction: ProjectTransaction,
4654 title: String,
4655 mut cx: AsyncWindowContext,
4656 ) -> Result<()> {
4657 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4658
4659 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4660 cx.update(|cx| {
4661 entries.sort_unstable_by_key(|(buffer, _)| {
4662 buffer.read(cx).file().map(|f| f.path().clone())
4663 });
4664 })?;
4665
4666 // If the project transaction's edits are all contained within this editor, then
4667 // avoid opening a new editor to display them.
4668
4669 if let Some((buffer, transaction)) = entries.first() {
4670 if entries.len() == 1 {
4671 let excerpt = this.update(&mut cx, |editor, cx| {
4672 editor
4673 .buffer()
4674 .read(cx)
4675 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4676 })?;
4677 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4678 if excerpted_buffer == *buffer {
4679 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4680 let excerpt_range = excerpt_range.to_offset(buffer);
4681 buffer
4682 .edited_ranges_for_transaction::<usize>(transaction)
4683 .all(|range| {
4684 excerpt_range.start <= range.start
4685 && excerpt_range.end >= range.end
4686 })
4687 })?;
4688
4689 if all_edits_within_excerpt {
4690 return Ok(());
4691 }
4692 }
4693 }
4694 }
4695 } else {
4696 return Ok(());
4697 }
4698
4699 let mut ranges_to_highlight = Vec::new();
4700 let excerpt_buffer = cx.new_model(|cx| {
4701 let mut multibuffer =
4702 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4703 for (buffer_handle, transaction) in &entries {
4704 let buffer = buffer_handle.read(cx);
4705 ranges_to_highlight.extend(
4706 multibuffer.push_excerpts_with_context_lines(
4707 buffer_handle.clone(),
4708 buffer
4709 .edited_ranges_for_transaction::<usize>(transaction)
4710 .collect(),
4711 DEFAULT_MULTIBUFFER_CONTEXT,
4712 cx,
4713 ),
4714 );
4715 }
4716 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4717 multibuffer
4718 })?;
4719
4720 workspace.update(&mut cx, |workspace, cx| {
4721 let project = workspace.project().clone();
4722 let editor =
4723 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4724 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4725 editor.update(cx, |editor, cx| {
4726 editor.highlight_background::<Self>(
4727 &ranges_to_highlight,
4728 |theme| theme.editor_highlighted_line_background,
4729 cx,
4730 );
4731 });
4732 })?;
4733
4734 Ok(())
4735 }
4736
4737 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4738 let project = self.project.clone()?;
4739 let buffer = self.buffer.read(cx);
4740 let newest_selection = self.selections.newest_anchor().clone();
4741 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4742 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4743 if start_buffer != end_buffer {
4744 return None;
4745 }
4746
4747 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4748 cx.background_executor()
4749 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4750 .await;
4751
4752 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4753 project.code_actions(&start_buffer, start..end, cx)
4754 }) {
4755 code_actions.await
4756 } else {
4757 Vec::new()
4758 };
4759
4760 this.update(&mut cx, |this, cx| {
4761 this.available_code_actions = if actions.is_empty() {
4762 None
4763 } else {
4764 Some((
4765 Location {
4766 buffer: start_buffer,
4767 range: start..end,
4768 },
4769 actions.into(),
4770 ))
4771 };
4772 cx.notify();
4773 })
4774 .log_err();
4775 }));
4776 None
4777 }
4778
4779 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4780 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4781 self.show_git_blame_inline = false;
4782
4783 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4784 cx.background_executor().timer(delay).await;
4785
4786 this.update(&mut cx, |this, cx| {
4787 this.show_git_blame_inline = true;
4788 cx.notify();
4789 })
4790 .log_err();
4791 }));
4792 }
4793 }
4794
4795 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4796 if self.pending_rename.is_some() {
4797 return None;
4798 }
4799
4800 let project = self.project.clone()?;
4801 let buffer = self.buffer.read(cx);
4802 let newest_selection = self.selections.newest_anchor().clone();
4803 let cursor_position = newest_selection.head();
4804 let (cursor_buffer, cursor_buffer_position) =
4805 buffer.text_anchor_for_position(cursor_position, cx)?;
4806 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4807 if cursor_buffer != tail_buffer {
4808 return None;
4809 }
4810
4811 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4812 cx.background_executor()
4813 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4814 .await;
4815
4816 let highlights = if let Some(highlights) = project
4817 .update(&mut cx, |project, cx| {
4818 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4819 })
4820 .log_err()
4821 {
4822 highlights.await.log_err()
4823 } else {
4824 None
4825 };
4826
4827 if let Some(highlights) = highlights {
4828 this.update(&mut cx, |this, cx| {
4829 if this.pending_rename.is_some() {
4830 return;
4831 }
4832
4833 let buffer_id = cursor_position.buffer_id;
4834 let buffer = this.buffer.read(cx);
4835 if !buffer
4836 .text_anchor_for_position(cursor_position, cx)
4837 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4838 {
4839 return;
4840 }
4841
4842 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4843 let mut write_ranges = Vec::new();
4844 let mut read_ranges = Vec::new();
4845 for highlight in highlights {
4846 for (excerpt_id, excerpt_range) in
4847 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4848 {
4849 let start = highlight
4850 .range
4851 .start
4852 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4853 let end = highlight
4854 .range
4855 .end
4856 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4857 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4858 continue;
4859 }
4860
4861 let range = Anchor {
4862 buffer_id,
4863 excerpt_id,
4864 text_anchor: start,
4865 }..Anchor {
4866 buffer_id,
4867 excerpt_id,
4868 text_anchor: end,
4869 };
4870 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4871 write_ranges.push(range);
4872 } else {
4873 read_ranges.push(range);
4874 }
4875 }
4876 }
4877
4878 this.highlight_background::<DocumentHighlightRead>(
4879 &read_ranges,
4880 |theme| theme.editor_document_highlight_read_background,
4881 cx,
4882 );
4883 this.highlight_background::<DocumentHighlightWrite>(
4884 &write_ranges,
4885 |theme| theme.editor_document_highlight_write_background,
4886 cx,
4887 );
4888 cx.notify();
4889 })
4890 .log_err();
4891 }
4892 }));
4893 None
4894 }
4895
4896 fn refresh_inline_completion(
4897 &mut self,
4898 debounce: bool,
4899 cx: &mut ViewContext<Self>,
4900 ) -> Option<()> {
4901 let provider = self.inline_completion_provider()?;
4902 let cursor = self.selections.newest_anchor().head();
4903 let (buffer, cursor_buffer_position) =
4904 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4905 if !self.show_inline_completions
4906 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4907 {
4908 self.discard_inline_completion(false, cx);
4909 return None;
4910 }
4911
4912 self.update_visible_inline_completion(cx);
4913 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4914 Some(())
4915 }
4916
4917 fn cycle_inline_completion(
4918 &mut self,
4919 direction: Direction,
4920 cx: &mut ViewContext<Self>,
4921 ) -> Option<()> {
4922 let provider = self.inline_completion_provider()?;
4923 let cursor = self.selections.newest_anchor().head();
4924 let (buffer, cursor_buffer_position) =
4925 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4926 if !self.show_inline_completions
4927 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4928 {
4929 return None;
4930 }
4931
4932 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4933 self.update_visible_inline_completion(cx);
4934
4935 Some(())
4936 }
4937
4938 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4939 if !self.has_active_inline_completion(cx) {
4940 self.refresh_inline_completion(false, cx);
4941 return;
4942 }
4943
4944 self.update_visible_inline_completion(cx);
4945 }
4946
4947 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4948 self.show_cursor_names(cx);
4949 }
4950
4951 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4952 self.show_cursor_names = true;
4953 cx.notify();
4954 cx.spawn(|this, mut cx| async move {
4955 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4956 this.update(&mut cx, |this, cx| {
4957 this.show_cursor_names = false;
4958 cx.notify()
4959 })
4960 .ok()
4961 })
4962 .detach();
4963 }
4964
4965 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4966 if self.has_active_inline_completion(cx) {
4967 self.cycle_inline_completion(Direction::Next, cx);
4968 } else {
4969 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4970 if is_copilot_disabled {
4971 cx.propagate();
4972 }
4973 }
4974 }
4975
4976 pub fn previous_inline_completion(
4977 &mut self,
4978 _: &PreviousInlineCompletion,
4979 cx: &mut ViewContext<Self>,
4980 ) {
4981 if self.has_active_inline_completion(cx) {
4982 self.cycle_inline_completion(Direction::Prev, cx);
4983 } else {
4984 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4985 if is_copilot_disabled {
4986 cx.propagate();
4987 }
4988 }
4989 }
4990
4991 pub fn accept_inline_completion(
4992 &mut self,
4993 _: &AcceptInlineCompletion,
4994 cx: &mut ViewContext<Self>,
4995 ) {
4996 let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
4997 return;
4998 };
4999 if let Some(provider) = self.inline_completion_provider() {
5000 provider.accept(cx);
5001 }
5002
5003 cx.emit(EditorEvent::InputHandled {
5004 utf16_range_to_replace: None,
5005 text: completion.text.to_string().into(),
5006 });
5007
5008 if let Some(range) = delete_range {
5009 self.change_selections(None, cx, |s| s.select_ranges([range]))
5010 }
5011 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5012 self.refresh_inline_completion(true, cx);
5013 cx.notify();
5014 }
5015
5016 pub fn accept_partial_inline_completion(
5017 &mut self,
5018 _: &AcceptPartialInlineCompletion,
5019 cx: &mut ViewContext<Self>,
5020 ) {
5021 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5022 if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
5023 let mut partial_completion = completion
5024 .text
5025 .chars()
5026 .by_ref()
5027 .take_while(|c| c.is_alphabetic())
5028 .collect::<String>();
5029 if partial_completion.is_empty() {
5030 partial_completion = completion
5031 .text
5032 .chars()
5033 .by_ref()
5034 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5035 .collect::<String>();
5036 }
5037
5038 cx.emit(EditorEvent::InputHandled {
5039 utf16_range_to_replace: None,
5040 text: partial_completion.clone().into(),
5041 });
5042
5043 if let Some(range) = delete_range {
5044 self.change_selections(None, cx, |s| s.select_ranges([range]))
5045 }
5046 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5047
5048 self.refresh_inline_completion(true, cx);
5049 cx.notify();
5050 }
5051 }
5052 }
5053
5054 fn discard_inline_completion(
5055 &mut self,
5056 should_report_inline_completion_event: bool,
5057 cx: &mut ViewContext<Self>,
5058 ) -> bool {
5059 if let Some(provider) = self.inline_completion_provider() {
5060 provider.discard(should_report_inline_completion_event, cx);
5061 }
5062
5063 self.take_active_inline_completion(cx).is_some()
5064 }
5065
5066 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5067 if let Some(completion) = self.active_inline_completion.as_ref() {
5068 let buffer = self.buffer.read(cx).read(cx);
5069 completion.0.position.is_valid(&buffer)
5070 } else {
5071 false
5072 }
5073 }
5074
5075 fn take_active_inline_completion(
5076 &mut self,
5077 cx: &mut ViewContext<Self>,
5078 ) -> Option<(Inlay, Option<Range<Anchor>>)> {
5079 let completion = self.active_inline_completion.take()?;
5080 self.display_map.update(cx, |map, cx| {
5081 map.splice_inlays(vec![completion.0.id], Default::default(), cx);
5082 });
5083 let buffer = self.buffer.read(cx).read(cx);
5084
5085 if completion.0.position.is_valid(&buffer) {
5086 Some(completion)
5087 } else {
5088 None
5089 }
5090 }
5091
5092 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5093 let selection = self.selections.newest_anchor();
5094 let cursor = selection.head();
5095
5096 let excerpt_id = cursor.excerpt_id;
5097
5098 if self.context_menu.read().is_none()
5099 && self.completion_tasks.is_empty()
5100 && selection.start == selection.end
5101 {
5102 if let Some(provider) = self.inline_completion_provider() {
5103 if let Some((buffer, cursor_buffer_position)) =
5104 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5105 {
5106 if let Some((text, text_anchor_range)) =
5107 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5108 {
5109 let text = Rope::from(text);
5110 let mut to_remove = Vec::new();
5111 if let Some(completion) = self.active_inline_completion.take() {
5112 to_remove.push(completion.0.id);
5113 }
5114
5115 let completion_inlay =
5116 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
5117
5118 let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
5119 let snapshot = self.buffer.read(cx).snapshot(cx);
5120 Some(
5121 snapshot.anchor_in_excerpt(excerpt_id, range.start)?
5122 ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
5123 )
5124 });
5125 self.active_inline_completion =
5126 Some((completion_inlay.clone(), multibuffer_anchor_range));
5127
5128 self.display_map.update(cx, move |map, cx| {
5129 map.splice_inlays(to_remove, vec![completion_inlay], cx)
5130 });
5131 cx.notify();
5132 return;
5133 }
5134 }
5135 }
5136 }
5137
5138 self.discard_inline_completion(false, cx);
5139 }
5140
5141 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5142 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5143 }
5144
5145 fn render_code_actions_indicator(
5146 &self,
5147 _style: &EditorStyle,
5148 row: DisplayRow,
5149 is_active: bool,
5150 cx: &mut ViewContext<Self>,
5151 ) -> Option<IconButton> {
5152 if self.available_code_actions.is_some() {
5153 Some(
5154 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5155 .shape(ui::IconButtonShape::Square)
5156 .icon_size(IconSize::XSmall)
5157 .icon_color(Color::Muted)
5158 .selected(is_active)
5159 .on_click(cx.listener(move |editor, _e, cx| {
5160 editor.focus(cx);
5161 editor.toggle_code_actions(
5162 &ToggleCodeActions {
5163 deployed_from_indicator: Some(row),
5164 },
5165 cx,
5166 );
5167 })),
5168 )
5169 } else {
5170 None
5171 }
5172 }
5173
5174 fn clear_tasks(&mut self) {
5175 self.tasks.clear()
5176 }
5177
5178 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5179 if let Some(_) = self.tasks.insert(key, value) {
5180 // This case should hopefully be rare, but just in case...
5181 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5182 }
5183 }
5184
5185 fn render_run_indicator(
5186 &self,
5187 _style: &EditorStyle,
5188 is_active: bool,
5189 row: DisplayRow,
5190 cx: &mut ViewContext<Self>,
5191 ) -> IconButton {
5192 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5193 .shape(ui::IconButtonShape::Square)
5194 .icon_size(IconSize::XSmall)
5195 .icon_color(Color::Muted)
5196 .selected(is_active)
5197 .on_click(cx.listener(move |editor, _e, cx| {
5198 editor.focus(cx);
5199 editor.toggle_code_actions(
5200 &ToggleCodeActions {
5201 deployed_from_indicator: Some(row),
5202 },
5203 cx,
5204 );
5205 }))
5206 }
5207
5208 fn close_hunk_diff_button(
5209 &self,
5210 hunk: HoveredHunk,
5211 row: DisplayRow,
5212 cx: &mut ViewContext<Self>,
5213 ) -> IconButton {
5214 IconButton::new(
5215 ("close_hunk_diff_indicator", row.0 as usize),
5216 ui::IconName::Close,
5217 )
5218 .shape(ui::IconButtonShape::Square)
5219 .icon_size(IconSize::XSmall)
5220 .icon_color(Color::Muted)
5221 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5222 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5223 }
5224
5225 pub fn context_menu_visible(&self) -> bool {
5226 self.context_menu
5227 .read()
5228 .as_ref()
5229 .map_or(false, |menu| menu.visible())
5230 }
5231
5232 fn render_context_menu(
5233 &self,
5234 cursor_position: DisplayPoint,
5235 style: &EditorStyle,
5236 max_height: Pixels,
5237 cx: &mut ViewContext<Editor>,
5238 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5239 self.context_menu.read().as_ref().map(|menu| {
5240 menu.render(
5241 cursor_position,
5242 style,
5243 max_height,
5244 self.workspace.as_ref().map(|(w, _)| w.clone()),
5245 cx,
5246 )
5247 })
5248 }
5249
5250 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5251 cx.notify();
5252 self.completion_tasks.clear();
5253 let context_menu = self.context_menu.write().take();
5254 if context_menu.is_some() {
5255 self.update_visible_inline_completion(cx);
5256 }
5257 context_menu
5258 }
5259
5260 pub fn insert_snippet(
5261 &mut self,
5262 insertion_ranges: &[Range<usize>],
5263 snippet: Snippet,
5264 cx: &mut ViewContext<Self>,
5265 ) -> Result<()> {
5266 struct Tabstop<T> {
5267 is_end_tabstop: bool,
5268 ranges: Vec<Range<T>>,
5269 }
5270
5271 let tabstops = self.buffer.update(cx, |buffer, cx| {
5272 let snippet_text: Arc<str> = snippet.text.clone().into();
5273 buffer.edit(
5274 insertion_ranges
5275 .iter()
5276 .cloned()
5277 .map(|range| (range, snippet_text.clone())),
5278 Some(AutoindentMode::EachLine),
5279 cx,
5280 );
5281
5282 let snapshot = &*buffer.read(cx);
5283 let snippet = &snippet;
5284 snippet
5285 .tabstops
5286 .iter()
5287 .map(|tabstop| {
5288 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5289 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5290 });
5291 let mut tabstop_ranges = tabstop
5292 .iter()
5293 .flat_map(|tabstop_range| {
5294 let mut delta = 0_isize;
5295 insertion_ranges.iter().map(move |insertion_range| {
5296 let insertion_start = insertion_range.start as isize + delta;
5297 delta +=
5298 snippet.text.len() as isize - insertion_range.len() as isize;
5299
5300 let start = ((insertion_start + tabstop_range.start) as usize)
5301 .min(snapshot.len());
5302 let end = ((insertion_start + tabstop_range.end) as usize)
5303 .min(snapshot.len());
5304 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5305 })
5306 })
5307 .collect::<Vec<_>>();
5308 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5309
5310 Tabstop {
5311 is_end_tabstop,
5312 ranges: tabstop_ranges,
5313 }
5314 })
5315 .collect::<Vec<_>>()
5316 });
5317 if let Some(tabstop) = tabstops.first() {
5318 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5319 s.select_ranges(tabstop.ranges.iter().cloned());
5320 });
5321
5322 // If we're already at the last tabstop and it's at the end of the snippet,
5323 // we're done, we don't need to keep the state around.
5324 if !tabstop.is_end_tabstop {
5325 let ranges = tabstops
5326 .into_iter()
5327 .map(|tabstop| tabstop.ranges)
5328 .collect::<Vec<_>>();
5329 self.snippet_stack.push(SnippetState {
5330 active_index: 0,
5331 ranges,
5332 });
5333 }
5334
5335 // Check whether the just-entered snippet ends with an auto-closable bracket.
5336 if self.autoclose_regions.is_empty() {
5337 let snapshot = self.buffer.read(cx).snapshot(cx);
5338 for selection in &mut self.selections.all::<Point>(cx) {
5339 let selection_head = selection.head();
5340 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5341 continue;
5342 };
5343
5344 let mut bracket_pair = None;
5345 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5346 let prev_chars = snapshot
5347 .reversed_chars_at(selection_head)
5348 .collect::<String>();
5349 for (pair, enabled) in scope.brackets() {
5350 if enabled
5351 && pair.close
5352 && prev_chars.starts_with(pair.start.as_str())
5353 && next_chars.starts_with(pair.end.as_str())
5354 {
5355 bracket_pair = Some(pair.clone());
5356 break;
5357 }
5358 }
5359 if let Some(pair) = bracket_pair {
5360 let start = snapshot.anchor_after(selection_head);
5361 let end = snapshot.anchor_after(selection_head);
5362 self.autoclose_regions.push(AutocloseRegion {
5363 selection_id: selection.id,
5364 range: start..end,
5365 pair,
5366 });
5367 }
5368 }
5369 }
5370 }
5371 Ok(())
5372 }
5373
5374 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5375 self.move_to_snippet_tabstop(Bias::Right, cx)
5376 }
5377
5378 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5379 self.move_to_snippet_tabstop(Bias::Left, cx)
5380 }
5381
5382 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5383 if let Some(mut snippet) = self.snippet_stack.pop() {
5384 match bias {
5385 Bias::Left => {
5386 if snippet.active_index > 0 {
5387 snippet.active_index -= 1;
5388 } else {
5389 self.snippet_stack.push(snippet);
5390 return false;
5391 }
5392 }
5393 Bias::Right => {
5394 if snippet.active_index + 1 < snippet.ranges.len() {
5395 snippet.active_index += 1;
5396 } else {
5397 self.snippet_stack.push(snippet);
5398 return false;
5399 }
5400 }
5401 }
5402 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5403 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5404 s.select_anchor_ranges(current_ranges.iter().cloned())
5405 });
5406 // If snippet state is not at the last tabstop, push it back on the stack
5407 if snippet.active_index + 1 < snippet.ranges.len() {
5408 self.snippet_stack.push(snippet);
5409 }
5410 return true;
5411 }
5412 }
5413
5414 false
5415 }
5416
5417 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5418 self.transact(cx, |this, cx| {
5419 this.select_all(&SelectAll, cx);
5420 this.insert("", cx);
5421 });
5422 }
5423
5424 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5425 self.transact(cx, |this, cx| {
5426 this.select_autoclose_pair(cx);
5427 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5428 if !this.linked_edit_ranges.is_empty() {
5429 let selections = this.selections.all::<MultiBufferPoint>(cx);
5430 let snapshot = this.buffer.read(cx).snapshot(cx);
5431
5432 for selection in selections.iter() {
5433 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5434 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5435 if selection_start.buffer_id != selection_end.buffer_id {
5436 continue;
5437 }
5438 if let Some(ranges) =
5439 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5440 {
5441 for (buffer, entries) in ranges {
5442 linked_ranges.entry(buffer).or_default().extend(entries);
5443 }
5444 }
5445 }
5446 }
5447
5448 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5449 if !this.selections.line_mode {
5450 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5451 for selection in &mut selections {
5452 if selection.is_empty() {
5453 let old_head = selection.head();
5454 let mut new_head =
5455 movement::left(&display_map, old_head.to_display_point(&display_map))
5456 .to_point(&display_map);
5457 if let Some((buffer, line_buffer_range)) = display_map
5458 .buffer_snapshot
5459 .buffer_line_for_row(MultiBufferRow(old_head.row))
5460 {
5461 let indent_size =
5462 buffer.indent_size_for_line(line_buffer_range.start.row);
5463 let indent_len = match indent_size.kind {
5464 IndentKind::Space => {
5465 buffer.settings_at(line_buffer_range.start, cx).tab_size
5466 }
5467 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5468 };
5469 if old_head.column <= indent_size.len && old_head.column > 0 {
5470 let indent_len = indent_len.get();
5471 new_head = cmp::min(
5472 new_head,
5473 MultiBufferPoint::new(
5474 old_head.row,
5475 ((old_head.column - 1) / indent_len) * indent_len,
5476 ),
5477 );
5478 }
5479 }
5480
5481 selection.set_head(new_head, SelectionGoal::None);
5482 }
5483 }
5484 }
5485
5486 this.signature_help_state.set_backspace_pressed(true);
5487 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5488 this.insert("", cx);
5489 let empty_str: Arc<str> = Arc::from("");
5490 for (buffer, edits) in linked_ranges {
5491 let snapshot = buffer.read(cx).snapshot();
5492 use text::ToPoint as TP;
5493
5494 let edits = edits
5495 .into_iter()
5496 .map(|range| {
5497 let end_point = TP::to_point(&range.end, &snapshot);
5498 let mut start_point = TP::to_point(&range.start, &snapshot);
5499
5500 if end_point == start_point {
5501 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5502 .saturating_sub(1);
5503 start_point = TP::to_point(&offset, &snapshot);
5504 };
5505
5506 (start_point..end_point, empty_str.clone())
5507 })
5508 .sorted_by_key(|(range, _)| range.start)
5509 .collect::<Vec<_>>();
5510 buffer.update(cx, |this, cx| {
5511 this.edit(edits, None, cx);
5512 })
5513 }
5514 this.refresh_inline_completion(true, cx);
5515 linked_editing_ranges::refresh_linked_ranges(this, cx);
5516 });
5517 }
5518
5519 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5520 self.transact(cx, |this, cx| {
5521 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5522 let line_mode = s.line_mode;
5523 s.move_with(|map, selection| {
5524 if selection.is_empty() && !line_mode {
5525 let cursor = movement::right(map, selection.head());
5526 selection.end = cursor;
5527 selection.reversed = true;
5528 selection.goal = SelectionGoal::None;
5529 }
5530 })
5531 });
5532 this.insert("", cx);
5533 this.refresh_inline_completion(true, cx);
5534 });
5535 }
5536
5537 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5538 if self.move_to_prev_snippet_tabstop(cx) {
5539 return;
5540 }
5541
5542 self.outdent(&Outdent, cx);
5543 }
5544
5545 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5546 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5547 return;
5548 }
5549
5550 let mut selections = self.selections.all_adjusted(cx);
5551 let buffer = self.buffer.read(cx);
5552 let snapshot = buffer.snapshot(cx);
5553 let rows_iter = selections.iter().map(|s| s.head().row);
5554 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5555
5556 let mut edits = Vec::new();
5557 let mut prev_edited_row = 0;
5558 let mut row_delta = 0;
5559 for selection in &mut selections {
5560 if selection.start.row != prev_edited_row {
5561 row_delta = 0;
5562 }
5563 prev_edited_row = selection.end.row;
5564
5565 // If the selection is non-empty, then increase the indentation of the selected lines.
5566 if !selection.is_empty() {
5567 row_delta =
5568 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5569 continue;
5570 }
5571
5572 // If the selection is empty and the cursor is in the leading whitespace before the
5573 // suggested indentation, then auto-indent the line.
5574 let cursor = selection.head();
5575 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5576 if let Some(suggested_indent) =
5577 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5578 {
5579 if cursor.column < suggested_indent.len
5580 && cursor.column <= current_indent.len
5581 && current_indent.len <= suggested_indent.len
5582 {
5583 selection.start = Point::new(cursor.row, suggested_indent.len);
5584 selection.end = selection.start;
5585 if row_delta == 0 {
5586 edits.extend(Buffer::edit_for_indent_size_adjustment(
5587 cursor.row,
5588 current_indent,
5589 suggested_indent,
5590 ));
5591 row_delta = suggested_indent.len - current_indent.len;
5592 }
5593 continue;
5594 }
5595 }
5596
5597 // Otherwise, insert a hard or soft tab.
5598 let settings = buffer.settings_at(cursor, cx);
5599 let tab_size = if settings.hard_tabs {
5600 IndentSize::tab()
5601 } else {
5602 let tab_size = settings.tab_size.get();
5603 let char_column = snapshot
5604 .text_for_range(Point::new(cursor.row, 0)..cursor)
5605 .flat_map(str::chars)
5606 .count()
5607 + row_delta as usize;
5608 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5609 IndentSize::spaces(chars_to_next_tab_stop)
5610 };
5611 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5612 selection.end = selection.start;
5613 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5614 row_delta += tab_size.len;
5615 }
5616
5617 self.transact(cx, |this, cx| {
5618 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5619 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5620 this.refresh_inline_completion(true, cx);
5621 });
5622 }
5623
5624 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5625 if self.read_only(cx) {
5626 return;
5627 }
5628 let mut selections = self.selections.all::<Point>(cx);
5629 let mut prev_edited_row = 0;
5630 let mut row_delta = 0;
5631 let mut edits = Vec::new();
5632 let buffer = self.buffer.read(cx);
5633 let snapshot = buffer.snapshot(cx);
5634 for selection in &mut selections {
5635 if selection.start.row != prev_edited_row {
5636 row_delta = 0;
5637 }
5638 prev_edited_row = selection.end.row;
5639
5640 row_delta =
5641 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5642 }
5643
5644 self.transact(cx, |this, cx| {
5645 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5646 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5647 });
5648 }
5649
5650 fn indent_selection(
5651 buffer: &MultiBuffer,
5652 snapshot: &MultiBufferSnapshot,
5653 selection: &mut Selection<Point>,
5654 edits: &mut Vec<(Range<Point>, String)>,
5655 delta_for_start_row: u32,
5656 cx: &AppContext,
5657 ) -> u32 {
5658 let settings = buffer.settings_at(selection.start, cx);
5659 let tab_size = settings.tab_size.get();
5660 let indent_kind = if settings.hard_tabs {
5661 IndentKind::Tab
5662 } else {
5663 IndentKind::Space
5664 };
5665 let mut start_row = selection.start.row;
5666 let mut end_row = selection.end.row + 1;
5667
5668 // If a selection ends at the beginning of a line, don't indent
5669 // that last line.
5670 if selection.end.column == 0 && selection.end.row > selection.start.row {
5671 end_row -= 1;
5672 }
5673
5674 // Avoid re-indenting a row that has already been indented by a
5675 // previous selection, but still update this selection's column
5676 // to reflect that indentation.
5677 if delta_for_start_row > 0 {
5678 start_row += 1;
5679 selection.start.column += delta_for_start_row;
5680 if selection.end.row == selection.start.row {
5681 selection.end.column += delta_for_start_row;
5682 }
5683 }
5684
5685 let mut delta_for_end_row = 0;
5686 let has_multiple_rows = start_row + 1 != end_row;
5687 for row in start_row..end_row {
5688 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5689 let indent_delta = match (current_indent.kind, indent_kind) {
5690 (IndentKind::Space, IndentKind::Space) => {
5691 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5692 IndentSize::spaces(columns_to_next_tab_stop)
5693 }
5694 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5695 (_, IndentKind::Tab) => IndentSize::tab(),
5696 };
5697
5698 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5699 0
5700 } else {
5701 selection.start.column
5702 };
5703 let row_start = Point::new(row, start);
5704 edits.push((
5705 row_start..row_start,
5706 indent_delta.chars().collect::<String>(),
5707 ));
5708
5709 // Update this selection's endpoints to reflect the indentation.
5710 if row == selection.start.row {
5711 selection.start.column += indent_delta.len;
5712 }
5713 if row == selection.end.row {
5714 selection.end.column += indent_delta.len;
5715 delta_for_end_row = indent_delta.len;
5716 }
5717 }
5718
5719 if selection.start.row == selection.end.row {
5720 delta_for_start_row + delta_for_end_row
5721 } else {
5722 delta_for_end_row
5723 }
5724 }
5725
5726 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5727 if self.read_only(cx) {
5728 return;
5729 }
5730 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5731 let selections = self.selections.all::<Point>(cx);
5732 let mut deletion_ranges = Vec::new();
5733 let mut last_outdent = None;
5734 {
5735 let buffer = self.buffer.read(cx);
5736 let snapshot = buffer.snapshot(cx);
5737 for selection in &selections {
5738 let settings = buffer.settings_at(selection.start, cx);
5739 let tab_size = settings.tab_size.get();
5740 let mut rows = selection.spanned_rows(false, &display_map);
5741
5742 // Avoid re-outdenting a row that has already been outdented by a
5743 // previous selection.
5744 if let Some(last_row) = last_outdent {
5745 if last_row == rows.start {
5746 rows.start = rows.start.next_row();
5747 }
5748 }
5749 let has_multiple_rows = rows.len() > 1;
5750 for row in rows.iter_rows() {
5751 let indent_size = snapshot.indent_size_for_line(row);
5752 if indent_size.len > 0 {
5753 let deletion_len = match indent_size.kind {
5754 IndentKind::Space => {
5755 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5756 if columns_to_prev_tab_stop == 0 {
5757 tab_size
5758 } else {
5759 columns_to_prev_tab_stop
5760 }
5761 }
5762 IndentKind::Tab => 1,
5763 };
5764 let start = if has_multiple_rows
5765 || deletion_len > selection.start.column
5766 || indent_size.len < selection.start.column
5767 {
5768 0
5769 } else {
5770 selection.start.column - deletion_len
5771 };
5772 deletion_ranges.push(
5773 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5774 );
5775 last_outdent = Some(row);
5776 }
5777 }
5778 }
5779 }
5780
5781 self.transact(cx, |this, cx| {
5782 this.buffer.update(cx, |buffer, cx| {
5783 let empty_str: Arc<str> = Arc::default();
5784 buffer.edit(
5785 deletion_ranges
5786 .into_iter()
5787 .map(|range| (range, empty_str.clone())),
5788 None,
5789 cx,
5790 );
5791 });
5792 let selections = this.selections.all::<usize>(cx);
5793 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5794 });
5795 }
5796
5797 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5798 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5799 let selections = self.selections.all::<Point>(cx);
5800
5801 let mut new_cursors = Vec::new();
5802 let mut edit_ranges = Vec::new();
5803 let mut selections = selections.iter().peekable();
5804 while let Some(selection) = selections.next() {
5805 let mut rows = selection.spanned_rows(false, &display_map);
5806 let goal_display_column = selection.head().to_display_point(&display_map).column();
5807
5808 // Accumulate contiguous regions of rows that we want to delete.
5809 while let Some(next_selection) = selections.peek() {
5810 let next_rows = next_selection.spanned_rows(false, &display_map);
5811 if next_rows.start <= rows.end {
5812 rows.end = next_rows.end;
5813 selections.next().unwrap();
5814 } else {
5815 break;
5816 }
5817 }
5818
5819 let buffer = &display_map.buffer_snapshot;
5820 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5821 let edit_end;
5822 let cursor_buffer_row;
5823 if buffer.max_point().row >= rows.end.0 {
5824 // If there's a line after the range, delete the \n from the end of the row range
5825 // and position the cursor on the next line.
5826 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5827 cursor_buffer_row = rows.end;
5828 } else {
5829 // If there isn't a line after the range, delete the \n from the line before the
5830 // start of the row range and position the cursor there.
5831 edit_start = edit_start.saturating_sub(1);
5832 edit_end = buffer.len();
5833 cursor_buffer_row = rows.start.previous_row();
5834 }
5835
5836 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5837 *cursor.column_mut() =
5838 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5839
5840 new_cursors.push((
5841 selection.id,
5842 buffer.anchor_after(cursor.to_point(&display_map)),
5843 ));
5844 edit_ranges.push(edit_start..edit_end);
5845 }
5846
5847 self.transact(cx, |this, cx| {
5848 let buffer = this.buffer.update(cx, |buffer, cx| {
5849 let empty_str: Arc<str> = Arc::default();
5850 buffer.edit(
5851 edit_ranges
5852 .into_iter()
5853 .map(|range| (range, empty_str.clone())),
5854 None,
5855 cx,
5856 );
5857 buffer.snapshot(cx)
5858 });
5859 let new_selections = new_cursors
5860 .into_iter()
5861 .map(|(id, cursor)| {
5862 let cursor = cursor.to_point(&buffer);
5863 Selection {
5864 id,
5865 start: cursor,
5866 end: cursor,
5867 reversed: false,
5868 goal: SelectionGoal::None,
5869 }
5870 })
5871 .collect();
5872
5873 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5874 s.select(new_selections);
5875 });
5876 });
5877 }
5878
5879 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5880 if self.read_only(cx) {
5881 return;
5882 }
5883 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5884 for selection in self.selections.all::<Point>(cx) {
5885 let start = MultiBufferRow(selection.start.row);
5886 let end = if selection.start.row == selection.end.row {
5887 MultiBufferRow(selection.start.row + 1)
5888 } else {
5889 MultiBufferRow(selection.end.row)
5890 };
5891
5892 if let Some(last_row_range) = row_ranges.last_mut() {
5893 if start <= last_row_range.end {
5894 last_row_range.end = end;
5895 continue;
5896 }
5897 }
5898 row_ranges.push(start..end);
5899 }
5900
5901 let snapshot = self.buffer.read(cx).snapshot(cx);
5902 let mut cursor_positions = Vec::new();
5903 for row_range in &row_ranges {
5904 let anchor = snapshot.anchor_before(Point::new(
5905 row_range.end.previous_row().0,
5906 snapshot.line_len(row_range.end.previous_row()),
5907 ));
5908 cursor_positions.push(anchor..anchor);
5909 }
5910
5911 self.transact(cx, |this, cx| {
5912 for row_range in row_ranges.into_iter().rev() {
5913 for row in row_range.iter_rows().rev() {
5914 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5915 let next_line_row = row.next_row();
5916 let indent = snapshot.indent_size_for_line(next_line_row);
5917 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5918
5919 let replace = if snapshot.line_len(next_line_row) > indent.len {
5920 " "
5921 } else {
5922 ""
5923 };
5924
5925 this.buffer.update(cx, |buffer, cx| {
5926 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5927 });
5928 }
5929 }
5930
5931 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5932 s.select_anchor_ranges(cursor_positions)
5933 });
5934 });
5935 }
5936
5937 pub fn sort_lines_case_sensitive(
5938 &mut self,
5939 _: &SortLinesCaseSensitive,
5940 cx: &mut ViewContext<Self>,
5941 ) {
5942 self.manipulate_lines(cx, |lines| lines.sort())
5943 }
5944
5945 pub fn sort_lines_case_insensitive(
5946 &mut self,
5947 _: &SortLinesCaseInsensitive,
5948 cx: &mut ViewContext<Self>,
5949 ) {
5950 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5951 }
5952
5953 pub fn unique_lines_case_insensitive(
5954 &mut self,
5955 _: &UniqueLinesCaseInsensitive,
5956 cx: &mut ViewContext<Self>,
5957 ) {
5958 self.manipulate_lines(cx, |lines| {
5959 let mut seen = HashSet::default();
5960 lines.retain(|line| seen.insert(line.to_lowercase()));
5961 })
5962 }
5963
5964 pub fn unique_lines_case_sensitive(
5965 &mut self,
5966 _: &UniqueLinesCaseSensitive,
5967 cx: &mut ViewContext<Self>,
5968 ) {
5969 self.manipulate_lines(cx, |lines| {
5970 let mut seen = HashSet::default();
5971 lines.retain(|line| seen.insert(*line));
5972 })
5973 }
5974
5975 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5976 let mut revert_changes = HashMap::default();
5977 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
5978 for hunk in hunks_for_rows(
5979 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
5980 &multi_buffer_snapshot,
5981 ) {
5982 Self::prepare_revert_change(&mut revert_changes, &self.buffer(), &hunk, cx);
5983 }
5984 if !revert_changes.is_empty() {
5985 self.transact(cx, |editor, cx| {
5986 editor.revert(revert_changes, cx);
5987 });
5988 }
5989 }
5990
5991 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5992 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
5993 if !revert_changes.is_empty() {
5994 self.transact(cx, |editor, cx| {
5995 editor.revert(revert_changes, cx);
5996 });
5997 }
5998 }
5999
6000 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6001 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6002 let project_path = buffer.read(cx).project_path(cx)?;
6003 let project = self.project.as_ref()?.read(cx);
6004 let entry = project.entry_for_path(&project_path, cx)?;
6005 let abs_path = project.absolute_path(&project_path, cx)?;
6006 let parent = if entry.is_symlink {
6007 abs_path.canonicalize().ok()?
6008 } else {
6009 abs_path
6010 }
6011 .parent()?
6012 .to_path_buf();
6013 Some(parent)
6014 }) {
6015 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6016 }
6017 }
6018
6019 fn gather_revert_changes(
6020 &mut self,
6021 selections: &[Selection<Anchor>],
6022 cx: &mut ViewContext<'_, Editor>,
6023 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6024 let mut revert_changes = HashMap::default();
6025 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6026 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6027 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6028 }
6029 revert_changes
6030 }
6031
6032 pub fn prepare_revert_change(
6033 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6034 multi_buffer: &Model<MultiBuffer>,
6035 hunk: &DiffHunk<MultiBufferRow>,
6036 cx: &AppContext,
6037 ) -> Option<()> {
6038 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6039 let buffer = buffer.read(cx);
6040 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6041 let buffer_snapshot = buffer.snapshot();
6042 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6043 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6044 probe
6045 .0
6046 .start
6047 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6048 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6049 }) {
6050 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6051 Some(())
6052 } else {
6053 None
6054 }
6055 }
6056
6057 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6058 self.manipulate_lines(cx, |lines| lines.reverse())
6059 }
6060
6061 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6062 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6063 }
6064
6065 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6066 where
6067 Fn: FnMut(&mut Vec<&str>),
6068 {
6069 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6070 let buffer = self.buffer.read(cx).snapshot(cx);
6071
6072 let mut edits = Vec::new();
6073
6074 let selections = self.selections.all::<Point>(cx);
6075 let mut selections = selections.iter().peekable();
6076 let mut contiguous_row_selections = Vec::new();
6077 let mut new_selections = Vec::new();
6078 let mut added_lines = 0;
6079 let mut removed_lines = 0;
6080
6081 while let Some(selection) = selections.next() {
6082 let (start_row, end_row) = consume_contiguous_rows(
6083 &mut contiguous_row_selections,
6084 selection,
6085 &display_map,
6086 &mut selections,
6087 );
6088
6089 let start_point = Point::new(start_row.0, 0);
6090 let end_point = Point::new(
6091 end_row.previous_row().0,
6092 buffer.line_len(end_row.previous_row()),
6093 );
6094 let text = buffer
6095 .text_for_range(start_point..end_point)
6096 .collect::<String>();
6097
6098 let mut lines = text.split('\n').collect_vec();
6099
6100 let lines_before = lines.len();
6101 callback(&mut lines);
6102 let lines_after = lines.len();
6103
6104 edits.push((start_point..end_point, lines.join("\n")));
6105
6106 // Selections must change based on added and removed line count
6107 let start_row =
6108 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6109 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6110 new_selections.push(Selection {
6111 id: selection.id,
6112 start: start_row,
6113 end: end_row,
6114 goal: SelectionGoal::None,
6115 reversed: selection.reversed,
6116 });
6117
6118 if lines_after > lines_before {
6119 added_lines += lines_after - lines_before;
6120 } else if lines_before > lines_after {
6121 removed_lines += lines_before - lines_after;
6122 }
6123 }
6124
6125 self.transact(cx, |this, cx| {
6126 let buffer = this.buffer.update(cx, |buffer, cx| {
6127 buffer.edit(edits, None, cx);
6128 buffer.snapshot(cx)
6129 });
6130
6131 // Recalculate offsets on newly edited buffer
6132 let new_selections = new_selections
6133 .iter()
6134 .map(|s| {
6135 let start_point = Point::new(s.start.0, 0);
6136 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6137 Selection {
6138 id: s.id,
6139 start: buffer.point_to_offset(start_point),
6140 end: buffer.point_to_offset(end_point),
6141 goal: s.goal,
6142 reversed: s.reversed,
6143 }
6144 })
6145 .collect();
6146
6147 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6148 s.select(new_selections);
6149 });
6150
6151 this.request_autoscroll(Autoscroll::fit(), cx);
6152 });
6153 }
6154
6155 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6156 self.manipulate_text(cx, |text| text.to_uppercase())
6157 }
6158
6159 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6160 self.manipulate_text(cx, |text| text.to_lowercase())
6161 }
6162
6163 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6164 self.manipulate_text(cx, |text| {
6165 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6166 // https://github.com/rutrum/convert-case/issues/16
6167 text.split('\n')
6168 .map(|line| line.to_case(Case::Title))
6169 .join("\n")
6170 })
6171 }
6172
6173 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6174 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6175 }
6176
6177 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6178 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6179 }
6180
6181 pub fn convert_to_upper_camel_case(
6182 &mut self,
6183 _: &ConvertToUpperCamelCase,
6184 cx: &mut ViewContext<Self>,
6185 ) {
6186 self.manipulate_text(cx, |text| {
6187 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6188 // https://github.com/rutrum/convert-case/issues/16
6189 text.split('\n')
6190 .map(|line| line.to_case(Case::UpperCamel))
6191 .join("\n")
6192 })
6193 }
6194
6195 pub fn convert_to_lower_camel_case(
6196 &mut self,
6197 _: &ConvertToLowerCamelCase,
6198 cx: &mut ViewContext<Self>,
6199 ) {
6200 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6201 }
6202
6203 pub fn convert_to_opposite_case(
6204 &mut self,
6205 _: &ConvertToOppositeCase,
6206 cx: &mut ViewContext<Self>,
6207 ) {
6208 self.manipulate_text(cx, |text| {
6209 text.chars()
6210 .fold(String::with_capacity(text.len()), |mut t, c| {
6211 if c.is_uppercase() {
6212 t.extend(c.to_lowercase());
6213 } else {
6214 t.extend(c.to_uppercase());
6215 }
6216 t
6217 })
6218 })
6219 }
6220
6221 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6222 where
6223 Fn: FnMut(&str) -> String,
6224 {
6225 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6226 let buffer = self.buffer.read(cx).snapshot(cx);
6227
6228 let mut new_selections = Vec::new();
6229 let mut edits = Vec::new();
6230 let mut selection_adjustment = 0i32;
6231
6232 for selection in self.selections.all::<usize>(cx) {
6233 let selection_is_empty = selection.is_empty();
6234
6235 let (start, end) = if selection_is_empty {
6236 let word_range = movement::surrounding_word(
6237 &display_map,
6238 selection.start.to_display_point(&display_map),
6239 );
6240 let start = word_range.start.to_offset(&display_map, Bias::Left);
6241 let end = word_range.end.to_offset(&display_map, Bias::Left);
6242 (start, end)
6243 } else {
6244 (selection.start, selection.end)
6245 };
6246
6247 let text = buffer.text_for_range(start..end).collect::<String>();
6248 let old_length = text.len() as i32;
6249 let text = callback(&text);
6250
6251 new_selections.push(Selection {
6252 start: (start as i32 - selection_adjustment) as usize,
6253 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6254 goal: SelectionGoal::None,
6255 ..selection
6256 });
6257
6258 selection_adjustment += old_length - text.len() as i32;
6259
6260 edits.push((start..end, text));
6261 }
6262
6263 self.transact(cx, |this, cx| {
6264 this.buffer.update(cx, |buffer, cx| {
6265 buffer.edit(edits, None, cx);
6266 });
6267
6268 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6269 s.select(new_selections);
6270 });
6271
6272 this.request_autoscroll(Autoscroll::fit(), cx);
6273 });
6274 }
6275
6276 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6277 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6278 let buffer = &display_map.buffer_snapshot;
6279 let selections = self.selections.all::<Point>(cx);
6280
6281 let mut edits = Vec::new();
6282 let mut selections_iter = selections.iter().peekable();
6283 while let Some(selection) = selections_iter.next() {
6284 // Avoid duplicating the same lines twice.
6285 let mut rows = selection.spanned_rows(false, &display_map);
6286
6287 while let Some(next_selection) = selections_iter.peek() {
6288 let next_rows = next_selection.spanned_rows(false, &display_map);
6289 if next_rows.start < rows.end {
6290 rows.end = next_rows.end;
6291 selections_iter.next().unwrap();
6292 } else {
6293 break;
6294 }
6295 }
6296
6297 // Copy the text from the selected row region and splice it either at the start
6298 // or end of the region.
6299 let start = Point::new(rows.start.0, 0);
6300 let end = Point::new(
6301 rows.end.previous_row().0,
6302 buffer.line_len(rows.end.previous_row()),
6303 );
6304 let text = buffer
6305 .text_for_range(start..end)
6306 .chain(Some("\n"))
6307 .collect::<String>();
6308 let insert_location = if upwards {
6309 Point::new(rows.end.0, 0)
6310 } else {
6311 start
6312 };
6313 edits.push((insert_location..insert_location, text));
6314 }
6315
6316 self.transact(cx, |this, cx| {
6317 this.buffer.update(cx, |buffer, cx| {
6318 buffer.edit(edits, None, cx);
6319 });
6320
6321 this.request_autoscroll(Autoscroll::fit(), cx);
6322 });
6323 }
6324
6325 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6326 self.duplicate_line(true, cx);
6327 }
6328
6329 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6330 self.duplicate_line(false, cx);
6331 }
6332
6333 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6334 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6335 let buffer = self.buffer.read(cx).snapshot(cx);
6336
6337 let mut edits = Vec::new();
6338 let mut unfold_ranges = Vec::new();
6339 let mut refold_ranges = Vec::new();
6340
6341 let selections = self.selections.all::<Point>(cx);
6342 let mut selections = selections.iter().peekable();
6343 let mut contiguous_row_selections = Vec::new();
6344 let mut new_selections = Vec::new();
6345
6346 while let Some(selection) = selections.next() {
6347 // Find all the selections that span a contiguous row range
6348 let (start_row, end_row) = consume_contiguous_rows(
6349 &mut contiguous_row_selections,
6350 selection,
6351 &display_map,
6352 &mut selections,
6353 );
6354
6355 // Move the text spanned by the row range to be before the line preceding the row range
6356 if start_row.0 > 0 {
6357 let range_to_move = Point::new(
6358 start_row.previous_row().0,
6359 buffer.line_len(start_row.previous_row()),
6360 )
6361 ..Point::new(
6362 end_row.previous_row().0,
6363 buffer.line_len(end_row.previous_row()),
6364 );
6365 let insertion_point = display_map
6366 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6367 .0;
6368
6369 // Don't move lines across excerpts
6370 if buffer
6371 .excerpt_boundaries_in_range((
6372 Bound::Excluded(insertion_point),
6373 Bound::Included(range_to_move.end),
6374 ))
6375 .next()
6376 .is_none()
6377 {
6378 let text = buffer
6379 .text_for_range(range_to_move.clone())
6380 .flat_map(|s| s.chars())
6381 .skip(1)
6382 .chain(['\n'])
6383 .collect::<String>();
6384
6385 edits.push((
6386 buffer.anchor_after(range_to_move.start)
6387 ..buffer.anchor_before(range_to_move.end),
6388 String::new(),
6389 ));
6390 let insertion_anchor = buffer.anchor_after(insertion_point);
6391 edits.push((insertion_anchor..insertion_anchor, text));
6392
6393 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6394
6395 // Move selections up
6396 new_selections.extend(contiguous_row_selections.drain(..).map(
6397 |mut selection| {
6398 selection.start.row -= row_delta;
6399 selection.end.row -= row_delta;
6400 selection
6401 },
6402 ));
6403
6404 // Move folds up
6405 unfold_ranges.push(range_to_move.clone());
6406 for fold in display_map.folds_in_range(
6407 buffer.anchor_before(range_to_move.start)
6408 ..buffer.anchor_after(range_to_move.end),
6409 ) {
6410 let mut start = fold.range.start.to_point(&buffer);
6411 let mut end = fold.range.end.to_point(&buffer);
6412 start.row -= row_delta;
6413 end.row -= row_delta;
6414 refold_ranges.push((start..end, fold.placeholder.clone()));
6415 }
6416 }
6417 }
6418
6419 // If we didn't move line(s), preserve the existing selections
6420 new_selections.append(&mut contiguous_row_selections);
6421 }
6422
6423 self.transact(cx, |this, cx| {
6424 this.unfold_ranges(unfold_ranges, true, true, cx);
6425 this.buffer.update(cx, |buffer, cx| {
6426 for (range, text) in edits {
6427 buffer.edit([(range, text)], None, cx);
6428 }
6429 });
6430 this.fold_ranges(refold_ranges, true, cx);
6431 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6432 s.select(new_selections);
6433 })
6434 });
6435 }
6436
6437 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6438 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6439 let buffer = self.buffer.read(cx).snapshot(cx);
6440
6441 let mut edits = Vec::new();
6442 let mut unfold_ranges = Vec::new();
6443 let mut refold_ranges = Vec::new();
6444
6445 let selections = self.selections.all::<Point>(cx);
6446 let mut selections = selections.iter().peekable();
6447 let mut contiguous_row_selections = Vec::new();
6448 let mut new_selections = Vec::new();
6449
6450 while let Some(selection) = selections.next() {
6451 // Find all the selections that span a contiguous row range
6452 let (start_row, end_row) = consume_contiguous_rows(
6453 &mut contiguous_row_selections,
6454 selection,
6455 &display_map,
6456 &mut selections,
6457 );
6458
6459 // Move the text spanned by the row range to be after the last line of the row range
6460 if end_row.0 <= buffer.max_point().row {
6461 let range_to_move =
6462 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6463 let insertion_point = display_map
6464 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6465 .0;
6466
6467 // Don't move lines across excerpt boundaries
6468 if buffer
6469 .excerpt_boundaries_in_range((
6470 Bound::Excluded(range_to_move.start),
6471 Bound::Included(insertion_point),
6472 ))
6473 .next()
6474 .is_none()
6475 {
6476 let mut text = String::from("\n");
6477 text.extend(buffer.text_for_range(range_to_move.clone()));
6478 text.pop(); // Drop trailing newline
6479 edits.push((
6480 buffer.anchor_after(range_to_move.start)
6481 ..buffer.anchor_before(range_to_move.end),
6482 String::new(),
6483 ));
6484 let insertion_anchor = buffer.anchor_after(insertion_point);
6485 edits.push((insertion_anchor..insertion_anchor, text));
6486
6487 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6488
6489 // Move selections down
6490 new_selections.extend(contiguous_row_selections.drain(..).map(
6491 |mut selection| {
6492 selection.start.row += row_delta;
6493 selection.end.row += row_delta;
6494 selection
6495 },
6496 ));
6497
6498 // Move folds down
6499 unfold_ranges.push(range_to_move.clone());
6500 for fold in display_map.folds_in_range(
6501 buffer.anchor_before(range_to_move.start)
6502 ..buffer.anchor_after(range_to_move.end),
6503 ) {
6504 let mut start = fold.range.start.to_point(&buffer);
6505 let mut end = fold.range.end.to_point(&buffer);
6506 start.row += row_delta;
6507 end.row += row_delta;
6508 refold_ranges.push((start..end, fold.placeholder.clone()));
6509 }
6510 }
6511 }
6512
6513 // If we didn't move line(s), preserve the existing selections
6514 new_selections.append(&mut contiguous_row_selections);
6515 }
6516
6517 self.transact(cx, |this, cx| {
6518 this.unfold_ranges(unfold_ranges, true, true, cx);
6519 this.buffer.update(cx, |buffer, cx| {
6520 for (range, text) in edits {
6521 buffer.edit([(range, text)], None, cx);
6522 }
6523 });
6524 this.fold_ranges(refold_ranges, true, cx);
6525 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6526 });
6527 }
6528
6529 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6530 let text_layout_details = &self.text_layout_details(cx);
6531 self.transact(cx, |this, cx| {
6532 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6533 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6534 let line_mode = s.line_mode;
6535 s.move_with(|display_map, selection| {
6536 if !selection.is_empty() || line_mode {
6537 return;
6538 }
6539
6540 let mut head = selection.head();
6541 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6542 if head.column() == display_map.line_len(head.row()) {
6543 transpose_offset = display_map
6544 .buffer_snapshot
6545 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6546 }
6547
6548 if transpose_offset == 0 {
6549 return;
6550 }
6551
6552 *head.column_mut() += 1;
6553 head = display_map.clip_point(head, Bias::Right);
6554 let goal = SelectionGoal::HorizontalPosition(
6555 display_map
6556 .x_for_display_point(head, &text_layout_details)
6557 .into(),
6558 );
6559 selection.collapse_to(head, goal);
6560
6561 let transpose_start = display_map
6562 .buffer_snapshot
6563 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6564 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6565 let transpose_end = display_map
6566 .buffer_snapshot
6567 .clip_offset(transpose_offset + 1, Bias::Right);
6568 if let Some(ch) =
6569 display_map.buffer_snapshot.chars_at(transpose_start).next()
6570 {
6571 edits.push((transpose_start..transpose_offset, String::new()));
6572 edits.push((transpose_end..transpose_end, ch.to_string()));
6573 }
6574 }
6575 });
6576 edits
6577 });
6578 this.buffer
6579 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6580 let selections = this.selections.all::<usize>(cx);
6581 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6582 s.select(selections);
6583 });
6584 });
6585 }
6586
6587 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6588 let mut text = String::new();
6589 let buffer = self.buffer.read(cx).snapshot(cx);
6590 let mut selections = self.selections.all::<Point>(cx);
6591 let mut clipboard_selections = Vec::with_capacity(selections.len());
6592 {
6593 let max_point = buffer.max_point();
6594 let mut is_first = true;
6595 for selection in &mut selections {
6596 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6597 if is_entire_line {
6598 selection.start = Point::new(selection.start.row, 0);
6599 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6600 selection.goal = SelectionGoal::None;
6601 }
6602 if is_first {
6603 is_first = false;
6604 } else {
6605 text += "\n";
6606 }
6607 let mut len = 0;
6608 for chunk in buffer.text_for_range(selection.start..selection.end) {
6609 text.push_str(chunk);
6610 len += chunk.len();
6611 }
6612 clipboard_selections.push(ClipboardSelection {
6613 len,
6614 is_entire_line,
6615 first_line_indent: buffer
6616 .indent_size_for_line(MultiBufferRow(selection.start.row))
6617 .len,
6618 });
6619 }
6620 }
6621
6622 self.transact(cx, |this, cx| {
6623 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6624 s.select(selections);
6625 });
6626 this.insert("", cx);
6627 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6628 text,
6629 clipboard_selections,
6630 ));
6631 });
6632 }
6633
6634 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6635 let selections = self.selections.all::<Point>(cx);
6636 let buffer = self.buffer.read(cx).read(cx);
6637 let mut text = String::new();
6638
6639 let mut clipboard_selections = Vec::with_capacity(selections.len());
6640 {
6641 let max_point = buffer.max_point();
6642 let mut is_first = true;
6643 for selection in selections.iter() {
6644 let mut start = selection.start;
6645 let mut end = selection.end;
6646 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6647 if is_entire_line {
6648 start = Point::new(start.row, 0);
6649 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6650 }
6651 if is_first {
6652 is_first = false;
6653 } else {
6654 text += "\n";
6655 }
6656 let mut len = 0;
6657 for chunk in buffer.text_for_range(start..end) {
6658 text.push_str(chunk);
6659 len += chunk.len();
6660 }
6661 clipboard_selections.push(ClipboardSelection {
6662 len,
6663 is_entire_line,
6664 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6665 });
6666 }
6667 }
6668
6669 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6670 text,
6671 clipboard_selections,
6672 ));
6673 }
6674
6675 pub fn do_paste(
6676 &mut self,
6677 text: &String,
6678 clipboard_selections: Option<Vec<ClipboardSelection>>,
6679 handle_entire_lines: bool,
6680 cx: &mut ViewContext<Self>,
6681 ) {
6682 if self.read_only(cx) {
6683 return;
6684 }
6685
6686 let clipboard_text = Cow::Borrowed(text);
6687
6688 self.transact(cx, |this, cx| {
6689 if let Some(mut clipboard_selections) = clipboard_selections {
6690 let old_selections = this.selections.all::<usize>(cx);
6691 let all_selections_were_entire_line =
6692 clipboard_selections.iter().all(|s| s.is_entire_line);
6693 let first_selection_indent_column =
6694 clipboard_selections.first().map(|s| s.first_line_indent);
6695 if clipboard_selections.len() != old_selections.len() {
6696 clipboard_selections.drain(..);
6697 }
6698
6699 this.buffer.update(cx, |buffer, cx| {
6700 let snapshot = buffer.read(cx);
6701 let mut start_offset = 0;
6702 let mut edits = Vec::new();
6703 let mut original_indent_columns = Vec::new();
6704 for (ix, selection) in old_selections.iter().enumerate() {
6705 let to_insert;
6706 let entire_line;
6707 let original_indent_column;
6708 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6709 let end_offset = start_offset + clipboard_selection.len;
6710 to_insert = &clipboard_text[start_offset..end_offset];
6711 entire_line = clipboard_selection.is_entire_line;
6712 start_offset = end_offset + 1;
6713 original_indent_column = Some(clipboard_selection.first_line_indent);
6714 } else {
6715 to_insert = clipboard_text.as_str();
6716 entire_line = all_selections_were_entire_line;
6717 original_indent_column = first_selection_indent_column
6718 }
6719
6720 // If the corresponding selection was empty when this slice of the
6721 // clipboard text was written, then the entire line containing the
6722 // selection was copied. If this selection is also currently empty,
6723 // then paste the line before the current line of the buffer.
6724 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6725 let column = selection.start.to_point(&snapshot).column as usize;
6726 let line_start = selection.start - column;
6727 line_start..line_start
6728 } else {
6729 selection.range()
6730 };
6731
6732 edits.push((range, to_insert));
6733 original_indent_columns.extend(original_indent_column);
6734 }
6735 drop(snapshot);
6736
6737 buffer.edit(
6738 edits,
6739 Some(AutoindentMode::Block {
6740 original_indent_columns,
6741 }),
6742 cx,
6743 );
6744 });
6745
6746 let selections = this.selections.all::<usize>(cx);
6747 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6748 } else {
6749 this.insert(&clipboard_text, cx);
6750 }
6751 });
6752 }
6753
6754 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6755 if let Some(item) = cx.read_from_clipboard() {
6756 let entries = item.entries();
6757
6758 match entries.first() {
6759 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6760 // of all the pasted entries.
6761 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6762 .do_paste(
6763 clipboard_string.text(),
6764 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6765 true,
6766 cx,
6767 ),
6768 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6769 }
6770 }
6771 }
6772
6773 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6774 if self.read_only(cx) {
6775 return;
6776 }
6777
6778 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6779 if let Some((selections, _)) =
6780 self.selection_history.transaction(transaction_id).cloned()
6781 {
6782 self.change_selections(None, cx, |s| {
6783 s.select_anchors(selections.to_vec());
6784 });
6785 }
6786 self.request_autoscroll(Autoscroll::fit(), cx);
6787 self.unmark_text(cx);
6788 self.refresh_inline_completion(true, cx);
6789 cx.emit(EditorEvent::Edited { transaction_id });
6790 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6791 }
6792 }
6793
6794 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6795 if self.read_only(cx) {
6796 return;
6797 }
6798
6799 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6800 if let Some((_, Some(selections))) =
6801 self.selection_history.transaction(transaction_id).cloned()
6802 {
6803 self.change_selections(None, cx, |s| {
6804 s.select_anchors(selections.to_vec());
6805 });
6806 }
6807 self.request_autoscroll(Autoscroll::fit(), cx);
6808 self.unmark_text(cx);
6809 self.refresh_inline_completion(true, cx);
6810 cx.emit(EditorEvent::Edited { transaction_id });
6811 }
6812 }
6813
6814 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6815 self.buffer
6816 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6817 }
6818
6819 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6820 self.buffer
6821 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6822 }
6823
6824 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6825 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6826 let line_mode = s.line_mode;
6827 s.move_with(|map, selection| {
6828 let cursor = if selection.is_empty() && !line_mode {
6829 movement::left(map, selection.start)
6830 } else {
6831 selection.start
6832 };
6833 selection.collapse_to(cursor, SelectionGoal::None);
6834 });
6835 })
6836 }
6837
6838 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6839 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6840 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6841 })
6842 }
6843
6844 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6845 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6846 let line_mode = s.line_mode;
6847 s.move_with(|map, selection| {
6848 let cursor = if selection.is_empty() && !line_mode {
6849 movement::right(map, selection.end)
6850 } else {
6851 selection.end
6852 };
6853 selection.collapse_to(cursor, SelectionGoal::None)
6854 });
6855 })
6856 }
6857
6858 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6859 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6860 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6861 })
6862 }
6863
6864 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6865 if self.take_rename(true, cx).is_some() {
6866 return;
6867 }
6868
6869 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6870 cx.propagate();
6871 return;
6872 }
6873
6874 let text_layout_details = &self.text_layout_details(cx);
6875 let selection_count = self.selections.count();
6876 let first_selection = self.selections.first_anchor();
6877
6878 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6879 let line_mode = s.line_mode;
6880 s.move_with(|map, selection| {
6881 if !selection.is_empty() && !line_mode {
6882 selection.goal = SelectionGoal::None;
6883 }
6884 let (cursor, goal) = movement::up(
6885 map,
6886 selection.start,
6887 selection.goal,
6888 false,
6889 &text_layout_details,
6890 );
6891 selection.collapse_to(cursor, goal);
6892 });
6893 });
6894
6895 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6896 {
6897 cx.propagate();
6898 }
6899 }
6900
6901 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6902 if self.take_rename(true, cx).is_some() {
6903 return;
6904 }
6905
6906 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6907 cx.propagate();
6908 return;
6909 }
6910
6911 let text_layout_details = &self.text_layout_details(cx);
6912
6913 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6914 let line_mode = s.line_mode;
6915 s.move_with(|map, selection| {
6916 if !selection.is_empty() && !line_mode {
6917 selection.goal = SelectionGoal::None;
6918 }
6919 let (cursor, goal) = movement::up_by_rows(
6920 map,
6921 selection.start,
6922 action.lines,
6923 selection.goal,
6924 false,
6925 &text_layout_details,
6926 );
6927 selection.collapse_to(cursor, goal);
6928 });
6929 })
6930 }
6931
6932 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
6933 if self.take_rename(true, cx).is_some() {
6934 return;
6935 }
6936
6937 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6938 cx.propagate();
6939 return;
6940 }
6941
6942 let text_layout_details = &self.text_layout_details(cx);
6943
6944 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6945 let line_mode = s.line_mode;
6946 s.move_with(|map, selection| {
6947 if !selection.is_empty() && !line_mode {
6948 selection.goal = SelectionGoal::None;
6949 }
6950 let (cursor, goal) = movement::down_by_rows(
6951 map,
6952 selection.start,
6953 action.lines,
6954 selection.goal,
6955 false,
6956 &text_layout_details,
6957 );
6958 selection.collapse_to(cursor, goal);
6959 });
6960 })
6961 }
6962
6963 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
6964 let text_layout_details = &self.text_layout_details(cx);
6965 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6966 s.move_heads_with(|map, head, goal| {
6967 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6968 })
6969 })
6970 }
6971
6972 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
6973 let text_layout_details = &self.text_layout_details(cx);
6974 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6975 s.move_heads_with(|map, head, goal| {
6976 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6977 })
6978 })
6979 }
6980
6981 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
6982 let Some(row_count) = self.visible_row_count() else {
6983 return;
6984 };
6985
6986 let text_layout_details = &self.text_layout_details(cx);
6987
6988 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6989 s.move_heads_with(|map, head, goal| {
6990 movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
6991 })
6992 })
6993 }
6994
6995 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
6996 if self.take_rename(true, cx).is_some() {
6997 return;
6998 }
6999
7000 if self
7001 .context_menu
7002 .write()
7003 .as_mut()
7004 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7005 .unwrap_or(false)
7006 {
7007 return;
7008 }
7009
7010 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7011 cx.propagate();
7012 return;
7013 }
7014
7015 let Some(row_count) = self.visible_row_count() else {
7016 return;
7017 };
7018
7019 let autoscroll = if action.center_cursor {
7020 Autoscroll::center()
7021 } else {
7022 Autoscroll::fit()
7023 };
7024
7025 let text_layout_details = &self.text_layout_details(cx);
7026
7027 self.change_selections(Some(autoscroll), cx, |s| {
7028 let line_mode = s.line_mode;
7029 s.move_with(|map, selection| {
7030 if !selection.is_empty() && !line_mode {
7031 selection.goal = SelectionGoal::None;
7032 }
7033 let (cursor, goal) = movement::up_by_rows(
7034 map,
7035 selection.end,
7036 row_count,
7037 selection.goal,
7038 false,
7039 &text_layout_details,
7040 );
7041 selection.collapse_to(cursor, goal);
7042 });
7043 });
7044 }
7045
7046 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7047 let text_layout_details = &self.text_layout_details(cx);
7048 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7049 s.move_heads_with(|map, head, goal| {
7050 movement::up(map, head, goal, false, &text_layout_details)
7051 })
7052 })
7053 }
7054
7055 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7056 self.take_rename(true, cx);
7057
7058 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7059 cx.propagate();
7060 return;
7061 }
7062
7063 let text_layout_details = &self.text_layout_details(cx);
7064 let selection_count = self.selections.count();
7065 let first_selection = self.selections.first_anchor();
7066
7067 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7068 let line_mode = s.line_mode;
7069 s.move_with(|map, selection| {
7070 if !selection.is_empty() && !line_mode {
7071 selection.goal = SelectionGoal::None;
7072 }
7073 let (cursor, goal) = movement::down(
7074 map,
7075 selection.end,
7076 selection.goal,
7077 false,
7078 &text_layout_details,
7079 );
7080 selection.collapse_to(cursor, goal);
7081 });
7082 });
7083
7084 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7085 {
7086 cx.propagate();
7087 }
7088 }
7089
7090 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7091 let Some(row_count) = self.visible_row_count() else {
7092 return;
7093 };
7094
7095 let text_layout_details = &self.text_layout_details(cx);
7096
7097 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7098 s.move_heads_with(|map, head, goal| {
7099 movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
7100 })
7101 })
7102 }
7103
7104 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7105 if self.take_rename(true, cx).is_some() {
7106 return;
7107 }
7108
7109 if self
7110 .context_menu
7111 .write()
7112 .as_mut()
7113 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7114 .unwrap_or(false)
7115 {
7116 return;
7117 }
7118
7119 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7120 cx.propagate();
7121 return;
7122 }
7123
7124 let Some(row_count) = self.visible_row_count() else {
7125 return;
7126 };
7127
7128 let autoscroll = if action.center_cursor {
7129 Autoscroll::center()
7130 } else {
7131 Autoscroll::fit()
7132 };
7133
7134 let text_layout_details = &self.text_layout_details(cx);
7135 self.change_selections(Some(autoscroll), cx, |s| {
7136 let line_mode = s.line_mode;
7137 s.move_with(|map, selection| {
7138 if !selection.is_empty() && !line_mode {
7139 selection.goal = SelectionGoal::None;
7140 }
7141 let (cursor, goal) = movement::down_by_rows(
7142 map,
7143 selection.end,
7144 row_count,
7145 selection.goal,
7146 false,
7147 &text_layout_details,
7148 );
7149 selection.collapse_to(cursor, goal);
7150 });
7151 });
7152 }
7153
7154 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7155 let text_layout_details = &self.text_layout_details(cx);
7156 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7157 s.move_heads_with(|map, head, goal| {
7158 movement::down(map, head, goal, false, &text_layout_details)
7159 })
7160 });
7161 }
7162
7163 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7164 if let Some(context_menu) = self.context_menu.write().as_mut() {
7165 context_menu.select_first(self.project.as_ref(), cx);
7166 }
7167 }
7168
7169 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7170 if let Some(context_menu) = self.context_menu.write().as_mut() {
7171 context_menu.select_prev(self.project.as_ref(), cx);
7172 }
7173 }
7174
7175 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7176 if let Some(context_menu) = self.context_menu.write().as_mut() {
7177 context_menu.select_next(self.project.as_ref(), cx);
7178 }
7179 }
7180
7181 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7182 if let Some(context_menu) = self.context_menu.write().as_mut() {
7183 context_menu.select_last(self.project.as_ref(), cx);
7184 }
7185 }
7186
7187 pub fn move_to_previous_word_start(
7188 &mut self,
7189 _: &MoveToPreviousWordStart,
7190 cx: &mut ViewContext<Self>,
7191 ) {
7192 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7193 s.move_cursors_with(|map, head, _| {
7194 (
7195 movement::previous_word_start(map, head),
7196 SelectionGoal::None,
7197 )
7198 });
7199 })
7200 }
7201
7202 pub fn move_to_previous_subword_start(
7203 &mut self,
7204 _: &MoveToPreviousSubwordStart,
7205 cx: &mut ViewContext<Self>,
7206 ) {
7207 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7208 s.move_cursors_with(|map, head, _| {
7209 (
7210 movement::previous_subword_start(map, head),
7211 SelectionGoal::None,
7212 )
7213 });
7214 })
7215 }
7216
7217 pub fn select_to_previous_word_start(
7218 &mut self,
7219 _: &SelectToPreviousWordStart,
7220 cx: &mut ViewContext<Self>,
7221 ) {
7222 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7223 s.move_heads_with(|map, head, _| {
7224 (
7225 movement::previous_word_start(map, head),
7226 SelectionGoal::None,
7227 )
7228 });
7229 })
7230 }
7231
7232 pub fn select_to_previous_subword_start(
7233 &mut self,
7234 _: &SelectToPreviousSubwordStart,
7235 cx: &mut ViewContext<Self>,
7236 ) {
7237 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7238 s.move_heads_with(|map, head, _| {
7239 (
7240 movement::previous_subword_start(map, head),
7241 SelectionGoal::None,
7242 )
7243 });
7244 })
7245 }
7246
7247 pub fn delete_to_previous_word_start(
7248 &mut self,
7249 _: &DeleteToPreviousWordStart,
7250 cx: &mut ViewContext<Self>,
7251 ) {
7252 self.transact(cx, |this, cx| {
7253 this.select_autoclose_pair(cx);
7254 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7255 let line_mode = s.line_mode;
7256 s.move_with(|map, selection| {
7257 if selection.is_empty() && !line_mode {
7258 let cursor = movement::previous_word_start(map, selection.head());
7259 selection.set_head(cursor, SelectionGoal::None);
7260 }
7261 });
7262 });
7263 this.insert("", cx);
7264 });
7265 }
7266
7267 pub fn delete_to_previous_subword_start(
7268 &mut self,
7269 _: &DeleteToPreviousSubwordStart,
7270 cx: &mut ViewContext<Self>,
7271 ) {
7272 self.transact(cx, |this, cx| {
7273 this.select_autoclose_pair(cx);
7274 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7275 let line_mode = s.line_mode;
7276 s.move_with(|map, selection| {
7277 if selection.is_empty() && !line_mode {
7278 let cursor = movement::previous_subword_start(map, selection.head());
7279 selection.set_head(cursor, SelectionGoal::None);
7280 }
7281 });
7282 });
7283 this.insert("", cx);
7284 });
7285 }
7286
7287 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7288 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7289 s.move_cursors_with(|map, head, _| {
7290 (movement::next_word_end(map, head), SelectionGoal::None)
7291 });
7292 })
7293 }
7294
7295 pub fn move_to_next_subword_end(
7296 &mut self,
7297 _: &MoveToNextSubwordEnd,
7298 cx: &mut ViewContext<Self>,
7299 ) {
7300 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7301 s.move_cursors_with(|map, head, _| {
7302 (movement::next_subword_end(map, head), SelectionGoal::None)
7303 });
7304 })
7305 }
7306
7307 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7308 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7309 s.move_heads_with(|map, head, _| {
7310 (movement::next_word_end(map, head), SelectionGoal::None)
7311 });
7312 })
7313 }
7314
7315 pub fn select_to_next_subword_end(
7316 &mut self,
7317 _: &SelectToNextSubwordEnd,
7318 cx: &mut ViewContext<Self>,
7319 ) {
7320 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7321 s.move_heads_with(|map, head, _| {
7322 (movement::next_subword_end(map, head), SelectionGoal::None)
7323 });
7324 })
7325 }
7326
7327 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
7328 self.transact(cx, |this, cx| {
7329 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7330 let line_mode = s.line_mode;
7331 s.move_with(|map, selection| {
7332 if selection.is_empty() && !line_mode {
7333 let cursor = movement::next_word_end(map, selection.head());
7334 selection.set_head(cursor, SelectionGoal::None);
7335 }
7336 });
7337 });
7338 this.insert("", cx);
7339 });
7340 }
7341
7342 pub fn delete_to_next_subword_end(
7343 &mut self,
7344 _: &DeleteToNextSubwordEnd,
7345 cx: &mut ViewContext<Self>,
7346 ) {
7347 self.transact(cx, |this, cx| {
7348 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7349 s.move_with(|map, selection| {
7350 if selection.is_empty() {
7351 let cursor = movement::next_subword_end(map, selection.head());
7352 selection.set_head(cursor, SelectionGoal::None);
7353 }
7354 });
7355 });
7356 this.insert("", cx);
7357 });
7358 }
7359
7360 pub fn move_to_beginning_of_line(
7361 &mut self,
7362 action: &MoveToBeginningOfLine,
7363 cx: &mut ViewContext<Self>,
7364 ) {
7365 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7366 s.move_cursors_with(|map, head, _| {
7367 (
7368 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7369 SelectionGoal::None,
7370 )
7371 });
7372 })
7373 }
7374
7375 pub fn select_to_beginning_of_line(
7376 &mut self,
7377 action: &SelectToBeginningOfLine,
7378 cx: &mut ViewContext<Self>,
7379 ) {
7380 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7381 s.move_heads_with(|map, head, _| {
7382 (
7383 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7384 SelectionGoal::None,
7385 )
7386 });
7387 });
7388 }
7389
7390 pub fn delete_to_beginning_of_line(
7391 &mut self,
7392 _: &DeleteToBeginningOfLine,
7393 cx: &mut ViewContext<Self>,
7394 ) {
7395 self.transact(cx, |this, cx| {
7396 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7397 s.move_with(|_, selection| {
7398 selection.reversed = true;
7399 });
7400 });
7401
7402 this.select_to_beginning_of_line(
7403 &SelectToBeginningOfLine {
7404 stop_at_soft_wraps: false,
7405 },
7406 cx,
7407 );
7408 this.backspace(&Backspace, cx);
7409 });
7410 }
7411
7412 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7413 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7414 s.move_cursors_with(|map, head, _| {
7415 (
7416 movement::line_end(map, head, action.stop_at_soft_wraps),
7417 SelectionGoal::None,
7418 )
7419 });
7420 })
7421 }
7422
7423 pub fn select_to_end_of_line(
7424 &mut self,
7425 action: &SelectToEndOfLine,
7426 cx: &mut ViewContext<Self>,
7427 ) {
7428 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7429 s.move_heads_with(|map, head, _| {
7430 (
7431 movement::line_end(map, head, action.stop_at_soft_wraps),
7432 SelectionGoal::None,
7433 )
7434 });
7435 })
7436 }
7437
7438 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7439 self.transact(cx, |this, cx| {
7440 this.select_to_end_of_line(
7441 &SelectToEndOfLine {
7442 stop_at_soft_wraps: false,
7443 },
7444 cx,
7445 );
7446 this.delete(&Delete, cx);
7447 });
7448 }
7449
7450 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7451 self.transact(cx, |this, cx| {
7452 this.select_to_end_of_line(
7453 &SelectToEndOfLine {
7454 stop_at_soft_wraps: false,
7455 },
7456 cx,
7457 );
7458 this.cut(&Cut, cx);
7459 });
7460 }
7461
7462 pub fn move_to_start_of_paragraph(
7463 &mut self,
7464 _: &MoveToStartOfParagraph,
7465 cx: &mut ViewContext<Self>,
7466 ) {
7467 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7468 cx.propagate();
7469 return;
7470 }
7471
7472 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7473 s.move_with(|map, selection| {
7474 selection.collapse_to(
7475 movement::start_of_paragraph(map, selection.head(), 1),
7476 SelectionGoal::None,
7477 )
7478 });
7479 })
7480 }
7481
7482 pub fn move_to_end_of_paragraph(
7483 &mut self,
7484 _: &MoveToEndOfParagraph,
7485 cx: &mut ViewContext<Self>,
7486 ) {
7487 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7488 cx.propagate();
7489 return;
7490 }
7491
7492 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7493 s.move_with(|map, selection| {
7494 selection.collapse_to(
7495 movement::end_of_paragraph(map, selection.head(), 1),
7496 SelectionGoal::None,
7497 )
7498 });
7499 })
7500 }
7501
7502 pub fn select_to_start_of_paragraph(
7503 &mut self,
7504 _: &SelectToStartOfParagraph,
7505 cx: &mut ViewContext<Self>,
7506 ) {
7507 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7508 cx.propagate();
7509 return;
7510 }
7511
7512 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7513 s.move_heads_with(|map, head, _| {
7514 (
7515 movement::start_of_paragraph(map, head, 1),
7516 SelectionGoal::None,
7517 )
7518 });
7519 })
7520 }
7521
7522 pub fn select_to_end_of_paragraph(
7523 &mut self,
7524 _: &SelectToEndOfParagraph,
7525 cx: &mut ViewContext<Self>,
7526 ) {
7527 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7528 cx.propagate();
7529 return;
7530 }
7531
7532 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7533 s.move_heads_with(|map, head, _| {
7534 (
7535 movement::end_of_paragraph(map, head, 1),
7536 SelectionGoal::None,
7537 )
7538 });
7539 })
7540 }
7541
7542 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7543 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7544 cx.propagate();
7545 return;
7546 }
7547
7548 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7549 s.select_ranges(vec![0..0]);
7550 });
7551 }
7552
7553 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7554 let mut selection = self.selections.last::<Point>(cx);
7555 selection.set_head(Point::zero(), SelectionGoal::None);
7556
7557 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7558 s.select(vec![selection]);
7559 });
7560 }
7561
7562 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7563 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7564 cx.propagate();
7565 return;
7566 }
7567
7568 let cursor = self.buffer.read(cx).read(cx).len();
7569 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7570 s.select_ranges(vec![cursor..cursor])
7571 });
7572 }
7573
7574 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7575 self.nav_history = nav_history;
7576 }
7577
7578 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7579 self.nav_history.as_ref()
7580 }
7581
7582 fn push_to_nav_history(
7583 &mut self,
7584 cursor_anchor: Anchor,
7585 new_position: Option<Point>,
7586 cx: &mut ViewContext<Self>,
7587 ) {
7588 if let Some(nav_history) = self.nav_history.as_mut() {
7589 let buffer = self.buffer.read(cx).read(cx);
7590 let cursor_position = cursor_anchor.to_point(&buffer);
7591 let scroll_state = self.scroll_manager.anchor();
7592 let scroll_top_row = scroll_state.top_row(&buffer);
7593 drop(buffer);
7594
7595 if let Some(new_position) = new_position {
7596 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7597 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7598 return;
7599 }
7600 }
7601
7602 nav_history.push(
7603 Some(NavigationData {
7604 cursor_anchor,
7605 cursor_position,
7606 scroll_anchor: scroll_state,
7607 scroll_top_row,
7608 }),
7609 cx,
7610 );
7611 }
7612 }
7613
7614 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7615 let buffer = self.buffer.read(cx).snapshot(cx);
7616 let mut selection = self.selections.first::<usize>(cx);
7617 selection.set_head(buffer.len(), SelectionGoal::None);
7618 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7619 s.select(vec![selection]);
7620 });
7621 }
7622
7623 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7624 let end = self.buffer.read(cx).read(cx).len();
7625 self.change_selections(None, cx, |s| {
7626 s.select_ranges(vec![0..end]);
7627 });
7628 }
7629
7630 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7631 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7632 let mut selections = self.selections.all::<Point>(cx);
7633 let max_point = display_map.buffer_snapshot.max_point();
7634 for selection in &mut selections {
7635 let rows = selection.spanned_rows(true, &display_map);
7636 selection.start = Point::new(rows.start.0, 0);
7637 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7638 selection.reversed = false;
7639 }
7640 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7641 s.select(selections);
7642 });
7643 }
7644
7645 pub fn split_selection_into_lines(
7646 &mut self,
7647 _: &SplitSelectionIntoLines,
7648 cx: &mut ViewContext<Self>,
7649 ) {
7650 let mut to_unfold = Vec::new();
7651 let mut new_selection_ranges = Vec::new();
7652 {
7653 let selections = self.selections.all::<Point>(cx);
7654 let buffer = self.buffer.read(cx).read(cx);
7655 for selection in selections {
7656 for row in selection.start.row..selection.end.row {
7657 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7658 new_selection_ranges.push(cursor..cursor);
7659 }
7660 new_selection_ranges.push(selection.end..selection.end);
7661 to_unfold.push(selection.start..selection.end);
7662 }
7663 }
7664 self.unfold_ranges(to_unfold, true, true, cx);
7665 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7666 s.select_ranges(new_selection_ranges);
7667 });
7668 }
7669
7670 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7671 self.add_selection(true, cx);
7672 }
7673
7674 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7675 self.add_selection(false, cx);
7676 }
7677
7678 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7679 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7680 let mut selections = self.selections.all::<Point>(cx);
7681 let text_layout_details = self.text_layout_details(cx);
7682 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7683 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7684 let range = oldest_selection.display_range(&display_map).sorted();
7685
7686 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7687 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7688 let positions = start_x.min(end_x)..start_x.max(end_x);
7689
7690 selections.clear();
7691 let mut stack = Vec::new();
7692 for row in range.start.row().0..=range.end.row().0 {
7693 if let Some(selection) = self.selections.build_columnar_selection(
7694 &display_map,
7695 DisplayRow(row),
7696 &positions,
7697 oldest_selection.reversed,
7698 &text_layout_details,
7699 ) {
7700 stack.push(selection.id);
7701 selections.push(selection);
7702 }
7703 }
7704
7705 if above {
7706 stack.reverse();
7707 }
7708
7709 AddSelectionsState { above, stack }
7710 });
7711
7712 let last_added_selection = *state.stack.last().unwrap();
7713 let mut new_selections = Vec::new();
7714 if above == state.above {
7715 let end_row = if above {
7716 DisplayRow(0)
7717 } else {
7718 display_map.max_point().row()
7719 };
7720
7721 'outer: for selection in selections {
7722 if selection.id == last_added_selection {
7723 let range = selection.display_range(&display_map).sorted();
7724 debug_assert_eq!(range.start.row(), range.end.row());
7725 let mut row = range.start.row();
7726 let positions =
7727 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7728 px(start)..px(end)
7729 } else {
7730 let start_x =
7731 display_map.x_for_display_point(range.start, &text_layout_details);
7732 let end_x =
7733 display_map.x_for_display_point(range.end, &text_layout_details);
7734 start_x.min(end_x)..start_x.max(end_x)
7735 };
7736
7737 while row != end_row {
7738 if above {
7739 row.0 -= 1;
7740 } else {
7741 row.0 += 1;
7742 }
7743
7744 if let Some(new_selection) = self.selections.build_columnar_selection(
7745 &display_map,
7746 row,
7747 &positions,
7748 selection.reversed,
7749 &text_layout_details,
7750 ) {
7751 state.stack.push(new_selection.id);
7752 if above {
7753 new_selections.push(new_selection);
7754 new_selections.push(selection);
7755 } else {
7756 new_selections.push(selection);
7757 new_selections.push(new_selection);
7758 }
7759
7760 continue 'outer;
7761 }
7762 }
7763 }
7764
7765 new_selections.push(selection);
7766 }
7767 } else {
7768 new_selections = selections;
7769 new_selections.retain(|s| s.id != last_added_selection);
7770 state.stack.pop();
7771 }
7772
7773 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7774 s.select(new_selections);
7775 });
7776 if state.stack.len() > 1 {
7777 self.add_selections_state = Some(state);
7778 }
7779 }
7780
7781 pub fn select_next_match_internal(
7782 &mut self,
7783 display_map: &DisplaySnapshot,
7784 replace_newest: bool,
7785 autoscroll: Option<Autoscroll>,
7786 cx: &mut ViewContext<Self>,
7787 ) -> Result<()> {
7788 fn select_next_match_ranges(
7789 this: &mut Editor,
7790 range: Range<usize>,
7791 replace_newest: bool,
7792 auto_scroll: Option<Autoscroll>,
7793 cx: &mut ViewContext<Editor>,
7794 ) {
7795 this.unfold_ranges([range.clone()], false, true, cx);
7796 this.change_selections(auto_scroll, cx, |s| {
7797 if replace_newest {
7798 s.delete(s.newest_anchor().id);
7799 }
7800 s.insert_range(range.clone());
7801 });
7802 }
7803
7804 let buffer = &display_map.buffer_snapshot;
7805 let mut selections = self.selections.all::<usize>(cx);
7806 if let Some(mut select_next_state) = self.select_next_state.take() {
7807 let query = &select_next_state.query;
7808 if !select_next_state.done {
7809 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7810 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7811 let mut next_selected_range = None;
7812
7813 let bytes_after_last_selection =
7814 buffer.bytes_in_range(last_selection.end..buffer.len());
7815 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7816 let query_matches = query
7817 .stream_find_iter(bytes_after_last_selection)
7818 .map(|result| (last_selection.end, result))
7819 .chain(
7820 query
7821 .stream_find_iter(bytes_before_first_selection)
7822 .map(|result| (0, result)),
7823 );
7824
7825 for (start_offset, query_match) in query_matches {
7826 let query_match = query_match.unwrap(); // can only fail due to I/O
7827 let offset_range =
7828 start_offset + query_match.start()..start_offset + query_match.end();
7829 let display_range = offset_range.start.to_display_point(&display_map)
7830 ..offset_range.end.to_display_point(&display_map);
7831
7832 if !select_next_state.wordwise
7833 || (!movement::is_inside_word(&display_map, display_range.start)
7834 && !movement::is_inside_word(&display_map, display_range.end))
7835 {
7836 // TODO: This is n^2, because we might check all the selections
7837 if !selections
7838 .iter()
7839 .any(|selection| selection.range().overlaps(&offset_range))
7840 {
7841 next_selected_range = Some(offset_range);
7842 break;
7843 }
7844 }
7845 }
7846
7847 if let Some(next_selected_range) = next_selected_range {
7848 select_next_match_ranges(
7849 self,
7850 next_selected_range,
7851 replace_newest,
7852 autoscroll,
7853 cx,
7854 );
7855 } else {
7856 select_next_state.done = true;
7857 }
7858 }
7859
7860 self.select_next_state = Some(select_next_state);
7861 } else {
7862 let mut only_carets = true;
7863 let mut same_text_selected = true;
7864 let mut selected_text = None;
7865
7866 let mut selections_iter = selections.iter().peekable();
7867 while let Some(selection) = selections_iter.next() {
7868 if selection.start != selection.end {
7869 only_carets = false;
7870 }
7871
7872 if same_text_selected {
7873 if selected_text.is_none() {
7874 selected_text =
7875 Some(buffer.text_for_range(selection.range()).collect::<String>());
7876 }
7877
7878 if let Some(next_selection) = selections_iter.peek() {
7879 if next_selection.range().len() == selection.range().len() {
7880 let next_selected_text = buffer
7881 .text_for_range(next_selection.range())
7882 .collect::<String>();
7883 if Some(next_selected_text) != selected_text {
7884 same_text_selected = false;
7885 selected_text = None;
7886 }
7887 } else {
7888 same_text_selected = false;
7889 selected_text = None;
7890 }
7891 }
7892 }
7893 }
7894
7895 if only_carets {
7896 for selection in &mut selections {
7897 let word_range = movement::surrounding_word(
7898 &display_map,
7899 selection.start.to_display_point(&display_map),
7900 );
7901 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7902 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7903 selection.goal = SelectionGoal::None;
7904 selection.reversed = false;
7905 select_next_match_ranges(
7906 self,
7907 selection.start..selection.end,
7908 replace_newest,
7909 autoscroll,
7910 cx,
7911 );
7912 }
7913
7914 if selections.len() == 1 {
7915 let selection = selections
7916 .last()
7917 .expect("ensured that there's only one selection");
7918 let query = buffer
7919 .text_for_range(selection.start..selection.end)
7920 .collect::<String>();
7921 let is_empty = query.is_empty();
7922 let select_state = SelectNextState {
7923 query: AhoCorasick::new(&[query])?,
7924 wordwise: true,
7925 done: is_empty,
7926 };
7927 self.select_next_state = Some(select_state);
7928 } else {
7929 self.select_next_state = None;
7930 }
7931 } else if let Some(selected_text) = selected_text {
7932 self.select_next_state = Some(SelectNextState {
7933 query: AhoCorasick::new(&[selected_text])?,
7934 wordwise: false,
7935 done: false,
7936 });
7937 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
7938 }
7939 }
7940 Ok(())
7941 }
7942
7943 pub fn select_all_matches(
7944 &mut self,
7945 _action: &SelectAllMatches,
7946 cx: &mut ViewContext<Self>,
7947 ) -> Result<()> {
7948 self.push_to_selection_history();
7949 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7950
7951 self.select_next_match_internal(&display_map, false, None, cx)?;
7952 let Some(select_next_state) = self.select_next_state.as_mut() else {
7953 return Ok(());
7954 };
7955 if select_next_state.done {
7956 return Ok(());
7957 }
7958
7959 let mut new_selections = self.selections.all::<usize>(cx);
7960
7961 let buffer = &display_map.buffer_snapshot;
7962 let query_matches = select_next_state
7963 .query
7964 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
7965
7966 for query_match in query_matches {
7967 let query_match = query_match.unwrap(); // can only fail due to I/O
7968 let offset_range = query_match.start()..query_match.end();
7969 let display_range = offset_range.start.to_display_point(&display_map)
7970 ..offset_range.end.to_display_point(&display_map);
7971
7972 if !select_next_state.wordwise
7973 || (!movement::is_inside_word(&display_map, display_range.start)
7974 && !movement::is_inside_word(&display_map, display_range.end))
7975 {
7976 self.selections.change_with(cx, |selections| {
7977 new_selections.push(Selection {
7978 id: selections.new_selection_id(),
7979 start: offset_range.start,
7980 end: offset_range.end,
7981 reversed: false,
7982 goal: SelectionGoal::None,
7983 });
7984 });
7985 }
7986 }
7987
7988 new_selections.sort_by_key(|selection| selection.start);
7989 let mut ix = 0;
7990 while ix + 1 < new_selections.len() {
7991 let current_selection = &new_selections[ix];
7992 let next_selection = &new_selections[ix + 1];
7993 if current_selection.range().overlaps(&next_selection.range()) {
7994 if current_selection.id < next_selection.id {
7995 new_selections.remove(ix + 1);
7996 } else {
7997 new_selections.remove(ix);
7998 }
7999 } else {
8000 ix += 1;
8001 }
8002 }
8003
8004 select_next_state.done = true;
8005 self.unfold_ranges(
8006 new_selections.iter().map(|selection| selection.range()),
8007 false,
8008 false,
8009 cx,
8010 );
8011 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8012 selections.select(new_selections)
8013 });
8014
8015 Ok(())
8016 }
8017
8018 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8019 self.push_to_selection_history();
8020 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8021 self.select_next_match_internal(
8022 &display_map,
8023 action.replace_newest,
8024 Some(Autoscroll::newest()),
8025 cx,
8026 )?;
8027 Ok(())
8028 }
8029
8030 pub fn select_previous(
8031 &mut self,
8032 action: &SelectPrevious,
8033 cx: &mut ViewContext<Self>,
8034 ) -> Result<()> {
8035 self.push_to_selection_history();
8036 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8037 let buffer = &display_map.buffer_snapshot;
8038 let mut selections = self.selections.all::<usize>(cx);
8039 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8040 let query = &select_prev_state.query;
8041 if !select_prev_state.done {
8042 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8043 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8044 let mut next_selected_range = None;
8045 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8046 let bytes_before_last_selection =
8047 buffer.reversed_bytes_in_range(0..last_selection.start);
8048 let bytes_after_first_selection =
8049 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8050 let query_matches = query
8051 .stream_find_iter(bytes_before_last_selection)
8052 .map(|result| (last_selection.start, result))
8053 .chain(
8054 query
8055 .stream_find_iter(bytes_after_first_selection)
8056 .map(|result| (buffer.len(), result)),
8057 );
8058 for (end_offset, query_match) in query_matches {
8059 let query_match = query_match.unwrap(); // can only fail due to I/O
8060 let offset_range =
8061 end_offset - query_match.end()..end_offset - query_match.start();
8062 let display_range = offset_range.start.to_display_point(&display_map)
8063 ..offset_range.end.to_display_point(&display_map);
8064
8065 if !select_prev_state.wordwise
8066 || (!movement::is_inside_word(&display_map, display_range.start)
8067 && !movement::is_inside_word(&display_map, display_range.end))
8068 {
8069 next_selected_range = Some(offset_range);
8070 break;
8071 }
8072 }
8073
8074 if let Some(next_selected_range) = next_selected_range {
8075 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8076 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8077 if action.replace_newest {
8078 s.delete(s.newest_anchor().id);
8079 }
8080 s.insert_range(next_selected_range);
8081 });
8082 } else {
8083 select_prev_state.done = true;
8084 }
8085 }
8086
8087 self.select_prev_state = Some(select_prev_state);
8088 } else {
8089 let mut only_carets = true;
8090 let mut same_text_selected = true;
8091 let mut selected_text = None;
8092
8093 let mut selections_iter = selections.iter().peekable();
8094 while let Some(selection) = selections_iter.next() {
8095 if selection.start != selection.end {
8096 only_carets = false;
8097 }
8098
8099 if same_text_selected {
8100 if selected_text.is_none() {
8101 selected_text =
8102 Some(buffer.text_for_range(selection.range()).collect::<String>());
8103 }
8104
8105 if let Some(next_selection) = selections_iter.peek() {
8106 if next_selection.range().len() == selection.range().len() {
8107 let next_selected_text = buffer
8108 .text_for_range(next_selection.range())
8109 .collect::<String>();
8110 if Some(next_selected_text) != selected_text {
8111 same_text_selected = false;
8112 selected_text = None;
8113 }
8114 } else {
8115 same_text_selected = false;
8116 selected_text = None;
8117 }
8118 }
8119 }
8120 }
8121
8122 if only_carets {
8123 for selection in &mut selections {
8124 let word_range = movement::surrounding_word(
8125 &display_map,
8126 selection.start.to_display_point(&display_map),
8127 );
8128 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8129 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8130 selection.goal = SelectionGoal::None;
8131 selection.reversed = false;
8132 }
8133 if selections.len() == 1 {
8134 let selection = selections
8135 .last()
8136 .expect("ensured that there's only one selection");
8137 let query = buffer
8138 .text_for_range(selection.start..selection.end)
8139 .collect::<String>();
8140 let is_empty = query.is_empty();
8141 let select_state = SelectNextState {
8142 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8143 wordwise: true,
8144 done: is_empty,
8145 };
8146 self.select_prev_state = Some(select_state);
8147 } else {
8148 self.select_prev_state = None;
8149 }
8150
8151 self.unfold_ranges(
8152 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8153 false,
8154 true,
8155 cx,
8156 );
8157 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8158 s.select(selections);
8159 });
8160 } else if let Some(selected_text) = selected_text {
8161 self.select_prev_state = Some(SelectNextState {
8162 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8163 wordwise: false,
8164 done: false,
8165 });
8166 self.select_previous(action, cx)?;
8167 }
8168 }
8169 Ok(())
8170 }
8171
8172 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8173 let text_layout_details = &self.text_layout_details(cx);
8174 self.transact(cx, |this, cx| {
8175 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8176 let mut edits = Vec::new();
8177 let mut selection_edit_ranges = Vec::new();
8178 let mut last_toggled_row = None;
8179 let snapshot = this.buffer.read(cx).read(cx);
8180 let empty_str: Arc<str> = Arc::default();
8181 let mut suffixes_inserted = Vec::new();
8182
8183 fn comment_prefix_range(
8184 snapshot: &MultiBufferSnapshot,
8185 row: MultiBufferRow,
8186 comment_prefix: &str,
8187 comment_prefix_whitespace: &str,
8188 ) -> Range<Point> {
8189 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8190
8191 let mut line_bytes = snapshot
8192 .bytes_in_range(start..snapshot.max_point())
8193 .flatten()
8194 .copied();
8195
8196 // If this line currently begins with the line comment prefix, then record
8197 // the range containing the prefix.
8198 if line_bytes
8199 .by_ref()
8200 .take(comment_prefix.len())
8201 .eq(comment_prefix.bytes())
8202 {
8203 // Include any whitespace that matches the comment prefix.
8204 let matching_whitespace_len = line_bytes
8205 .zip(comment_prefix_whitespace.bytes())
8206 .take_while(|(a, b)| a == b)
8207 .count() as u32;
8208 let end = Point::new(
8209 start.row,
8210 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8211 );
8212 start..end
8213 } else {
8214 start..start
8215 }
8216 }
8217
8218 fn comment_suffix_range(
8219 snapshot: &MultiBufferSnapshot,
8220 row: MultiBufferRow,
8221 comment_suffix: &str,
8222 comment_suffix_has_leading_space: bool,
8223 ) -> Range<Point> {
8224 let end = Point::new(row.0, snapshot.line_len(row));
8225 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8226
8227 let mut line_end_bytes = snapshot
8228 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8229 .flatten()
8230 .copied();
8231
8232 let leading_space_len = if suffix_start_column > 0
8233 && line_end_bytes.next() == Some(b' ')
8234 && comment_suffix_has_leading_space
8235 {
8236 1
8237 } else {
8238 0
8239 };
8240
8241 // If this line currently begins with the line comment prefix, then record
8242 // the range containing the prefix.
8243 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8244 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8245 start..end
8246 } else {
8247 end..end
8248 }
8249 }
8250
8251 // TODO: Handle selections that cross excerpts
8252 for selection in &mut selections {
8253 let start_column = snapshot
8254 .indent_size_for_line(MultiBufferRow(selection.start.row))
8255 .len;
8256 let language = if let Some(language) =
8257 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8258 {
8259 language
8260 } else {
8261 continue;
8262 };
8263
8264 selection_edit_ranges.clear();
8265
8266 // If multiple selections contain a given row, avoid processing that
8267 // row more than once.
8268 let mut start_row = MultiBufferRow(selection.start.row);
8269 if last_toggled_row == Some(start_row) {
8270 start_row = start_row.next_row();
8271 }
8272 let end_row =
8273 if selection.end.row > selection.start.row && selection.end.column == 0 {
8274 MultiBufferRow(selection.end.row - 1)
8275 } else {
8276 MultiBufferRow(selection.end.row)
8277 };
8278 last_toggled_row = Some(end_row);
8279
8280 if start_row > end_row {
8281 continue;
8282 }
8283
8284 // If the language has line comments, toggle those.
8285 let full_comment_prefixes = language.line_comment_prefixes();
8286 if !full_comment_prefixes.is_empty() {
8287 let first_prefix = full_comment_prefixes
8288 .first()
8289 .expect("prefixes is non-empty");
8290 let prefix_trimmed_lengths = full_comment_prefixes
8291 .iter()
8292 .map(|p| p.trim_end_matches(' ').len())
8293 .collect::<SmallVec<[usize; 4]>>();
8294
8295 let mut all_selection_lines_are_comments = true;
8296
8297 for row in start_row.0..=end_row.0 {
8298 let row = MultiBufferRow(row);
8299 if start_row < end_row && snapshot.is_line_blank(row) {
8300 continue;
8301 }
8302
8303 let prefix_range = full_comment_prefixes
8304 .iter()
8305 .zip(prefix_trimmed_lengths.iter().copied())
8306 .map(|(prefix, trimmed_prefix_len)| {
8307 comment_prefix_range(
8308 snapshot.deref(),
8309 row,
8310 &prefix[..trimmed_prefix_len],
8311 &prefix[trimmed_prefix_len..],
8312 )
8313 })
8314 .max_by_key(|range| range.end.column - range.start.column)
8315 .expect("prefixes is non-empty");
8316
8317 if prefix_range.is_empty() {
8318 all_selection_lines_are_comments = false;
8319 }
8320
8321 selection_edit_ranges.push(prefix_range);
8322 }
8323
8324 if all_selection_lines_are_comments {
8325 edits.extend(
8326 selection_edit_ranges
8327 .iter()
8328 .cloned()
8329 .map(|range| (range, empty_str.clone())),
8330 );
8331 } else {
8332 let min_column = selection_edit_ranges
8333 .iter()
8334 .map(|range| range.start.column)
8335 .min()
8336 .unwrap_or(0);
8337 edits.extend(selection_edit_ranges.iter().map(|range| {
8338 let position = Point::new(range.start.row, min_column);
8339 (position..position, first_prefix.clone())
8340 }));
8341 }
8342 } else if let Some((full_comment_prefix, comment_suffix)) =
8343 language.block_comment_delimiters()
8344 {
8345 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8346 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8347 let prefix_range = comment_prefix_range(
8348 snapshot.deref(),
8349 start_row,
8350 comment_prefix,
8351 comment_prefix_whitespace,
8352 );
8353 let suffix_range = comment_suffix_range(
8354 snapshot.deref(),
8355 end_row,
8356 comment_suffix.trim_start_matches(' '),
8357 comment_suffix.starts_with(' '),
8358 );
8359
8360 if prefix_range.is_empty() || suffix_range.is_empty() {
8361 edits.push((
8362 prefix_range.start..prefix_range.start,
8363 full_comment_prefix.clone(),
8364 ));
8365 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8366 suffixes_inserted.push((end_row, comment_suffix.len()));
8367 } else {
8368 edits.push((prefix_range, empty_str.clone()));
8369 edits.push((suffix_range, empty_str.clone()));
8370 }
8371 } else {
8372 continue;
8373 }
8374 }
8375
8376 drop(snapshot);
8377 this.buffer.update(cx, |buffer, cx| {
8378 buffer.edit(edits, None, cx);
8379 });
8380
8381 // Adjust selections so that they end before any comment suffixes that
8382 // were inserted.
8383 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8384 let mut selections = this.selections.all::<Point>(cx);
8385 let snapshot = this.buffer.read(cx).read(cx);
8386 for selection in &mut selections {
8387 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8388 match row.cmp(&MultiBufferRow(selection.end.row)) {
8389 Ordering::Less => {
8390 suffixes_inserted.next();
8391 continue;
8392 }
8393 Ordering::Greater => break,
8394 Ordering::Equal => {
8395 if selection.end.column == snapshot.line_len(row) {
8396 if selection.is_empty() {
8397 selection.start.column -= suffix_len as u32;
8398 }
8399 selection.end.column -= suffix_len as u32;
8400 }
8401 break;
8402 }
8403 }
8404 }
8405 }
8406
8407 drop(snapshot);
8408 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8409
8410 let selections = this.selections.all::<Point>(cx);
8411 let selections_on_single_row = selections.windows(2).all(|selections| {
8412 selections[0].start.row == selections[1].start.row
8413 && selections[0].end.row == selections[1].end.row
8414 && selections[0].start.row == selections[0].end.row
8415 });
8416 let selections_selecting = selections
8417 .iter()
8418 .any(|selection| selection.start != selection.end);
8419 let advance_downwards = action.advance_downwards
8420 && selections_on_single_row
8421 && !selections_selecting
8422 && !matches!(this.mode, EditorMode::SingleLine { .. });
8423
8424 if advance_downwards {
8425 let snapshot = this.buffer.read(cx).snapshot(cx);
8426
8427 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8428 s.move_cursors_with(|display_snapshot, display_point, _| {
8429 let mut point = display_point.to_point(display_snapshot);
8430 point.row += 1;
8431 point = snapshot.clip_point(point, Bias::Left);
8432 let display_point = point.to_display_point(display_snapshot);
8433 let goal = SelectionGoal::HorizontalPosition(
8434 display_snapshot
8435 .x_for_display_point(display_point, &text_layout_details)
8436 .into(),
8437 );
8438 (display_point, goal)
8439 })
8440 });
8441 }
8442 });
8443 }
8444
8445 pub fn select_enclosing_symbol(
8446 &mut self,
8447 _: &SelectEnclosingSymbol,
8448 cx: &mut ViewContext<Self>,
8449 ) {
8450 let buffer = self.buffer.read(cx).snapshot(cx);
8451 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8452
8453 fn update_selection(
8454 selection: &Selection<usize>,
8455 buffer_snap: &MultiBufferSnapshot,
8456 ) -> Option<Selection<usize>> {
8457 let cursor = selection.head();
8458 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8459 for symbol in symbols.iter().rev() {
8460 let start = symbol.range.start.to_offset(&buffer_snap);
8461 let end = symbol.range.end.to_offset(&buffer_snap);
8462 let new_range = start..end;
8463 if start < selection.start || end > selection.end {
8464 return Some(Selection {
8465 id: selection.id,
8466 start: new_range.start,
8467 end: new_range.end,
8468 goal: SelectionGoal::None,
8469 reversed: selection.reversed,
8470 });
8471 }
8472 }
8473 None
8474 }
8475
8476 let mut selected_larger_symbol = false;
8477 let new_selections = old_selections
8478 .iter()
8479 .map(|selection| match update_selection(selection, &buffer) {
8480 Some(new_selection) => {
8481 if new_selection.range() != selection.range() {
8482 selected_larger_symbol = true;
8483 }
8484 new_selection
8485 }
8486 None => selection.clone(),
8487 })
8488 .collect::<Vec<_>>();
8489
8490 if selected_larger_symbol {
8491 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8492 s.select(new_selections);
8493 });
8494 }
8495 }
8496
8497 pub fn select_larger_syntax_node(
8498 &mut self,
8499 _: &SelectLargerSyntaxNode,
8500 cx: &mut ViewContext<Self>,
8501 ) {
8502 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8503 let buffer = self.buffer.read(cx).snapshot(cx);
8504 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8505
8506 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8507 let mut selected_larger_node = false;
8508 let new_selections = old_selections
8509 .iter()
8510 .map(|selection| {
8511 let old_range = selection.start..selection.end;
8512 let mut new_range = old_range.clone();
8513 while let Some(containing_range) =
8514 buffer.range_for_syntax_ancestor(new_range.clone())
8515 {
8516 new_range = containing_range;
8517 if !display_map.intersects_fold(new_range.start)
8518 && !display_map.intersects_fold(new_range.end)
8519 {
8520 break;
8521 }
8522 }
8523
8524 selected_larger_node |= new_range != old_range;
8525 Selection {
8526 id: selection.id,
8527 start: new_range.start,
8528 end: new_range.end,
8529 goal: SelectionGoal::None,
8530 reversed: selection.reversed,
8531 }
8532 })
8533 .collect::<Vec<_>>();
8534
8535 if selected_larger_node {
8536 stack.push(old_selections);
8537 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8538 s.select(new_selections);
8539 });
8540 }
8541 self.select_larger_syntax_node_stack = stack;
8542 }
8543
8544 pub fn select_smaller_syntax_node(
8545 &mut self,
8546 _: &SelectSmallerSyntaxNode,
8547 cx: &mut ViewContext<Self>,
8548 ) {
8549 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8550 if let Some(selections) = stack.pop() {
8551 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8552 s.select(selections.to_vec());
8553 });
8554 }
8555 self.select_larger_syntax_node_stack = stack;
8556 }
8557
8558 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8559 if !EditorSettings::get_global(cx).gutter.runnables {
8560 self.clear_tasks();
8561 return Task::ready(());
8562 }
8563 let project = self.project.clone();
8564 cx.spawn(|this, mut cx| async move {
8565 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8566 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8567 }) else {
8568 return;
8569 };
8570
8571 let Some(project) = project else {
8572 return;
8573 };
8574
8575 let hide_runnables = project
8576 .update(&mut cx, |project, cx| {
8577 // Do not display any test indicators in non-dev server remote projects.
8578 project.is_remote() && project.ssh_connection_string(cx).is_none()
8579 })
8580 .unwrap_or(true);
8581 if hide_runnables {
8582 return;
8583 }
8584 let new_rows =
8585 cx.background_executor()
8586 .spawn({
8587 let snapshot = display_snapshot.clone();
8588 async move {
8589 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8590 }
8591 })
8592 .await;
8593 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8594
8595 this.update(&mut cx, |this, _| {
8596 this.clear_tasks();
8597 for (key, value) in rows {
8598 this.insert_tasks(key, value);
8599 }
8600 })
8601 .ok();
8602 })
8603 }
8604 fn fetch_runnable_ranges(
8605 snapshot: &DisplaySnapshot,
8606 range: Range<Anchor>,
8607 ) -> Vec<language::RunnableRange> {
8608 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8609 }
8610
8611 fn runnable_rows(
8612 project: Model<Project>,
8613 snapshot: DisplaySnapshot,
8614 runnable_ranges: Vec<RunnableRange>,
8615 mut cx: AsyncWindowContext,
8616 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8617 runnable_ranges
8618 .into_iter()
8619 .filter_map(|mut runnable| {
8620 let tasks = cx
8621 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8622 .ok()?;
8623 if tasks.is_empty() {
8624 return None;
8625 }
8626
8627 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8628
8629 let row = snapshot
8630 .buffer_snapshot
8631 .buffer_line_for_row(MultiBufferRow(point.row))?
8632 .1
8633 .start
8634 .row;
8635
8636 let context_range =
8637 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8638 Some((
8639 (runnable.buffer_id, row),
8640 RunnableTasks {
8641 templates: tasks,
8642 offset: MultiBufferOffset(runnable.run_range.start),
8643 context_range,
8644 column: point.column,
8645 extra_variables: runnable.extra_captures,
8646 },
8647 ))
8648 })
8649 .collect()
8650 }
8651
8652 fn templates_with_tags(
8653 project: &Model<Project>,
8654 runnable: &mut Runnable,
8655 cx: &WindowContext<'_>,
8656 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8657 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8658 let (worktree_id, file) = project
8659 .buffer_for_id(runnable.buffer, cx)
8660 .and_then(|buffer| buffer.read(cx).file())
8661 .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
8662 .unzip();
8663
8664 (project.task_inventory().clone(), worktree_id, file)
8665 });
8666
8667 let inventory = inventory.read(cx);
8668 let tags = mem::take(&mut runnable.tags);
8669 let mut tags: Vec<_> = tags
8670 .into_iter()
8671 .flat_map(|tag| {
8672 let tag = tag.0.clone();
8673 inventory
8674 .list_tasks(
8675 file.clone(),
8676 Some(runnable.language.clone()),
8677 worktree_id,
8678 cx,
8679 )
8680 .into_iter()
8681 .filter(move |(_, template)| {
8682 template.tags.iter().any(|source_tag| source_tag == &tag)
8683 })
8684 })
8685 .sorted_by_key(|(kind, _)| kind.to_owned())
8686 .collect();
8687 if let Some((leading_tag_source, _)) = tags.first() {
8688 // Strongest source wins; if we have worktree tag binding, prefer that to
8689 // global and language bindings;
8690 // if we have a global binding, prefer that to language binding.
8691 let first_mismatch = tags
8692 .iter()
8693 .position(|(tag_source, _)| tag_source != leading_tag_source);
8694 if let Some(index) = first_mismatch {
8695 tags.truncate(index);
8696 }
8697 }
8698
8699 tags
8700 }
8701
8702 pub fn move_to_enclosing_bracket(
8703 &mut self,
8704 _: &MoveToEnclosingBracket,
8705 cx: &mut ViewContext<Self>,
8706 ) {
8707 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8708 s.move_offsets_with(|snapshot, selection| {
8709 let Some(enclosing_bracket_ranges) =
8710 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8711 else {
8712 return;
8713 };
8714
8715 let mut best_length = usize::MAX;
8716 let mut best_inside = false;
8717 let mut best_in_bracket_range = false;
8718 let mut best_destination = None;
8719 for (open, close) in enclosing_bracket_ranges {
8720 let close = close.to_inclusive();
8721 let length = close.end() - open.start;
8722 let inside = selection.start >= open.end && selection.end <= *close.start();
8723 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8724 || close.contains(&selection.head());
8725
8726 // If best is next to a bracket and current isn't, skip
8727 if !in_bracket_range && best_in_bracket_range {
8728 continue;
8729 }
8730
8731 // Prefer smaller lengths unless best is inside and current isn't
8732 if length > best_length && (best_inside || !inside) {
8733 continue;
8734 }
8735
8736 best_length = length;
8737 best_inside = inside;
8738 best_in_bracket_range = in_bracket_range;
8739 best_destination = Some(
8740 if close.contains(&selection.start) && close.contains(&selection.end) {
8741 if inside {
8742 open.end
8743 } else {
8744 open.start
8745 }
8746 } else {
8747 if inside {
8748 *close.start()
8749 } else {
8750 *close.end()
8751 }
8752 },
8753 );
8754 }
8755
8756 if let Some(destination) = best_destination {
8757 selection.collapse_to(destination, SelectionGoal::None);
8758 }
8759 })
8760 });
8761 }
8762
8763 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8764 self.end_selection(cx);
8765 self.selection_history.mode = SelectionHistoryMode::Undoing;
8766 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8767 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8768 self.select_next_state = entry.select_next_state;
8769 self.select_prev_state = entry.select_prev_state;
8770 self.add_selections_state = entry.add_selections_state;
8771 self.request_autoscroll(Autoscroll::newest(), cx);
8772 }
8773 self.selection_history.mode = SelectionHistoryMode::Normal;
8774 }
8775
8776 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8777 self.end_selection(cx);
8778 self.selection_history.mode = SelectionHistoryMode::Redoing;
8779 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8780 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8781 self.select_next_state = entry.select_next_state;
8782 self.select_prev_state = entry.select_prev_state;
8783 self.add_selections_state = entry.add_selections_state;
8784 self.request_autoscroll(Autoscroll::newest(), cx);
8785 }
8786 self.selection_history.mode = SelectionHistoryMode::Normal;
8787 }
8788
8789 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8790 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8791 }
8792
8793 pub fn expand_excerpts_down(
8794 &mut self,
8795 action: &ExpandExcerptsDown,
8796 cx: &mut ViewContext<Self>,
8797 ) {
8798 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8799 }
8800
8801 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8802 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8803 }
8804
8805 pub fn expand_excerpts_for_direction(
8806 &mut self,
8807 lines: u32,
8808 direction: ExpandExcerptDirection,
8809 cx: &mut ViewContext<Self>,
8810 ) {
8811 let selections = self.selections.disjoint_anchors();
8812
8813 let lines = if lines == 0 {
8814 EditorSettings::get_global(cx).expand_excerpt_lines
8815 } else {
8816 lines
8817 };
8818
8819 self.buffer.update(cx, |buffer, cx| {
8820 buffer.expand_excerpts(
8821 selections
8822 .into_iter()
8823 .map(|selection| selection.head().excerpt_id)
8824 .dedup(),
8825 lines,
8826 direction,
8827 cx,
8828 )
8829 })
8830 }
8831
8832 pub fn expand_excerpt(
8833 &mut self,
8834 excerpt: ExcerptId,
8835 direction: ExpandExcerptDirection,
8836 cx: &mut ViewContext<Self>,
8837 ) {
8838 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8839 self.buffer.update(cx, |buffer, cx| {
8840 buffer.expand_excerpts([excerpt], lines, direction, cx)
8841 })
8842 }
8843
8844 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8845 self.go_to_diagnostic_impl(Direction::Next, cx)
8846 }
8847
8848 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8849 self.go_to_diagnostic_impl(Direction::Prev, cx)
8850 }
8851
8852 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8853 let buffer = self.buffer.read(cx).snapshot(cx);
8854 let selection = self.selections.newest::<usize>(cx);
8855
8856 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8857 if direction == Direction::Next {
8858 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8859 let (group_id, jump_to) = popover.activation_info();
8860 if self.activate_diagnostics(group_id, cx) {
8861 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8862 let mut new_selection = s.newest_anchor().clone();
8863 new_selection.collapse_to(jump_to, SelectionGoal::None);
8864 s.select_anchors(vec![new_selection.clone()]);
8865 });
8866 }
8867 return;
8868 }
8869 }
8870
8871 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8872 active_diagnostics
8873 .primary_range
8874 .to_offset(&buffer)
8875 .to_inclusive()
8876 });
8877 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8878 if active_primary_range.contains(&selection.head()) {
8879 *active_primary_range.start()
8880 } else {
8881 selection.head()
8882 }
8883 } else {
8884 selection.head()
8885 };
8886 let snapshot = self.snapshot(cx);
8887 loop {
8888 let diagnostics = if direction == Direction::Prev {
8889 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8890 } else {
8891 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8892 }
8893 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8894 let group = diagnostics
8895 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8896 // be sorted in a stable way
8897 // skip until we are at current active diagnostic, if it exists
8898 .skip_while(|entry| {
8899 (match direction {
8900 Direction::Prev => entry.range.start >= search_start,
8901 Direction::Next => entry.range.start <= search_start,
8902 }) && self
8903 .active_diagnostics
8904 .as_ref()
8905 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8906 })
8907 .find_map(|entry| {
8908 if entry.diagnostic.is_primary
8909 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8910 && !entry.range.is_empty()
8911 // if we match with the active diagnostic, skip it
8912 && Some(entry.diagnostic.group_id)
8913 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8914 {
8915 Some((entry.range, entry.diagnostic.group_id))
8916 } else {
8917 None
8918 }
8919 });
8920
8921 if let Some((primary_range, group_id)) = group {
8922 if self.activate_diagnostics(group_id, cx) {
8923 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8924 s.select(vec![Selection {
8925 id: selection.id,
8926 start: primary_range.start,
8927 end: primary_range.start,
8928 reversed: false,
8929 goal: SelectionGoal::None,
8930 }]);
8931 });
8932 }
8933 break;
8934 } else {
8935 // Cycle around to the start of the buffer, potentially moving back to the start of
8936 // the currently active diagnostic.
8937 active_primary_range.take();
8938 if direction == Direction::Prev {
8939 if search_start == buffer.len() {
8940 break;
8941 } else {
8942 search_start = buffer.len();
8943 }
8944 } else if search_start == 0 {
8945 break;
8946 } else {
8947 search_start = 0;
8948 }
8949 }
8950 }
8951 }
8952
8953 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
8954 let snapshot = self
8955 .display_map
8956 .update(cx, |display_map, cx| display_map.snapshot(cx));
8957 let selection = self.selections.newest::<Point>(cx);
8958
8959 if !self.seek_in_direction(
8960 &snapshot,
8961 selection.head(),
8962 false,
8963 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8964 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
8965 ),
8966 cx,
8967 ) {
8968 let wrapped_point = Point::zero();
8969 self.seek_in_direction(
8970 &snapshot,
8971 wrapped_point,
8972 true,
8973 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8974 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
8975 ),
8976 cx,
8977 );
8978 }
8979 }
8980
8981 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
8982 let snapshot = self
8983 .display_map
8984 .update(cx, |display_map, cx| display_map.snapshot(cx));
8985 let selection = self.selections.newest::<Point>(cx);
8986
8987 if !self.seek_in_direction(
8988 &snapshot,
8989 selection.head(),
8990 false,
8991 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8992 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
8993 ),
8994 cx,
8995 ) {
8996 let wrapped_point = snapshot.buffer_snapshot.max_point();
8997 self.seek_in_direction(
8998 &snapshot,
8999 wrapped_point,
9000 true,
9001 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9002 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9003 ),
9004 cx,
9005 );
9006 }
9007 }
9008
9009 fn seek_in_direction(
9010 &mut self,
9011 snapshot: &DisplaySnapshot,
9012 initial_point: Point,
9013 is_wrapped: bool,
9014 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
9015 cx: &mut ViewContext<Editor>,
9016 ) -> bool {
9017 let display_point = initial_point.to_display_point(snapshot);
9018 let mut hunks = hunks
9019 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
9020 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9021 .dedup();
9022
9023 if let Some(hunk) = hunks.next() {
9024 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9025 let row = hunk.start_display_row();
9026 let point = DisplayPoint::new(row, 0);
9027 s.select_display_ranges([point..point]);
9028 });
9029
9030 true
9031 } else {
9032 false
9033 }
9034 }
9035
9036 pub fn go_to_definition(
9037 &mut self,
9038 _: &GoToDefinition,
9039 cx: &mut ViewContext<Self>,
9040 ) -> Task<Result<Navigated>> {
9041 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9042 let references = self.find_all_references(&FindAllReferences, cx);
9043 cx.background_executor().spawn(async move {
9044 if definition.await? == Navigated::Yes {
9045 return Ok(Navigated::Yes);
9046 }
9047 if let Some(references) = references {
9048 if references.await? == Navigated::Yes {
9049 return Ok(Navigated::Yes);
9050 }
9051 }
9052
9053 Ok(Navigated::No)
9054 })
9055 }
9056
9057 pub fn go_to_declaration(
9058 &mut self,
9059 _: &GoToDeclaration,
9060 cx: &mut ViewContext<Self>,
9061 ) -> Task<Result<Navigated>> {
9062 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9063 }
9064
9065 pub fn go_to_declaration_split(
9066 &mut self,
9067 _: &GoToDeclaration,
9068 cx: &mut ViewContext<Self>,
9069 ) -> Task<Result<Navigated>> {
9070 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9071 }
9072
9073 pub fn go_to_implementation(
9074 &mut self,
9075 _: &GoToImplementation,
9076 cx: &mut ViewContext<Self>,
9077 ) -> Task<Result<Navigated>> {
9078 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9079 }
9080
9081 pub fn go_to_implementation_split(
9082 &mut self,
9083 _: &GoToImplementationSplit,
9084 cx: &mut ViewContext<Self>,
9085 ) -> Task<Result<Navigated>> {
9086 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9087 }
9088
9089 pub fn go_to_type_definition(
9090 &mut self,
9091 _: &GoToTypeDefinition,
9092 cx: &mut ViewContext<Self>,
9093 ) -> Task<Result<Navigated>> {
9094 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9095 }
9096
9097 pub fn go_to_definition_split(
9098 &mut self,
9099 _: &GoToDefinitionSplit,
9100 cx: &mut ViewContext<Self>,
9101 ) -> Task<Result<Navigated>> {
9102 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9103 }
9104
9105 pub fn go_to_type_definition_split(
9106 &mut self,
9107 _: &GoToTypeDefinitionSplit,
9108 cx: &mut ViewContext<Self>,
9109 ) -> Task<Result<Navigated>> {
9110 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9111 }
9112
9113 fn go_to_definition_of_kind(
9114 &mut self,
9115 kind: GotoDefinitionKind,
9116 split: bool,
9117 cx: &mut ViewContext<Self>,
9118 ) -> Task<Result<Navigated>> {
9119 let Some(workspace) = self.workspace() else {
9120 return Task::ready(Ok(Navigated::No));
9121 };
9122 let buffer = self.buffer.read(cx);
9123 let head = self.selections.newest::<usize>(cx).head();
9124 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9125 text_anchor
9126 } else {
9127 return Task::ready(Ok(Navigated::No));
9128 };
9129
9130 let project = workspace.read(cx).project().clone();
9131 let definitions = project.update(cx, |project, cx| match kind {
9132 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9133 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9134 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9135 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9136 });
9137
9138 cx.spawn(|editor, mut cx| async move {
9139 let definitions = definitions.await?;
9140 let navigated = editor
9141 .update(&mut cx, |editor, cx| {
9142 editor.navigate_to_hover_links(
9143 Some(kind),
9144 definitions
9145 .into_iter()
9146 .filter(|location| {
9147 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9148 })
9149 .map(HoverLink::Text)
9150 .collect::<Vec<_>>(),
9151 split,
9152 cx,
9153 )
9154 })?
9155 .await?;
9156 anyhow::Ok(navigated)
9157 })
9158 }
9159
9160 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9161 let position = self.selections.newest_anchor().head();
9162 let Some((buffer, buffer_position)) =
9163 self.buffer.read(cx).text_anchor_for_position(position, cx)
9164 else {
9165 return;
9166 };
9167
9168 cx.spawn(|editor, mut cx| async move {
9169 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9170 editor.update(&mut cx, |_, cx| {
9171 cx.open_url(&url);
9172 })
9173 } else {
9174 Ok(())
9175 }
9176 })
9177 .detach();
9178 }
9179
9180 pub(crate) fn navigate_to_hover_links(
9181 &mut self,
9182 kind: Option<GotoDefinitionKind>,
9183 mut definitions: Vec<HoverLink>,
9184 split: bool,
9185 cx: &mut ViewContext<Editor>,
9186 ) -> Task<Result<Navigated>> {
9187 // If there is one definition, just open it directly
9188 if definitions.len() == 1 {
9189 let definition = definitions.pop().unwrap();
9190 let target_task = match definition {
9191 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9192 HoverLink::InlayHint(lsp_location, server_id) => {
9193 self.compute_target_location(lsp_location, server_id, cx)
9194 }
9195 HoverLink::Url(url) => {
9196 cx.open_url(&url);
9197 Task::ready(Ok(None))
9198 }
9199 };
9200 cx.spawn(|editor, mut cx| async move {
9201 let target = target_task.await.context("target resolution task")?;
9202 let Some(target) = target else {
9203 return Ok(Navigated::No);
9204 };
9205 editor.update(&mut cx, |editor, cx| {
9206 let Some(workspace) = editor.workspace() else {
9207 return Navigated::No;
9208 };
9209 let pane = workspace.read(cx).active_pane().clone();
9210
9211 let range = target.range.to_offset(target.buffer.read(cx));
9212 let range = editor.range_for_match(&range);
9213
9214 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9215 let buffer = target.buffer.read(cx);
9216 let range = check_multiline_range(buffer, range);
9217 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9218 s.select_ranges([range]);
9219 });
9220 } else {
9221 cx.window_context().defer(move |cx| {
9222 let target_editor: View<Self> =
9223 workspace.update(cx, |workspace, cx| {
9224 let pane = if split {
9225 workspace.adjacent_pane(cx)
9226 } else {
9227 workspace.active_pane().clone()
9228 };
9229
9230 workspace.open_project_item(
9231 pane,
9232 target.buffer.clone(),
9233 true,
9234 true,
9235 cx,
9236 )
9237 });
9238 target_editor.update(cx, |target_editor, cx| {
9239 // When selecting a definition in a different buffer, disable the nav history
9240 // to avoid creating a history entry at the previous cursor location.
9241 pane.update(cx, |pane, _| pane.disable_history());
9242 let buffer = target.buffer.read(cx);
9243 let range = check_multiline_range(buffer, range);
9244 target_editor.change_selections(
9245 Some(Autoscroll::focused()),
9246 cx,
9247 |s| {
9248 s.select_ranges([range]);
9249 },
9250 );
9251 pane.update(cx, |pane, _| pane.enable_history());
9252 });
9253 });
9254 }
9255 Navigated::Yes
9256 })
9257 })
9258 } else if !definitions.is_empty() {
9259 let replica_id = self.replica_id(cx);
9260 cx.spawn(|editor, mut cx| async move {
9261 let (title, location_tasks, workspace) = editor
9262 .update(&mut cx, |editor, cx| {
9263 let tab_kind = match kind {
9264 Some(GotoDefinitionKind::Implementation) => "Implementations",
9265 _ => "Definitions",
9266 };
9267 let title = definitions
9268 .iter()
9269 .find_map(|definition| match definition {
9270 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9271 let buffer = origin.buffer.read(cx);
9272 format!(
9273 "{} for {}",
9274 tab_kind,
9275 buffer
9276 .text_for_range(origin.range.clone())
9277 .collect::<String>()
9278 )
9279 }),
9280 HoverLink::InlayHint(_, _) => None,
9281 HoverLink::Url(_) => None,
9282 })
9283 .unwrap_or(tab_kind.to_string());
9284 let location_tasks = definitions
9285 .into_iter()
9286 .map(|definition| match definition {
9287 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9288 HoverLink::InlayHint(lsp_location, server_id) => {
9289 editor.compute_target_location(lsp_location, server_id, cx)
9290 }
9291 HoverLink::Url(_) => Task::ready(Ok(None)),
9292 })
9293 .collect::<Vec<_>>();
9294 (title, location_tasks, editor.workspace().clone())
9295 })
9296 .context("location tasks preparation")?;
9297
9298 let locations = futures::future::join_all(location_tasks)
9299 .await
9300 .into_iter()
9301 .filter_map(|location| location.transpose())
9302 .collect::<Result<_>>()
9303 .context("location tasks")?;
9304
9305 let Some(workspace) = workspace else {
9306 return Ok(Navigated::No);
9307 };
9308 let opened = workspace
9309 .update(&mut cx, |workspace, cx| {
9310 Self::open_locations_in_multibuffer(
9311 workspace, locations, replica_id, title, split, cx,
9312 )
9313 })
9314 .ok();
9315
9316 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9317 })
9318 } else {
9319 Task::ready(Ok(Navigated::No))
9320 }
9321 }
9322
9323 fn compute_target_location(
9324 &self,
9325 lsp_location: lsp::Location,
9326 server_id: LanguageServerId,
9327 cx: &mut ViewContext<Editor>,
9328 ) -> Task<anyhow::Result<Option<Location>>> {
9329 let Some(project) = self.project.clone() else {
9330 return Task::Ready(Some(Ok(None)));
9331 };
9332
9333 cx.spawn(move |editor, mut cx| async move {
9334 let location_task = editor.update(&mut cx, |editor, cx| {
9335 project.update(cx, |project, cx| {
9336 let language_server_name =
9337 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9338 project
9339 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9340 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9341 });
9342 language_server_name.map(|language_server_name| {
9343 project.open_local_buffer_via_lsp(
9344 lsp_location.uri.clone(),
9345 server_id,
9346 language_server_name,
9347 cx,
9348 )
9349 })
9350 })
9351 })?;
9352 let location = match location_task {
9353 Some(task) => Some({
9354 let target_buffer_handle = task.await.context("open local buffer")?;
9355 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9356 let target_start = target_buffer
9357 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9358 let target_end = target_buffer
9359 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9360 target_buffer.anchor_after(target_start)
9361 ..target_buffer.anchor_before(target_end)
9362 })?;
9363 Location {
9364 buffer: target_buffer_handle,
9365 range,
9366 }
9367 }),
9368 None => None,
9369 };
9370 Ok(location)
9371 })
9372 }
9373
9374 pub fn find_all_references(
9375 &mut self,
9376 _: &FindAllReferences,
9377 cx: &mut ViewContext<Self>,
9378 ) -> Option<Task<Result<Navigated>>> {
9379 let multi_buffer = self.buffer.read(cx);
9380 let selection = self.selections.newest::<usize>(cx);
9381 let head = selection.head();
9382
9383 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9384 let head_anchor = multi_buffer_snapshot.anchor_at(
9385 head,
9386 if head < selection.tail() {
9387 Bias::Right
9388 } else {
9389 Bias::Left
9390 },
9391 );
9392
9393 match self
9394 .find_all_references_task_sources
9395 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9396 {
9397 Ok(_) => {
9398 log::info!(
9399 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9400 );
9401 return None;
9402 }
9403 Err(i) => {
9404 self.find_all_references_task_sources.insert(i, head_anchor);
9405 }
9406 }
9407
9408 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9409 let replica_id = self.replica_id(cx);
9410 let workspace = self.workspace()?;
9411 let project = workspace.read(cx).project().clone();
9412 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9413 Some(cx.spawn(|editor, mut cx| async move {
9414 let _cleanup = defer({
9415 let mut cx = cx.clone();
9416 move || {
9417 let _ = editor.update(&mut cx, |editor, _| {
9418 if let Ok(i) =
9419 editor
9420 .find_all_references_task_sources
9421 .binary_search_by(|anchor| {
9422 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9423 })
9424 {
9425 editor.find_all_references_task_sources.remove(i);
9426 }
9427 });
9428 }
9429 });
9430
9431 let locations = references.await?;
9432 if locations.is_empty() {
9433 return anyhow::Ok(Navigated::No);
9434 }
9435
9436 workspace.update(&mut cx, |workspace, cx| {
9437 let title = locations
9438 .first()
9439 .as_ref()
9440 .map(|location| {
9441 let buffer = location.buffer.read(cx);
9442 format!(
9443 "References to `{}`",
9444 buffer
9445 .text_for_range(location.range.clone())
9446 .collect::<String>()
9447 )
9448 })
9449 .unwrap();
9450 Self::open_locations_in_multibuffer(
9451 workspace, locations, replica_id, title, false, cx,
9452 );
9453 Navigated::Yes
9454 })
9455 }))
9456 }
9457
9458 /// Opens a multibuffer with the given project locations in it
9459 pub fn open_locations_in_multibuffer(
9460 workspace: &mut Workspace,
9461 mut locations: Vec<Location>,
9462 replica_id: ReplicaId,
9463 title: String,
9464 split: bool,
9465 cx: &mut ViewContext<Workspace>,
9466 ) {
9467 // If there are multiple definitions, open them in a multibuffer
9468 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9469 let mut locations = locations.into_iter().peekable();
9470 let mut ranges_to_highlight = Vec::new();
9471 let capability = workspace.project().read(cx).capability();
9472
9473 let excerpt_buffer = cx.new_model(|cx| {
9474 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9475 while let Some(location) = locations.next() {
9476 let buffer = location.buffer.read(cx);
9477 let mut ranges_for_buffer = Vec::new();
9478 let range = location.range.to_offset(buffer);
9479 ranges_for_buffer.push(range.clone());
9480
9481 while let Some(next_location) = locations.peek() {
9482 if next_location.buffer == location.buffer {
9483 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9484 locations.next();
9485 } else {
9486 break;
9487 }
9488 }
9489
9490 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9491 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9492 location.buffer.clone(),
9493 ranges_for_buffer,
9494 DEFAULT_MULTIBUFFER_CONTEXT,
9495 cx,
9496 ))
9497 }
9498
9499 multibuffer.with_title(title)
9500 });
9501
9502 let editor = cx.new_view(|cx| {
9503 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9504 });
9505 editor.update(cx, |editor, cx| {
9506 if let Some(first_range) = ranges_to_highlight.first() {
9507 editor.change_selections(None, cx, |selections| {
9508 selections.clear_disjoint();
9509 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9510 });
9511 }
9512 editor.highlight_background::<Self>(
9513 &ranges_to_highlight,
9514 |theme| theme.editor_highlighted_line_background,
9515 cx,
9516 );
9517 });
9518
9519 let item = Box::new(editor);
9520 let item_id = item.item_id();
9521
9522 if split {
9523 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9524 } else {
9525 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9526 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9527 pane.close_current_preview_item(cx)
9528 } else {
9529 None
9530 }
9531 });
9532 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9533 }
9534 workspace.active_pane().update(cx, |pane, cx| {
9535 pane.set_preview_item_id(Some(item_id), cx);
9536 });
9537 }
9538
9539 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9540 use language::ToOffset as _;
9541
9542 let project = self.project.clone()?;
9543 let selection = self.selections.newest_anchor().clone();
9544 let (cursor_buffer, cursor_buffer_position) = self
9545 .buffer
9546 .read(cx)
9547 .text_anchor_for_position(selection.head(), cx)?;
9548 let (tail_buffer, cursor_buffer_position_end) = self
9549 .buffer
9550 .read(cx)
9551 .text_anchor_for_position(selection.tail(), cx)?;
9552 if tail_buffer != cursor_buffer {
9553 return None;
9554 }
9555
9556 let snapshot = cursor_buffer.read(cx).snapshot();
9557 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9558 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9559 let prepare_rename = project.update(cx, |project, cx| {
9560 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9561 });
9562 drop(snapshot);
9563
9564 Some(cx.spawn(|this, mut cx| async move {
9565 let rename_range = if let Some(range) = prepare_rename.await? {
9566 Some(range)
9567 } else {
9568 this.update(&mut cx, |this, cx| {
9569 let buffer = this.buffer.read(cx).snapshot(cx);
9570 let mut buffer_highlights = this
9571 .document_highlights_for_position(selection.head(), &buffer)
9572 .filter(|highlight| {
9573 highlight.start.excerpt_id == selection.head().excerpt_id
9574 && highlight.end.excerpt_id == selection.head().excerpt_id
9575 });
9576 buffer_highlights
9577 .next()
9578 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9579 })?
9580 };
9581 if let Some(rename_range) = rename_range {
9582 this.update(&mut cx, |this, cx| {
9583 let snapshot = cursor_buffer.read(cx).snapshot();
9584 let rename_buffer_range = rename_range.to_offset(&snapshot);
9585 let cursor_offset_in_rename_range =
9586 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9587 let cursor_offset_in_rename_range_end =
9588 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9589
9590 this.take_rename(false, cx);
9591 let buffer = this.buffer.read(cx).read(cx);
9592 let cursor_offset = selection.head().to_offset(&buffer);
9593 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9594 let rename_end = rename_start + rename_buffer_range.len();
9595 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9596 let mut old_highlight_id = None;
9597 let old_name: Arc<str> = buffer
9598 .chunks(rename_start..rename_end, true)
9599 .map(|chunk| {
9600 if old_highlight_id.is_none() {
9601 old_highlight_id = chunk.syntax_highlight_id;
9602 }
9603 chunk.text
9604 })
9605 .collect::<String>()
9606 .into();
9607
9608 drop(buffer);
9609
9610 // Position the selection in the rename editor so that it matches the current selection.
9611 this.show_local_selections = false;
9612 let rename_editor = cx.new_view(|cx| {
9613 let mut editor = Editor::single_line(cx);
9614 editor.buffer.update(cx, |buffer, cx| {
9615 buffer.edit([(0..0, old_name.clone())], None, cx)
9616 });
9617 let rename_selection_range = match cursor_offset_in_rename_range
9618 .cmp(&cursor_offset_in_rename_range_end)
9619 {
9620 Ordering::Equal => {
9621 editor.select_all(&SelectAll, cx);
9622 return editor;
9623 }
9624 Ordering::Less => {
9625 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9626 }
9627 Ordering::Greater => {
9628 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9629 }
9630 };
9631 if rename_selection_range.end > old_name.len() {
9632 editor.select_all(&SelectAll, cx);
9633 } else {
9634 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9635 s.select_ranges([rename_selection_range]);
9636 });
9637 }
9638 editor
9639 });
9640 cx.subscribe(&rename_editor, |_, _, e, cx| match e {
9641 EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
9642 _ => {}
9643 })
9644 .detach();
9645
9646 let write_highlights =
9647 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9648 let read_highlights =
9649 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9650 let ranges = write_highlights
9651 .iter()
9652 .flat_map(|(_, ranges)| ranges.iter())
9653 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9654 .cloned()
9655 .collect();
9656
9657 this.highlight_text::<Rename>(
9658 ranges,
9659 HighlightStyle {
9660 fade_out: Some(0.6),
9661 ..Default::default()
9662 },
9663 cx,
9664 );
9665 let rename_focus_handle = rename_editor.focus_handle(cx);
9666 cx.focus(&rename_focus_handle);
9667 let block_id = this.insert_blocks(
9668 [BlockProperties {
9669 style: BlockStyle::Flex,
9670 position: range.start,
9671 height: 1,
9672 render: Box::new({
9673 let rename_editor = rename_editor.clone();
9674 move |cx: &mut BlockContext| {
9675 let mut text_style = cx.editor_style.text.clone();
9676 if let Some(highlight_style) = old_highlight_id
9677 .and_then(|h| h.style(&cx.editor_style.syntax))
9678 {
9679 text_style = text_style.highlight(highlight_style);
9680 }
9681 div()
9682 .pl(cx.anchor_x)
9683 .child(EditorElement::new(
9684 &rename_editor,
9685 EditorStyle {
9686 background: cx.theme().system().transparent,
9687 local_player: cx.editor_style.local_player,
9688 text: text_style,
9689 scrollbar_width: cx.editor_style.scrollbar_width,
9690 syntax: cx.editor_style.syntax.clone(),
9691 status: cx.editor_style.status.clone(),
9692 inlay_hints_style: HighlightStyle {
9693 color: Some(cx.theme().status().hint),
9694 font_weight: Some(FontWeight::BOLD),
9695 ..HighlightStyle::default()
9696 },
9697 suggestions_style: HighlightStyle {
9698 color: Some(cx.theme().status().predictive),
9699 ..HighlightStyle::default()
9700 },
9701 },
9702 ))
9703 .into_any_element()
9704 }
9705 }),
9706 disposition: BlockDisposition::Below,
9707 priority: 0,
9708 }],
9709 Some(Autoscroll::fit()),
9710 cx,
9711 )[0];
9712 this.pending_rename = Some(RenameState {
9713 range,
9714 old_name,
9715 editor: rename_editor,
9716 block_id,
9717 });
9718 })?;
9719 }
9720
9721 Ok(())
9722 }))
9723 }
9724
9725 pub fn confirm_rename(
9726 &mut self,
9727 _: &ConfirmRename,
9728 cx: &mut ViewContext<Self>,
9729 ) -> Option<Task<Result<()>>> {
9730 let rename = self.take_rename(false, cx)?;
9731 let workspace = self.workspace()?;
9732 let (start_buffer, start) = self
9733 .buffer
9734 .read(cx)
9735 .text_anchor_for_position(rename.range.start, cx)?;
9736 let (end_buffer, end) = self
9737 .buffer
9738 .read(cx)
9739 .text_anchor_for_position(rename.range.end, cx)?;
9740 if start_buffer != end_buffer {
9741 return None;
9742 }
9743
9744 let buffer = start_buffer;
9745 let range = start..end;
9746 let old_name = rename.old_name;
9747 let new_name = rename.editor.read(cx).text(cx);
9748
9749 let rename = workspace
9750 .read(cx)
9751 .project()
9752 .clone()
9753 .update(cx, |project, cx| {
9754 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9755 });
9756 let workspace = workspace.downgrade();
9757
9758 Some(cx.spawn(|editor, mut cx| async move {
9759 let project_transaction = rename.await?;
9760 Self::open_project_transaction(
9761 &editor,
9762 workspace,
9763 project_transaction,
9764 format!("Rename: {} → {}", old_name, new_name),
9765 cx.clone(),
9766 )
9767 .await?;
9768
9769 editor.update(&mut cx, |editor, cx| {
9770 editor.refresh_document_highlights(cx);
9771 })?;
9772 Ok(())
9773 }))
9774 }
9775
9776 fn take_rename(
9777 &mut self,
9778 moving_cursor: bool,
9779 cx: &mut ViewContext<Self>,
9780 ) -> Option<RenameState> {
9781 let rename = self.pending_rename.take()?;
9782 if rename.editor.focus_handle(cx).is_focused(cx) {
9783 cx.focus(&self.focus_handle);
9784 }
9785
9786 self.remove_blocks(
9787 [rename.block_id].into_iter().collect(),
9788 Some(Autoscroll::fit()),
9789 cx,
9790 );
9791 self.clear_highlights::<Rename>(cx);
9792 self.show_local_selections = true;
9793
9794 if moving_cursor {
9795 let rename_editor = rename.editor.read(cx);
9796 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9797
9798 // Update the selection to match the position of the selection inside
9799 // the rename editor.
9800 let snapshot = self.buffer.read(cx).read(cx);
9801 let rename_range = rename.range.to_offset(&snapshot);
9802 let cursor_in_editor = snapshot
9803 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9804 .min(rename_range.end);
9805 drop(snapshot);
9806
9807 self.change_selections(None, cx, |s| {
9808 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9809 });
9810 } else {
9811 self.refresh_document_highlights(cx);
9812 }
9813
9814 Some(rename)
9815 }
9816
9817 pub fn pending_rename(&self) -> Option<&RenameState> {
9818 self.pending_rename.as_ref()
9819 }
9820
9821 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9822 let project = match &self.project {
9823 Some(project) => project.clone(),
9824 None => return None,
9825 };
9826
9827 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9828 }
9829
9830 fn perform_format(
9831 &mut self,
9832 project: Model<Project>,
9833 trigger: FormatTrigger,
9834 cx: &mut ViewContext<Self>,
9835 ) -> Task<Result<()>> {
9836 let buffer = self.buffer().clone();
9837 let mut buffers = buffer.read(cx).all_buffers();
9838 if trigger == FormatTrigger::Save {
9839 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9840 }
9841
9842 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9843 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9844
9845 cx.spawn(|_, mut cx| async move {
9846 let transaction = futures::select_biased! {
9847 () = timeout => {
9848 log::warn!("timed out waiting for formatting");
9849 None
9850 }
9851 transaction = format.log_err().fuse() => transaction,
9852 };
9853
9854 buffer
9855 .update(&mut cx, |buffer, cx| {
9856 if let Some(transaction) = transaction {
9857 if !buffer.is_singleton() {
9858 buffer.push_transaction(&transaction.0, cx);
9859 }
9860 }
9861
9862 cx.notify();
9863 })
9864 .ok();
9865
9866 Ok(())
9867 })
9868 }
9869
9870 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
9871 if let Some(project) = self.project.clone() {
9872 self.buffer.update(cx, |multi_buffer, cx| {
9873 project.update(cx, |project, cx| {
9874 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
9875 });
9876 })
9877 }
9878 }
9879
9880 fn cancel_language_server_work(
9881 &mut self,
9882 _: &CancelLanguageServerWork,
9883 cx: &mut ViewContext<Self>,
9884 ) {
9885 if let Some(project) = self.project.clone() {
9886 self.buffer.update(cx, |multi_buffer, cx| {
9887 project.update(cx, |project, cx| {
9888 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
9889 });
9890 })
9891 }
9892 }
9893
9894 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
9895 cx.show_character_palette();
9896 }
9897
9898 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
9899 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
9900 let buffer = self.buffer.read(cx).snapshot(cx);
9901 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
9902 let is_valid = buffer
9903 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
9904 .any(|entry| {
9905 entry.diagnostic.is_primary
9906 && !entry.range.is_empty()
9907 && entry.range.start == primary_range_start
9908 && entry.diagnostic.message == active_diagnostics.primary_message
9909 });
9910
9911 if is_valid != active_diagnostics.is_valid {
9912 active_diagnostics.is_valid = is_valid;
9913 let mut new_styles = HashMap::default();
9914 for (block_id, diagnostic) in &active_diagnostics.blocks {
9915 new_styles.insert(
9916 *block_id,
9917 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
9918 );
9919 }
9920 self.display_map.update(cx, |display_map, _cx| {
9921 display_map.replace_blocks(new_styles)
9922 });
9923 }
9924 }
9925 }
9926
9927 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
9928 self.dismiss_diagnostics(cx);
9929 let snapshot = self.snapshot(cx);
9930 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
9931 let buffer = self.buffer.read(cx).snapshot(cx);
9932
9933 let mut primary_range = None;
9934 let mut primary_message = None;
9935 let mut group_end = Point::zero();
9936 let diagnostic_group = buffer
9937 .diagnostic_group::<MultiBufferPoint>(group_id)
9938 .filter_map(|entry| {
9939 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
9940 && (entry.range.start.row == entry.range.end.row
9941 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
9942 {
9943 return None;
9944 }
9945 if entry.range.end > group_end {
9946 group_end = entry.range.end;
9947 }
9948 if entry.diagnostic.is_primary {
9949 primary_range = Some(entry.range.clone());
9950 primary_message = Some(entry.diagnostic.message.clone());
9951 }
9952 Some(entry)
9953 })
9954 .collect::<Vec<_>>();
9955 let primary_range = primary_range?;
9956 let primary_message = primary_message?;
9957 let primary_range =
9958 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
9959
9960 let blocks = display_map
9961 .insert_blocks(
9962 diagnostic_group.iter().map(|entry| {
9963 let diagnostic = entry.diagnostic.clone();
9964 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
9965 BlockProperties {
9966 style: BlockStyle::Fixed,
9967 position: buffer.anchor_after(entry.range.start),
9968 height: message_height,
9969 render: diagnostic_block_renderer(diagnostic, None, true, true),
9970 disposition: BlockDisposition::Below,
9971 priority: 0,
9972 }
9973 }),
9974 cx,
9975 )
9976 .into_iter()
9977 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
9978 .collect();
9979
9980 Some(ActiveDiagnosticGroup {
9981 primary_range,
9982 primary_message,
9983 group_id,
9984 blocks,
9985 is_valid: true,
9986 })
9987 });
9988 self.active_diagnostics.is_some()
9989 }
9990
9991 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
9992 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
9993 self.display_map.update(cx, |display_map, cx| {
9994 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
9995 });
9996 cx.notify();
9997 }
9998 }
9999
10000 pub fn set_selections_from_remote(
10001 &mut self,
10002 selections: Vec<Selection<Anchor>>,
10003 pending_selection: Option<Selection<Anchor>>,
10004 cx: &mut ViewContext<Self>,
10005 ) {
10006 let old_cursor_position = self.selections.newest_anchor().head();
10007 self.selections.change_with(cx, |s| {
10008 s.select_anchors(selections);
10009 if let Some(pending_selection) = pending_selection {
10010 s.set_pending(pending_selection, SelectMode::Character);
10011 } else {
10012 s.clear_pending();
10013 }
10014 });
10015 self.selections_did_change(false, &old_cursor_position, true, cx);
10016 }
10017
10018 fn push_to_selection_history(&mut self) {
10019 self.selection_history.push(SelectionHistoryEntry {
10020 selections: self.selections.disjoint_anchors(),
10021 select_next_state: self.select_next_state.clone(),
10022 select_prev_state: self.select_prev_state.clone(),
10023 add_selections_state: self.add_selections_state.clone(),
10024 });
10025 }
10026
10027 pub fn transact(
10028 &mut self,
10029 cx: &mut ViewContext<Self>,
10030 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10031 ) -> Option<TransactionId> {
10032 self.start_transaction_at(Instant::now(), cx);
10033 update(self, cx);
10034 self.end_transaction_at(Instant::now(), cx)
10035 }
10036
10037 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10038 self.end_selection(cx);
10039 if let Some(tx_id) = self
10040 .buffer
10041 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10042 {
10043 self.selection_history
10044 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10045 cx.emit(EditorEvent::TransactionBegun {
10046 transaction_id: tx_id,
10047 })
10048 }
10049 }
10050
10051 fn end_transaction_at(
10052 &mut self,
10053 now: Instant,
10054 cx: &mut ViewContext<Self>,
10055 ) -> Option<TransactionId> {
10056 if let Some(transaction_id) = self
10057 .buffer
10058 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10059 {
10060 if let Some((_, end_selections)) =
10061 self.selection_history.transaction_mut(transaction_id)
10062 {
10063 *end_selections = Some(self.selections.disjoint_anchors());
10064 } else {
10065 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10066 }
10067
10068 cx.emit(EditorEvent::Edited { transaction_id });
10069 Some(transaction_id)
10070 } else {
10071 None
10072 }
10073 }
10074
10075 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10076 let mut fold_ranges = Vec::new();
10077
10078 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10079
10080 let selections = self.selections.all_adjusted(cx);
10081 for selection in selections {
10082 let range = selection.range().sorted();
10083 let buffer_start_row = range.start.row;
10084
10085 for row in (0..=range.end.row).rev() {
10086 if let Some((foldable_range, fold_text)) =
10087 display_map.foldable_range(MultiBufferRow(row))
10088 {
10089 if foldable_range.end.row >= buffer_start_row {
10090 fold_ranges.push((foldable_range, fold_text));
10091 if row <= range.start.row {
10092 break;
10093 }
10094 }
10095 }
10096 }
10097 }
10098
10099 self.fold_ranges(fold_ranges, true, cx);
10100 }
10101
10102 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10103 let buffer_row = fold_at.buffer_row;
10104 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10105
10106 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10107 let autoscroll = self
10108 .selections
10109 .all::<Point>(cx)
10110 .iter()
10111 .any(|selection| fold_range.overlaps(&selection.range()));
10112
10113 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10114 }
10115 }
10116
10117 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10118 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10119 let buffer = &display_map.buffer_snapshot;
10120 let selections = self.selections.all::<Point>(cx);
10121 let ranges = selections
10122 .iter()
10123 .map(|s| {
10124 let range = s.display_range(&display_map).sorted();
10125 let mut start = range.start.to_point(&display_map);
10126 let mut end = range.end.to_point(&display_map);
10127 start.column = 0;
10128 end.column = buffer.line_len(MultiBufferRow(end.row));
10129 start..end
10130 })
10131 .collect::<Vec<_>>();
10132
10133 self.unfold_ranges(ranges, true, true, cx);
10134 }
10135
10136 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10137 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10138
10139 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10140 ..Point::new(
10141 unfold_at.buffer_row.0,
10142 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10143 );
10144
10145 let autoscroll = self
10146 .selections
10147 .all::<Point>(cx)
10148 .iter()
10149 .any(|selection| selection.range().overlaps(&intersection_range));
10150
10151 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10152 }
10153
10154 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10155 let selections = self.selections.all::<Point>(cx);
10156 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10157 let line_mode = self.selections.line_mode;
10158 let ranges = selections.into_iter().map(|s| {
10159 if line_mode {
10160 let start = Point::new(s.start.row, 0);
10161 let end = Point::new(
10162 s.end.row,
10163 display_map
10164 .buffer_snapshot
10165 .line_len(MultiBufferRow(s.end.row)),
10166 );
10167 (start..end, display_map.fold_placeholder.clone())
10168 } else {
10169 (s.start..s.end, display_map.fold_placeholder.clone())
10170 }
10171 });
10172 self.fold_ranges(ranges, true, cx);
10173 }
10174
10175 pub fn fold_ranges<T: ToOffset + Clone>(
10176 &mut self,
10177 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10178 auto_scroll: bool,
10179 cx: &mut ViewContext<Self>,
10180 ) {
10181 let mut fold_ranges = Vec::new();
10182 let mut buffers_affected = HashMap::default();
10183 let multi_buffer = self.buffer().read(cx);
10184 for (fold_range, fold_text) in ranges {
10185 if let Some((_, buffer, _)) =
10186 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10187 {
10188 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10189 };
10190 fold_ranges.push((fold_range, fold_text));
10191 }
10192
10193 let mut ranges = fold_ranges.into_iter().peekable();
10194 if ranges.peek().is_some() {
10195 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10196
10197 if auto_scroll {
10198 self.request_autoscroll(Autoscroll::fit(), cx);
10199 }
10200
10201 for buffer in buffers_affected.into_values() {
10202 self.sync_expanded_diff_hunks(buffer, cx);
10203 }
10204
10205 cx.notify();
10206
10207 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10208 // Clear diagnostics block when folding a range that contains it.
10209 let snapshot = self.snapshot(cx);
10210 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10211 drop(snapshot);
10212 self.active_diagnostics = Some(active_diagnostics);
10213 self.dismiss_diagnostics(cx);
10214 } else {
10215 self.active_diagnostics = Some(active_diagnostics);
10216 }
10217 }
10218
10219 self.scrollbar_marker_state.dirty = true;
10220 }
10221 }
10222
10223 pub fn unfold_ranges<T: ToOffset + Clone>(
10224 &mut self,
10225 ranges: impl IntoIterator<Item = Range<T>>,
10226 inclusive: bool,
10227 auto_scroll: bool,
10228 cx: &mut ViewContext<Self>,
10229 ) {
10230 let mut unfold_ranges = Vec::new();
10231 let mut buffers_affected = HashMap::default();
10232 let multi_buffer = self.buffer().read(cx);
10233 for range in ranges {
10234 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10235 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10236 };
10237 unfold_ranges.push(range);
10238 }
10239
10240 let mut ranges = unfold_ranges.into_iter().peekable();
10241 if ranges.peek().is_some() {
10242 self.display_map
10243 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10244 if auto_scroll {
10245 self.request_autoscroll(Autoscroll::fit(), cx);
10246 }
10247
10248 for buffer in buffers_affected.into_values() {
10249 self.sync_expanded_diff_hunks(buffer, cx);
10250 }
10251
10252 cx.notify();
10253 self.scrollbar_marker_state.dirty = true;
10254 self.active_indent_guides_state.dirty = true;
10255 }
10256 }
10257
10258 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10259 if hovered != self.gutter_hovered {
10260 self.gutter_hovered = hovered;
10261 cx.notify();
10262 }
10263 }
10264
10265 pub fn insert_blocks(
10266 &mut self,
10267 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10268 autoscroll: Option<Autoscroll>,
10269 cx: &mut ViewContext<Self>,
10270 ) -> Vec<CustomBlockId> {
10271 let blocks = self
10272 .display_map
10273 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10274 if let Some(autoscroll) = autoscroll {
10275 self.request_autoscroll(autoscroll, cx);
10276 }
10277 cx.notify();
10278 blocks
10279 }
10280
10281 pub fn resize_blocks(
10282 &mut self,
10283 heights: HashMap<CustomBlockId, u32>,
10284 autoscroll: Option<Autoscroll>,
10285 cx: &mut ViewContext<Self>,
10286 ) {
10287 self.display_map
10288 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10289 if let Some(autoscroll) = autoscroll {
10290 self.request_autoscroll(autoscroll, cx);
10291 }
10292 cx.notify();
10293 }
10294
10295 pub fn replace_blocks(
10296 &mut self,
10297 renderers: HashMap<CustomBlockId, RenderBlock>,
10298 autoscroll: Option<Autoscroll>,
10299 cx: &mut ViewContext<Self>,
10300 ) {
10301 self.display_map
10302 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10303 if let Some(autoscroll) = autoscroll {
10304 self.request_autoscroll(autoscroll, cx);
10305 }
10306 cx.notify();
10307 }
10308
10309 pub fn remove_blocks(
10310 &mut self,
10311 block_ids: HashSet<CustomBlockId>,
10312 autoscroll: Option<Autoscroll>,
10313 cx: &mut ViewContext<Self>,
10314 ) {
10315 self.display_map.update(cx, |display_map, cx| {
10316 display_map.remove_blocks(block_ids, cx)
10317 });
10318 if let Some(autoscroll) = autoscroll {
10319 self.request_autoscroll(autoscroll, cx);
10320 }
10321 cx.notify();
10322 }
10323
10324 pub fn row_for_block(
10325 &self,
10326 block_id: CustomBlockId,
10327 cx: &mut ViewContext<Self>,
10328 ) -> Option<DisplayRow> {
10329 self.display_map
10330 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10331 }
10332
10333 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10334 self.focused_block = Some(focused_block);
10335 }
10336
10337 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10338 self.focused_block.take()
10339 }
10340
10341 pub fn insert_creases(
10342 &mut self,
10343 creases: impl IntoIterator<Item = Crease>,
10344 cx: &mut ViewContext<Self>,
10345 ) -> Vec<CreaseId> {
10346 self.display_map
10347 .update(cx, |map, cx| map.insert_creases(creases, cx))
10348 }
10349
10350 pub fn remove_creases(
10351 &mut self,
10352 ids: impl IntoIterator<Item = CreaseId>,
10353 cx: &mut ViewContext<Self>,
10354 ) {
10355 self.display_map
10356 .update(cx, |map, cx| map.remove_creases(ids, cx));
10357 }
10358
10359 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10360 self.display_map
10361 .update(cx, |map, cx| map.snapshot(cx))
10362 .longest_row()
10363 }
10364
10365 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10366 self.display_map
10367 .update(cx, |map, cx| map.snapshot(cx))
10368 .max_point()
10369 }
10370
10371 pub fn text(&self, cx: &AppContext) -> String {
10372 self.buffer.read(cx).read(cx).text()
10373 }
10374
10375 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10376 let text = self.text(cx);
10377 let text = text.trim();
10378
10379 if text.is_empty() {
10380 return None;
10381 }
10382
10383 Some(text.to_string())
10384 }
10385
10386 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10387 self.transact(cx, |this, cx| {
10388 this.buffer
10389 .read(cx)
10390 .as_singleton()
10391 .expect("you can only call set_text on editors for singleton buffers")
10392 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10393 });
10394 }
10395
10396 pub fn display_text(&self, cx: &mut AppContext) -> String {
10397 self.display_map
10398 .update(cx, |map, cx| map.snapshot(cx))
10399 .text()
10400 }
10401
10402 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10403 let mut wrap_guides = smallvec::smallvec![];
10404
10405 if self.show_wrap_guides == Some(false) {
10406 return wrap_guides;
10407 }
10408
10409 let settings = self.buffer.read(cx).settings_at(0, cx);
10410 if settings.show_wrap_guides {
10411 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10412 wrap_guides.push((soft_wrap as usize, true));
10413 }
10414 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10415 }
10416
10417 wrap_guides
10418 }
10419
10420 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10421 let settings = self.buffer.read(cx).settings_at(0, cx);
10422 let mode = self
10423 .soft_wrap_mode_override
10424 .unwrap_or_else(|| settings.soft_wrap);
10425 match mode {
10426 language_settings::SoftWrap::None => SoftWrap::None,
10427 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10428 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10429 language_settings::SoftWrap::PreferredLineLength => {
10430 SoftWrap::Column(settings.preferred_line_length)
10431 }
10432 }
10433 }
10434
10435 pub fn set_soft_wrap_mode(
10436 &mut self,
10437 mode: language_settings::SoftWrap,
10438 cx: &mut ViewContext<Self>,
10439 ) {
10440 self.soft_wrap_mode_override = Some(mode);
10441 cx.notify();
10442 }
10443
10444 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10445 let rem_size = cx.rem_size();
10446 self.display_map.update(cx, |map, cx| {
10447 map.set_font(
10448 style.text.font(),
10449 style.text.font_size.to_pixels(rem_size),
10450 cx,
10451 )
10452 });
10453 self.style = Some(style);
10454 }
10455
10456 pub fn style(&self) -> Option<&EditorStyle> {
10457 self.style.as_ref()
10458 }
10459
10460 // Called by the element. This method is not designed to be called outside of the editor
10461 // element's layout code because it does not notify when rewrapping is computed synchronously.
10462 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10463 self.display_map
10464 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10465 }
10466
10467 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10468 if self.soft_wrap_mode_override.is_some() {
10469 self.soft_wrap_mode_override.take();
10470 } else {
10471 let soft_wrap = match self.soft_wrap_mode(cx) {
10472 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10473 SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10474 language_settings::SoftWrap::PreferLine
10475 }
10476 };
10477 self.soft_wrap_mode_override = Some(soft_wrap);
10478 }
10479 cx.notify();
10480 }
10481
10482 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10483 let Some(workspace) = self.workspace() else {
10484 return;
10485 };
10486 let fs = workspace.read(cx).app_state().fs.clone();
10487 let current_show = TabBarSettings::get_global(cx).show;
10488 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10489 setting.show = Some(!current_show);
10490 });
10491 }
10492
10493 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10494 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10495 self.buffer
10496 .read(cx)
10497 .settings_at(0, cx)
10498 .indent_guides
10499 .enabled
10500 });
10501 self.show_indent_guides = Some(!currently_enabled);
10502 cx.notify();
10503 }
10504
10505 fn should_show_indent_guides(&self) -> Option<bool> {
10506 self.show_indent_guides
10507 }
10508
10509 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10510 let mut editor_settings = EditorSettings::get_global(cx).clone();
10511 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10512 EditorSettings::override_global(editor_settings, cx);
10513 }
10514
10515 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10516 self.show_gutter = show_gutter;
10517 cx.notify();
10518 }
10519
10520 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10521 self.show_line_numbers = Some(show_line_numbers);
10522 cx.notify();
10523 }
10524
10525 pub fn set_show_git_diff_gutter(
10526 &mut self,
10527 show_git_diff_gutter: bool,
10528 cx: &mut ViewContext<Self>,
10529 ) {
10530 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10531 cx.notify();
10532 }
10533
10534 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10535 self.show_code_actions = Some(show_code_actions);
10536 cx.notify();
10537 }
10538
10539 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10540 self.show_runnables = Some(show_runnables);
10541 cx.notify();
10542 }
10543
10544 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10545 if self.display_map.read(cx).masked != masked {
10546 self.display_map.update(cx, |map, _| map.masked = masked);
10547 }
10548 cx.notify()
10549 }
10550
10551 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10552 self.show_wrap_guides = Some(show_wrap_guides);
10553 cx.notify();
10554 }
10555
10556 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10557 self.show_indent_guides = Some(show_indent_guides);
10558 cx.notify();
10559 }
10560
10561 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10562 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10563 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10564 if let Some(dir) = file.abs_path(cx).parent() {
10565 return Some(dir.to_owned());
10566 }
10567 }
10568
10569 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10570 return Some(project_path.path.to_path_buf());
10571 }
10572 }
10573
10574 None
10575 }
10576
10577 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10578 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10579 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10580 cx.reveal_path(&file.abs_path(cx));
10581 }
10582 }
10583 }
10584
10585 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10586 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10587 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10588 if let Some(path) = file.abs_path(cx).to_str() {
10589 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10590 }
10591 }
10592 }
10593 }
10594
10595 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10596 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10597 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10598 if let Some(path) = file.path().to_str() {
10599 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10600 }
10601 }
10602 }
10603 }
10604
10605 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10606 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10607
10608 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10609 self.start_git_blame(true, cx);
10610 }
10611
10612 cx.notify();
10613 }
10614
10615 pub fn toggle_git_blame_inline(
10616 &mut self,
10617 _: &ToggleGitBlameInline,
10618 cx: &mut ViewContext<Self>,
10619 ) {
10620 self.toggle_git_blame_inline_internal(true, cx);
10621 cx.notify();
10622 }
10623
10624 pub fn git_blame_inline_enabled(&self) -> bool {
10625 self.git_blame_inline_enabled
10626 }
10627
10628 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10629 self.show_selection_menu = self
10630 .show_selection_menu
10631 .map(|show_selections_menu| !show_selections_menu)
10632 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10633
10634 cx.notify();
10635 }
10636
10637 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10638 self.show_selection_menu
10639 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10640 }
10641
10642 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10643 if let Some(project) = self.project.as_ref() {
10644 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10645 return;
10646 };
10647
10648 if buffer.read(cx).file().is_none() {
10649 return;
10650 }
10651
10652 let focused = self.focus_handle(cx).contains_focused(cx);
10653
10654 let project = project.clone();
10655 let blame =
10656 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10657 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10658 self.blame = Some(blame);
10659 }
10660 }
10661
10662 fn toggle_git_blame_inline_internal(
10663 &mut self,
10664 user_triggered: bool,
10665 cx: &mut ViewContext<Self>,
10666 ) {
10667 if self.git_blame_inline_enabled {
10668 self.git_blame_inline_enabled = false;
10669 self.show_git_blame_inline = false;
10670 self.show_git_blame_inline_delay_task.take();
10671 } else {
10672 self.git_blame_inline_enabled = true;
10673 self.start_git_blame_inline(user_triggered, cx);
10674 }
10675
10676 cx.notify();
10677 }
10678
10679 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10680 self.start_git_blame(user_triggered, cx);
10681
10682 if ProjectSettings::get_global(cx)
10683 .git
10684 .inline_blame_delay()
10685 .is_some()
10686 {
10687 self.start_inline_blame_timer(cx);
10688 } else {
10689 self.show_git_blame_inline = true
10690 }
10691 }
10692
10693 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10694 self.blame.as_ref()
10695 }
10696
10697 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10698 self.show_git_blame_gutter && self.has_blame_entries(cx)
10699 }
10700
10701 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10702 self.show_git_blame_inline
10703 && self.focus_handle.is_focused(cx)
10704 && !self.newest_selection_head_on_empty_line(cx)
10705 && self.has_blame_entries(cx)
10706 }
10707
10708 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10709 self.blame()
10710 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10711 }
10712
10713 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10714 let cursor_anchor = self.selections.newest_anchor().head();
10715
10716 let snapshot = self.buffer.read(cx).snapshot(cx);
10717 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10718
10719 snapshot.line_len(buffer_row) == 0
10720 }
10721
10722 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10723 let (path, selection, repo) = maybe!({
10724 let project_handle = self.project.as_ref()?.clone();
10725 let project = project_handle.read(cx);
10726
10727 let selection = self.selections.newest::<Point>(cx);
10728 let selection_range = selection.range();
10729
10730 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10731 (buffer, selection_range.start.row..selection_range.end.row)
10732 } else {
10733 let buffer_ranges = self
10734 .buffer()
10735 .read(cx)
10736 .range_to_buffer_ranges(selection_range, cx);
10737
10738 let (buffer, range, _) = if selection.reversed {
10739 buffer_ranges.first()
10740 } else {
10741 buffer_ranges.last()
10742 }?;
10743
10744 let snapshot = buffer.read(cx).snapshot();
10745 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10746 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10747 (buffer.clone(), selection)
10748 };
10749
10750 let path = buffer
10751 .read(cx)
10752 .file()?
10753 .as_local()?
10754 .path()
10755 .to_str()?
10756 .to_string();
10757 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10758 Some((path, selection, repo))
10759 })
10760 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10761
10762 const REMOTE_NAME: &str = "origin";
10763 let origin_url = repo
10764 .remote_url(REMOTE_NAME)
10765 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10766 let sha = repo
10767 .head_sha()
10768 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10769
10770 let (provider, remote) =
10771 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10772 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10773
10774 Ok(provider.build_permalink(
10775 remote,
10776 BuildPermalinkParams {
10777 sha: &sha,
10778 path: &path,
10779 selection: Some(selection),
10780 },
10781 ))
10782 }
10783
10784 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10785 let permalink = self.get_permalink_to_line(cx);
10786
10787 match permalink {
10788 Ok(permalink) => {
10789 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
10790 }
10791 Err(err) => {
10792 let message = format!("Failed to copy permalink: {err}");
10793
10794 Err::<(), anyhow::Error>(err).log_err();
10795
10796 if let Some(workspace) = self.workspace() {
10797 workspace.update(cx, |workspace, cx| {
10798 struct CopyPermalinkToLine;
10799
10800 workspace.show_toast(
10801 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10802 cx,
10803 )
10804 })
10805 }
10806 }
10807 }
10808 }
10809
10810 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10811 let permalink = self.get_permalink_to_line(cx);
10812
10813 match permalink {
10814 Ok(permalink) => {
10815 cx.open_url(permalink.as_ref());
10816 }
10817 Err(err) => {
10818 let message = format!("Failed to open permalink: {err}");
10819
10820 Err::<(), anyhow::Error>(err).log_err();
10821
10822 if let Some(workspace) = self.workspace() {
10823 workspace.update(cx, |workspace, cx| {
10824 struct OpenPermalinkToLine;
10825
10826 workspace.show_toast(
10827 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10828 cx,
10829 )
10830 })
10831 }
10832 }
10833 }
10834 }
10835
10836 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10837 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10838 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10839 pub fn highlight_rows<T: 'static>(
10840 &mut self,
10841 rows: RangeInclusive<Anchor>,
10842 color: Option<Hsla>,
10843 should_autoscroll: bool,
10844 cx: &mut ViewContext<Self>,
10845 ) {
10846 let snapshot = self.buffer().read(cx).snapshot(cx);
10847 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10848 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10849 highlight
10850 .range
10851 .start()
10852 .cmp(&rows.start(), &snapshot)
10853 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10854 });
10855 match (color, existing_highlight_index) {
10856 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10857 ix,
10858 RowHighlight {
10859 index: post_inc(&mut self.highlight_order),
10860 range: rows,
10861 should_autoscroll,
10862 color,
10863 },
10864 ),
10865 (None, Ok(i)) => {
10866 row_highlights.remove(i);
10867 }
10868 }
10869 }
10870
10871 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10872 pub fn clear_row_highlights<T: 'static>(&mut self) {
10873 self.highlighted_rows.remove(&TypeId::of::<T>());
10874 }
10875
10876 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10877 pub fn highlighted_rows<T: 'static>(
10878 &self,
10879 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10880 Some(
10881 self.highlighted_rows
10882 .get(&TypeId::of::<T>())?
10883 .iter()
10884 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10885 )
10886 }
10887
10888 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10889 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10890 /// Allows to ignore certain kinds of highlights.
10891 pub fn highlighted_display_rows(
10892 &mut self,
10893 cx: &mut WindowContext,
10894 ) -> BTreeMap<DisplayRow, Hsla> {
10895 let snapshot = self.snapshot(cx);
10896 let mut used_highlight_orders = HashMap::default();
10897 self.highlighted_rows
10898 .iter()
10899 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10900 .fold(
10901 BTreeMap::<DisplayRow, Hsla>::new(),
10902 |mut unique_rows, highlight| {
10903 let start_row = highlight.range.start().to_display_point(&snapshot).row();
10904 let end_row = highlight.range.end().to_display_point(&snapshot).row();
10905 for row in start_row.0..=end_row.0 {
10906 let used_index =
10907 used_highlight_orders.entry(row).or_insert(highlight.index);
10908 if highlight.index >= *used_index {
10909 *used_index = highlight.index;
10910 match highlight.color {
10911 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10912 None => unique_rows.remove(&DisplayRow(row)),
10913 };
10914 }
10915 }
10916 unique_rows
10917 },
10918 )
10919 }
10920
10921 pub fn highlighted_display_row_for_autoscroll(
10922 &self,
10923 snapshot: &DisplaySnapshot,
10924 ) -> Option<DisplayRow> {
10925 self.highlighted_rows
10926 .values()
10927 .flat_map(|highlighted_rows| highlighted_rows.iter())
10928 .filter_map(|highlight| {
10929 if highlight.color.is_none() || !highlight.should_autoscroll {
10930 return None;
10931 }
10932 Some(highlight.range.start().to_display_point(&snapshot).row())
10933 })
10934 .min()
10935 }
10936
10937 pub fn set_search_within_ranges(
10938 &mut self,
10939 ranges: &[Range<Anchor>],
10940 cx: &mut ViewContext<Self>,
10941 ) {
10942 self.highlight_background::<SearchWithinRange>(
10943 ranges,
10944 |colors| colors.editor_document_highlight_read_background,
10945 cx,
10946 )
10947 }
10948
10949 pub fn set_breadcrumb_header(&mut self, new_header: String) {
10950 self.breadcrumb_header = Some(new_header);
10951 }
10952
10953 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10954 self.clear_background_highlights::<SearchWithinRange>(cx);
10955 }
10956
10957 pub fn highlight_background<T: 'static>(
10958 &mut self,
10959 ranges: &[Range<Anchor>],
10960 color_fetcher: fn(&ThemeColors) -> Hsla,
10961 cx: &mut ViewContext<Self>,
10962 ) {
10963 self.background_highlights
10964 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10965 self.scrollbar_marker_state.dirty = true;
10966 cx.notify();
10967 }
10968
10969 pub fn clear_background_highlights<T: 'static>(
10970 &mut self,
10971 cx: &mut ViewContext<Self>,
10972 ) -> Option<BackgroundHighlight> {
10973 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10974 if !text_highlights.1.is_empty() {
10975 self.scrollbar_marker_state.dirty = true;
10976 cx.notify();
10977 }
10978 Some(text_highlights)
10979 }
10980
10981 pub fn highlight_gutter<T: 'static>(
10982 &mut self,
10983 ranges: &[Range<Anchor>],
10984 color_fetcher: fn(&AppContext) -> Hsla,
10985 cx: &mut ViewContext<Self>,
10986 ) {
10987 self.gutter_highlights
10988 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10989 cx.notify();
10990 }
10991
10992 pub fn clear_gutter_highlights<T: 'static>(
10993 &mut self,
10994 cx: &mut ViewContext<Self>,
10995 ) -> Option<GutterHighlight> {
10996 cx.notify();
10997 self.gutter_highlights.remove(&TypeId::of::<T>())
10998 }
10999
11000 #[cfg(feature = "test-support")]
11001 pub fn all_text_background_highlights(
11002 &mut self,
11003 cx: &mut ViewContext<Self>,
11004 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11005 let snapshot = self.snapshot(cx);
11006 let buffer = &snapshot.buffer_snapshot;
11007 let start = buffer.anchor_before(0);
11008 let end = buffer.anchor_after(buffer.len());
11009 let theme = cx.theme().colors();
11010 self.background_highlights_in_range(start..end, &snapshot, theme)
11011 }
11012
11013 #[cfg(feature = "test-support")]
11014 pub fn search_background_highlights(
11015 &mut self,
11016 cx: &mut ViewContext<Self>,
11017 ) -> Vec<Range<Point>> {
11018 let snapshot = self.buffer().read(cx).snapshot(cx);
11019
11020 let highlights = self
11021 .background_highlights
11022 .get(&TypeId::of::<items::BufferSearchHighlights>());
11023
11024 if let Some((_color, ranges)) = highlights {
11025 ranges
11026 .iter()
11027 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11028 .collect_vec()
11029 } else {
11030 vec![]
11031 }
11032 }
11033
11034 fn document_highlights_for_position<'a>(
11035 &'a self,
11036 position: Anchor,
11037 buffer: &'a MultiBufferSnapshot,
11038 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11039 let read_highlights = self
11040 .background_highlights
11041 .get(&TypeId::of::<DocumentHighlightRead>())
11042 .map(|h| &h.1);
11043 let write_highlights = self
11044 .background_highlights
11045 .get(&TypeId::of::<DocumentHighlightWrite>())
11046 .map(|h| &h.1);
11047 let left_position = position.bias_left(buffer);
11048 let right_position = position.bias_right(buffer);
11049 read_highlights
11050 .into_iter()
11051 .chain(write_highlights)
11052 .flat_map(move |ranges| {
11053 let start_ix = match ranges.binary_search_by(|probe| {
11054 let cmp = probe.end.cmp(&left_position, buffer);
11055 if cmp.is_ge() {
11056 Ordering::Greater
11057 } else {
11058 Ordering::Less
11059 }
11060 }) {
11061 Ok(i) | Err(i) => i,
11062 };
11063
11064 ranges[start_ix..]
11065 .iter()
11066 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11067 })
11068 }
11069
11070 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11071 self.background_highlights
11072 .get(&TypeId::of::<T>())
11073 .map_or(false, |(_, highlights)| !highlights.is_empty())
11074 }
11075
11076 pub fn background_highlights_in_range(
11077 &self,
11078 search_range: Range<Anchor>,
11079 display_snapshot: &DisplaySnapshot,
11080 theme: &ThemeColors,
11081 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11082 let mut results = Vec::new();
11083 for (color_fetcher, ranges) in self.background_highlights.values() {
11084 let color = color_fetcher(theme);
11085 let start_ix = match ranges.binary_search_by(|probe| {
11086 let cmp = probe
11087 .end
11088 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11089 if cmp.is_gt() {
11090 Ordering::Greater
11091 } else {
11092 Ordering::Less
11093 }
11094 }) {
11095 Ok(i) | Err(i) => i,
11096 };
11097 for range in &ranges[start_ix..] {
11098 if range
11099 .start
11100 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11101 .is_ge()
11102 {
11103 break;
11104 }
11105
11106 let start = range.start.to_display_point(&display_snapshot);
11107 let end = range.end.to_display_point(&display_snapshot);
11108 results.push((start..end, color))
11109 }
11110 }
11111 results
11112 }
11113
11114 pub fn background_highlight_row_ranges<T: 'static>(
11115 &self,
11116 search_range: Range<Anchor>,
11117 display_snapshot: &DisplaySnapshot,
11118 count: usize,
11119 ) -> Vec<RangeInclusive<DisplayPoint>> {
11120 let mut results = Vec::new();
11121 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11122 return vec![];
11123 };
11124
11125 let start_ix = match ranges.binary_search_by(|probe| {
11126 let cmp = probe
11127 .end
11128 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11129 if cmp.is_gt() {
11130 Ordering::Greater
11131 } else {
11132 Ordering::Less
11133 }
11134 }) {
11135 Ok(i) | Err(i) => i,
11136 };
11137 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11138 if let (Some(start_display), Some(end_display)) = (start, end) {
11139 results.push(
11140 start_display.to_display_point(display_snapshot)
11141 ..=end_display.to_display_point(display_snapshot),
11142 );
11143 }
11144 };
11145 let mut start_row: Option<Point> = None;
11146 let mut end_row: Option<Point> = None;
11147 if ranges.len() > count {
11148 return Vec::new();
11149 }
11150 for range in &ranges[start_ix..] {
11151 if range
11152 .start
11153 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11154 .is_ge()
11155 {
11156 break;
11157 }
11158 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11159 if let Some(current_row) = &end_row {
11160 if end.row == current_row.row {
11161 continue;
11162 }
11163 }
11164 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11165 if start_row.is_none() {
11166 assert_eq!(end_row, None);
11167 start_row = Some(start);
11168 end_row = Some(end);
11169 continue;
11170 }
11171 if let Some(current_end) = end_row.as_mut() {
11172 if start.row > current_end.row + 1 {
11173 push_region(start_row, end_row);
11174 start_row = Some(start);
11175 end_row = Some(end);
11176 } else {
11177 // Merge two hunks.
11178 *current_end = end;
11179 }
11180 } else {
11181 unreachable!();
11182 }
11183 }
11184 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11185 push_region(start_row, end_row);
11186 results
11187 }
11188
11189 pub fn gutter_highlights_in_range(
11190 &self,
11191 search_range: Range<Anchor>,
11192 display_snapshot: &DisplaySnapshot,
11193 cx: &AppContext,
11194 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11195 let mut results = Vec::new();
11196 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11197 let color = color_fetcher(cx);
11198 let start_ix = match ranges.binary_search_by(|probe| {
11199 let cmp = probe
11200 .end
11201 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11202 if cmp.is_gt() {
11203 Ordering::Greater
11204 } else {
11205 Ordering::Less
11206 }
11207 }) {
11208 Ok(i) | Err(i) => i,
11209 };
11210 for range in &ranges[start_ix..] {
11211 if range
11212 .start
11213 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11214 .is_ge()
11215 {
11216 break;
11217 }
11218
11219 let start = range.start.to_display_point(&display_snapshot);
11220 let end = range.end.to_display_point(&display_snapshot);
11221 results.push((start..end, color))
11222 }
11223 }
11224 results
11225 }
11226
11227 /// Get the text ranges corresponding to the redaction query
11228 pub fn redacted_ranges(
11229 &self,
11230 search_range: Range<Anchor>,
11231 display_snapshot: &DisplaySnapshot,
11232 cx: &WindowContext,
11233 ) -> Vec<Range<DisplayPoint>> {
11234 display_snapshot
11235 .buffer_snapshot
11236 .redacted_ranges(search_range, |file| {
11237 if let Some(file) = file {
11238 file.is_private()
11239 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11240 } else {
11241 false
11242 }
11243 })
11244 .map(|range| {
11245 range.start.to_display_point(display_snapshot)
11246 ..range.end.to_display_point(display_snapshot)
11247 })
11248 .collect()
11249 }
11250
11251 pub fn highlight_text<T: 'static>(
11252 &mut self,
11253 ranges: Vec<Range<Anchor>>,
11254 style: HighlightStyle,
11255 cx: &mut ViewContext<Self>,
11256 ) {
11257 self.display_map.update(cx, |map, _| {
11258 map.highlight_text(TypeId::of::<T>(), ranges, style)
11259 });
11260 cx.notify();
11261 }
11262
11263 pub(crate) fn highlight_inlays<T: 'static>(
11264 &mut self,
11265 highlights: Vec<InlayHighlight>,
11266 style: HighlightStyle,
11267 cx: &mut ViewContext<Self>,
11268 ) {
11269 self.display_map.update(cx, |map, _| {
11270 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11271 });
11272 cx.notify();
11273 }
11274
11275 pub fn text_highlights<'a, T: 'static>(
11276 &'a self,
11277 cx: &'a AppContext,
11278 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11279 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11280 }
11281
11282 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11283 let cleared = self
11284 .display_map
11285 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11286 if cleared {
11287 cx.notify();
11288 }
11289 }
11290
11291 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11292 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11293 && self.focus_handle.is_focused(cx)
11294 }
11295
11296 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11297 self.show_cursor_when_unfocused = is_enabled;
11298 cx.notify();
11299 }
11300
11301 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11302 cx.notify();
11303 }
11304
11305 fn on_buffer_event(
11306 &mut self,
11307 multibuffer: Model<MultiBuffer>,
11308 event: &multi_buffer::Event,
11309 cx: &mut ViewContext<Self>,
11310 ) {
11311 match event {
11312 multi_buffer::Event::Edited {
11313 singleton_buffer_edited,
11314 } => {
11315 self.scrollbar_marker_state.dirty = true;
11316 self.active_indent_guides_state.dirty = true;
11317 self.refresh_active_diagnostics(cx);
11318 self.refresh_code_actions(cx);
11319 if self.has_active_inline_completion(cx) {
11320 self.update_visible_inline_completion(cx);
11321 }
11322 cx.emit(EditorEvent::BufferEdited);
11323 cx.emit(SearchEvent::MatchesInvalidated);
11324 if *singleton_buffer_edited {
11325 if let Some(project) = &self.project {
11326 let project = project.read(cx);
11327 #[allow(clippy::mutable_key_type)]
11328 let languages_affected = multibuffer
11329 .read(cx)
11330 .all_buffers()
11331 .into_iter()
11332 .filter_map(|buffer| {
11333 let buffer = buffer.read(cx);
11334 let language = buffer.language()?;
11335 if project.is_local()
11336 && project.language_servers_for_buffer(buffer, cx).count() == 0
11337 {
11338 None
11339 } else {
11340 Some(language)
11341 }
11342 })
11343 .cloned()
11344 .collect::<HashSet<_>>();
11345 if !languages_affected.is_empty() {
11346 self.refresh_inlay_hints(
11347 InlayHintRefreshReason::BufferEdited(languages_affected),
11348 cx,
11349 );
11350 }
11351 }
11352 }
11353
11354 let Some(project) = &self.project else { return };
11355 let telemetry = project.read(cx).client().telemetry().clone();
11356 refresh_linked_ranges(self, cx);
11357 telemetry.log_edit_event("editor");
11358 }
11359 multi_buffer::Event::ExcerptsAdded {
11360 buffer,
11361 predecessor,
11362 excerpts,
11363 } => {
11364 self.tasks_update_task = Some(self.refresh_runnables(cx));
11365 cx.emit(EditorEvent::ExcerptsAdded {
11366 buffer: buffer.clone(),
11367 predecessor: *predecessor,
11368 excerpts: excerpts.clone(),
11369 });
11370 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11371 }
11372 multi_buffer::Event::ExcerptsRemoved { ids } => {
11373 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11374 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11375 }
11376 multi_buffer::Event::ExcerptsEdited { ids } => {
11377 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11378 }
11379 multi_buffer::Event::ExcerptsExpanded { ids } => {
11380 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11381 }
11382 multi_buffer::Event::Reparsed(buffer_id) => {
11383 self.tasks_update_task = Some(self.refresh_runnables(cx));
11384
11385 cx.emit(EditorEvent::Reparsed(*buffer_id));
11386 }
11387 multi_buffer::Event::LanguageChanged(buffer_id) => {
11388 linked_editing_ranges::refresh_linked_ranges(self, cx);
11389 cx.emit(EditorEvent::Reparsed(*buffer_id));
11390 cx.notify();
11391 }
11392 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11393 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11394 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11395 cx.emit(EditorEvent::TitleChanged)
11396 }
11397 multi_buffer::Event::DiffBaseChanged => {
11398 self.scrollbar_marker_state.dirty = true;
11399 cx.emit(EditorEvent::DiffBaseChanged);
11400 cx.notify();
11401 }
11402 multi_buffer::Event::DiffUpdated { buffer } => {
11403 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11404 cx.notify();
11405 }
11406 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11407 multi_buffer::Event::DiagnosticsUpdated => {
11408 self.refresh_active_diagnostics(cx);
11409 self.scrollbar_marker_state.dirty = true;
11410 cx.notify();
11411 }
11412 _ => {}
11413 };
11414 }
11415
11416 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11417 cx.notify();
11418 }
11419
11420 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11421 self.tasks_update_task = Some(self.refresh_runnables(cx));
11422 self.refresh_inline_completion(true, cx);
11423 self.refresh_inlay_hints(
11424 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11425 self.selections.newest_anchor().head(),
11426 &self.buffer.read(cx).snapshot(cx),
11427 cx,
11428 )),
11429 cx,
11430 );
11431 let editor_settings = EditorSettings::get_global(cx);
11432 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11433 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11434
11435 let project_settings = ProjectSettings::get_global(cx);
11436 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11437
11438 if self.mode == EditorMode::Full {
11439 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11440 if self.git_blame_inline_enabled != inline_blame_enabled {
11441 self.toggle_git_blame_inline_internal(false, cx);
11442 }
11443 }
11444
11445 cx.notify();
11446 }
11447
11448 pub fn set_searchable(&mut self, searchable: bool) {
11449 self.searchable = searchable;
11450 }
11451
11452 pub fn searchable(&self) -> bool {
11453 self.searchable
11454 }
11455
11456 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11457 self.open_excerpts_common(true, cx)
11458 }
11459
11460 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11461 self.open_excerpts_common(false, cx)
11462 }
11463
11464 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11465 let buffer = self.buffer.read(cx);
11466 if buffer.is_singleton() {
11467 cx.propagate();
11468 return;
11469 }
11470
11471 let Some(workspace) = self.workspace() else {
11472 cx.propagate();
11473 return;
11474 };
11475
11476 let mut new_selections_by_buffer = HashMap::default();
11477 for selection in self.selections.all::<usize>(cx) {
11478 for (buffer, mut range, _) in
11479 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11480 {
11481 if selection.reversed {
11482 mem::swap(&mut range.start, &mut range.end);
11483 }
11484 new_selections_by_buffer
11485 .entry(buffer)
11486 .or_insert(Vec::new())
11487 .push(range)
11488 }
11489 }
11490
11491 // We defer the pane interaction because we ourselves are a workspace item
11492 // and activating a new item causes the pane to call a method on us reentrantly,
11493 // which panics if we're on the stack.
11494 cx.window_context().defer(move |cx| {
11495 workspace.update(cx, |workspace, cx| {
11496 let pane = if split {
11497 workspace.adjacent_pane(cx)
11498 } else {
11499 workspace.active_pane().clone()
11500 };
11501
11502 for (buffer, ranges) in new_selections_by_buffer {
11503 let editor =
11504 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11505 editor.update(cx, |editor, cx| {
11506 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11507 s.select_ranges(ranges);
11508 });
11509 });
11510 }
11511 })
11512 });
11513 }
11514
11515 fn jump(
11516 &mut self,
11517 path: ProjectPath,
11518 position: Point,
11519 anchor: language::Anchor,
11520 offset_from_top: u32,
11521 cx: &mut ViewContext<Self>,
11522 ) {
11523 let workspace = self.workspace();
11524 cx.spawn(|_, mut cx| async move {
11525 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11526 let editor = workspace.update(&mut cx, |workspace, cx| {
11527 // Reset the preview item id before opening the new item
11528 workspace.active_pane().update(cx, |pane, cx| {
11529 pane.set_preview_item_id(None, cx);
11530 });
11531 workspace.open_path_preview(path, None, true, true, cx)
11532 })?;
11533 let editor = editor
11534 .await?
11535 .downcast::<Editor>()
11536 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11537 .downgrade();
11538 editor.update(&mut cx, |editor, cx| {
11539 let buffer = editor
11540 .buffer()
11541 .read(cx)
11542 .as_singleton()
11543 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11544 let buffer = buffer.read(cx);
11545 let cursor = if buffer.can_resolve(&anchor) {
11546 language::ToPoint::to_point(&anchor, buffer)
11547 } else {
11548 buffer.clip_point(position, Bias::Left)
11549 };
11550
11551 let nav_history = editor.nav_history.take();
11552 editor.change_selections(
11553 Some(Autoscroll::top_relative(offset_from_top as usize)),
11554 cx,
11555 |s| {
11556 s.select_ranges([cursor..cursor]);
11557 },
11558 );
11559 editor.nav_history = nav_history;
11560
11561 anyhow::Ok(())
11562 })??;
11563
11564 anyhow::Ok(())
11565 })
11566 .detach_and_log_err(cx);
11567 }
11568
11569 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11570 let snapshot = self.buffer.read(cx).read(cx);
11571 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11572 Some(
11573 ranges
11574 .iter()
11575 .map(move |range| {
11576 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11577 })
11578 .collect(),
11579 )
11580 }
11581
11582 fn selection_replacement_ranges(
11583 &self,
11584 range: Range<OffsetUtf16>,
11585 cx: &AppContext,
11586 ) -> Vec<Range<OffsetUtf16>> {
11587 let selections = self.selections.all::<OffsetUtf16>(cx);
11588 let newest_selection = selections
11589 .iter()
11590 .max_by_key(|selection| selection.id)
11591 .unwrap();
11592 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11593 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11594 let snapshot = self.buffer.read(cx).read(cx);
11595 selections
11596 .into_iter()
11597 .map(|mut selection| {
11598 selection.start.0 =
11599 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11600 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11601 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11602 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11603 })
11604 .collect()
11605 }
11606
11607 fn report_editor_event(
11608 &self,
11609 operation: &'static str,
11610 file_extension: Option<String>,
11611 cx: &AppContext,
11612 ) {
11613 if cfg!(any(test, feature = "test-support")) {
11614 return;
11615 }
11616
11617 let Some(project) = &self.project else { return };
11618
11619 // If None, we are in a file without an extension
11620 let file = self
11621 .buffer
11622 .read(cx)
11623 .as_singleton()
11624 .and_then(|b| b.read(cx).file());
11625 let file_extension = file_extension.or(file
11626 .as_ref()
11627 .and_then(|file| Path::new(file.file_name(cx)).extension())
11628 .and_then(|e| e.to_str())
11629 .map(|a| a.to_string()));
11630
11631 let vim_mode = cx
11632 .global::<SettingsStore>()
11633 .raw_user_settings()
11634 .get("vim_mode")
11635 == Some(&serde_json::Value::Bool(true));
11636
11637 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11638 == language::language_settings::InlineCompletionProvider::Copilot;
11639 let copilot_enabled_for_language = self
11640 .buffer
11641 .read(cx)
11642 .settings_at(0, cx)
11643 .show_inline_completions;
11644
11645 let telemetry = project.read(cx).client().telemetry().clone();
11646 telemetry.report_editor_event(
11647 file_extension,
11648 vim_mode,
11649 operation,
11650 copilot_enabled,
11651 copilot_enabled_for_language,
11652 )
11653 }
11654
11655 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11656 /// with each line being an array of {text, highlight} objects.
11657 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11658 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11659 return;
11660 };
11661
11662 #[derive(Serialize)]
11663 struct Chunk<'a> {
11664 text: String,
11665 highlight: Option<&'a str>,
11666 }
11667
11668 let snapshot = buffer.read(cx).snapshot();
11669 let range = self
11670 .selected_text_range(cx)
11671 .and_then(|selected_range| {
11672 if selected_range.is_empty() {
11673 None
11674 } else {
11675 Some(selected_range)
11676 }
11677 })
11678 .unwrap_or_else(|| 0..snapshot.len());
11679
11680 let chunks = snapshot.chunks(range, true);
11681 let mut lines = Vec::new();
11682 let mut line: VecDeque<Chunk> = VecDeque::new();
11683
11684 let Some(style) = self.style.as_ref() else {
11685 return;
11686 };
11687
11688 for chunk in chunks {
11689 let highlight = chunk
11690 .syntax_highlight_id
11691 .and_then(|id| id.name(&style.syntax));
11692 let mut chunk_lines = chunk.text.split('\n').peekable();
11693 while let Some(text) = chunk_lines.next() {
11694 let mut merged_with_last_token = false;
11695 if let Some(last_token) = line.back_mut() {
11696 if last_token.highlight == highlight {
11697 last_token.text.push_str(text);
11698 merged_with_last_token = true;
11699 }
11700 }
11701
11702 if !merged_with_last_token {
11703 line.push_back(Chunk {
11704 text: text.into(),
11705 highlight,
11706 });
11707 }
11708
11709 if chunk_lines.peek().is_some() {
11710 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11711 line.pop_front();
11712 }
11713 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11714 line.pop_back();
11715 }
11716
11717 lines.push(mem::take(&mut line));
11718 }
11719 }
11720 }
11721
11722 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11723 return;
11724 };
11725 cx.write_to_clipboard(ClipboardItem::new_string(lines));
11726 }
11727
11728 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11729 &self.inlay_hint_cache
11730 }
11731
11732 pub fn replay_insert_event(
11733 &mut self,
11734 text: &str,
11735 relative_utf16_range: Option<Range<isize>>,
11736 cx: &mut ViewContext<Self>,
11737 ) {
11738 if !self.input_enabled {
11739 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11740 return;
11741 }
11742 if let Some(relative_utf16_range) = relative_utf16_range {
11743 let selections = self.selections.all::<OffsetUtf16>(cx);
11744 self.change_selections(None, cx, |s| {
11745 let new_ranges = selections.into_iter().map(|range| {
11746 let start = OffsetUtf16(
11747 range
11748 .head()
11749 .0
11750 .saturating_add_signed(relative_utf16_range.start),
11751 );
11752 let end = OffsetUtf16(
11753 range
11754 .head()
11755 .0
11756 .saturating_add_signed(relative_utf16_range.end),
11757 );
11758 start..end
11759 });
11760 s.select_ranges(new_ranges);
11761 });
11762 }
11763
11764 self.handle_input(text, cx);
11765 }
11766
11767 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11768 let Some(project) = self.project.as_ref() else {
11769 return false;
11770 };
11771 let project = project.read(cx);
11772
11773 let mut supports = false;
11774 self.buffer().read(cx).for_each_buffer(|buffer| {
11775 if !supports {
11776 supports = project
11777 .language_servers_for_buffer(buffer.read(cx), cx)
11778 .any(
11779 |(_, server)| match server.capabilities().inlay_hint_provider {
11780 Some(lsp::OneOf::Left(enabled)) => enabled,
11781 Some(lsp::OneOf::Right(_)) => true,
11782 None => false,
11783 },
11784 )
11785 }
11786 });
11787 supports
11788 }
11789
11790 pub fn focus(&self, cx: &mut WindowContext) {
11791 cx.focus(&self.focus_handle)
11792 }
11793
11794 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11795 self.focus_handle.is_focused(cx)
11796 }
11797
11798 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11799 cx.emit(EditorEvent::Focused);
11800
11801 if let Some(descendant) = self
11802 .last_focused_descendant
11803 .take()
11804 .and_then(|descendant| descendant.upgrade())
11805 {
11806 cx.focus(&descendant);
11807 } else {
11808 if let Some(blame) = self.blame.as_ref() {
11809 blame.update(cx, GitBlame::focus)
11810 }
11811
11812 self.blink_manager.update(cx, BlinkManager::enable);
11813 self.show_cursor_names(cx);
11814 self.buffer.update(cx, |buffer, cx| {
11815 buffer.finalize_last_transaction(cx);
11816 if self.leader_peer_id.is_none() {
11817 buffer.set_active_selections(
11818 &self.selections.disjoint_anchors(),
11819 self.selections.line_mode,
11820 self.cursor_shape,
11821 cx,
11822 );
11823 }
11824 });
11825 }
11826 }
11827
11828 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11829 cx.emit(EditorEvent::FocusedIn)
11830 }
11831
11832 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11833 if event.blurred != self.focus_handle {
11834 self.last_focused_descendant = Some(event.blurred);
11835 }
11836 }
11837
11838 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11839 self.blink_manager.update(cx, BlinkManager::disable);
11840 self.buffer
11841 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11842
11843 if let Some(blame) = self.blame.as_ref() {
11844 blame.update(cx, GitBlame::blur)
11845 }
11846 if !self.hover_state.focused(cx) {
11847 hide_hover(self, cx);
11848 }
11849
11850 self.hide_context_menu(cx);
11851 cx.emit(EditorEvent::Blurred);
11852 cx.notify();
11853 }
11854
11855 pub fn register_action<A: Action>(
11856 &mut self,
11857 listener: impl Fn(&A, &mut WindowContext) + 'static,
11858 ) -> Subscription {
11859 let id = self.next_editor_action_id.post_inc();
11860 let listener = Arc::new(listener);
11861 self.editor_actions.borrow_mut().insert(
11862 id,
11863 Box::new(move |cx| {
11864 let _view = cx.view().clone();
11865 let cx = cx.window_context();
11866 let listener = listener.clone();
11867 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11868 let action = action.downcast_ref().unwrap();
11869 if phase == DispatchPhase::Bubble {
11870 listener(action, cx)
11871 }
11872 })
11873 }),
11874 );
11875
11876 let editor_actions = self.editor_actions.clone();
11877 Subscription::new(move || {
11878 editor_actions.borrow_mut().remove(&id);
11879 })
11880 }
11881
11882 pub fn file_header_size(&self) -> u32 {
11883 self.file_header_size
11884 }
11885
11886 pub fn revert(
11887 &mut self,
11888 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
11889 cx: &mut ViewContext<Self>,
11890 ) {
11891 self.buffer().update(cx, |multi_buffer, cx| {
11892 for (buffer_id, changes) in revert_changes {
11893 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
11894 buffer.update(cx, |buffer, cx| {
11895 buffer.edit(
11896 changes.into_iter().map(|(range, text)| {
11897 (range, text.to_string().map(Arc::<str>::from))
11898 }),
11899 None,
11900 cx,
11901 );
11902 });
11903 }
11904 }
11905 });
11906 self.change_selections(None, cx, |selections| selections.refresh());
11907 }
11908
11909 pub fn to_pixel_point(
11910 &mut self,
11911 source: multi_buffer::Anchor,
11912 editor_snapshot: &EditorSnapshot,
11913 cx: &mut ViewContext<Self>,
11914 ) -> Option<gpui::Point<Pixels>> {
11915 let source_point = source.to_display_point(editor_snapshot);
11916 self.display_to_pixel_point(source_point, editor_snapshot, cx)
11917 }
11918
11919 pub fn display_to_pixel_point(
11920 &mut self,
11921 source: DisplayPoint,
11922 editor_snapshot: &EditorSnapshot,
11923 cx: &mut ViewContext<Self>,
11924 ) -> Option<gpui::Point<Pixels>> {
11925 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
11926 let text_layout_details = self.text_layout_details(cx);
11927 let scroll_top = text_layout_details
11928 .scroll_anchor
11929 .scroll_position(editor_snapshot)
11930 .y;
11931
11932 if source.row().as_f32() < scroll_top.floor() {
11933 return None;
11934 }
11935 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
11936 let source_y = line_height * (source.row().as_f32() - scroll_top);
11937 Some(gpui::Point::new(source_x, source_y))
11938 }
11939
11940 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
11941 let bounds = self.last_bounds?;
11942 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
11943 }
11944
11945 pub fn has_active_completions_menu(&self) -> bool {
11946 self.context_menu.read().as_ref().map_or(false, |menu| {
11947 menu.visible() && matches!(menu, ContextMenu::Completions(_))
11948 })
11949 }
11950}
11951
11952fn hunks_for_selections(
11953 multi_buffer_snapshot: &MultiBufferSnapshot,
11954 selections: &[Selection<Anchor>],
11955) -> Vec<DiffHunk<MultiBufferRow>> {
11956 let buffer_rows_for_selections = selections.iter().map(|selection| {
11957 let head = selection.head();
11958 let tail = selection.tail();
11959 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11960 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11961 if start > end {
11962 end..start
11963 } else {
11964 start..end
11965 }
11966 });
11967
11968 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
11969}
11970
11971pub fn hunks_for_rows(
11972 rows: impl Iterator<Item = Range<MultiBufferRow>>,
11973 multi_buffer_snapshot: &MultiBufferSnapshot,
11974) -> Vec<DiffHunk<MultiBufferRow>> {
11975 let mut hunks = Vec::new();
11976 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11977 HashMap::default();
11978 for selected_multi_buffer_rows in rows {
11979 let query_rows =
11980 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11981 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11982 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11983 // when the caret is just above or just below the deleted hunk.
11984 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11985 let related_to_selection = if allow_adjacent {
11986 hunk.associated_range.overlaps(&query_rows)
11987 || hunk.associated_range.start == query_rows.end
11988 || hunk.associated_range.end == query_rows.start
11989 } else {
11990 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11991 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11992 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11993 || selected_multi_buffer_rows.end == hunk.associated_range.start
11994 };
11995 if related_to_selection {
11996 if !processed_buffer_rows
11997 .entry(hunk.buffer_id)
11998 .or_default()
11999 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12000 {
12001 continue;
12002 }
12003 hunks.push(hunk);
12004 }
12005 }
12006 }
12007
12008 hunks
12009}
12010
12011pub trait CollaborationHub {
12012 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12013 fn user_participant_indices<'a>(
12014 &self,
12015 cx: &'a AppContext,
12016 ) -> &'a HashMap<u64, ParticipantIndex>;
12017 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12018}
12019
12020impl CollaborationHub for Model<Project> {
12021 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12022 self.read(cx).collaborators()
12023 }
12024
12025 fn user_participant_indices<'a>(
12026 &self,
12027 cx: &'a AppContext,
12028 ) -> &'a HashMap<u64, ParticipantIndex> {
12029 self.read(cx).user_store().read(cx).participant_indices()
12030 }
12031
12032 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12033 let this = self.read(cx);
12034 let user_ids = this.collaborators().values().map(|c| c.user_id);
12035 this.user_store().read_with(cx, |user_store, cx| {
12036 user_store.participant_names(user_ids, cx)
12037 })
12038 }
12039}
12040
12041pub trait CompletionProvider {
12042 fn completions(
12043 &self,
12044 buffer: &Model<Buffer>,
12045 buffer_position: text::Anchor,
12046 trigger: CompletionContext,
12047 cx: &mut ViewContext<Editor>,
12048 ) -> Task<Result<Vec<Completion>>>;
12049
12050 fn resolve_completions(
12051 &self,
12052 buffer: Model<Buffer>,
12053 completion_indices: Vec<usize>,
12054 completions: Arc<RwLock<Box<[Completion]>>>,
12055 cx: &mut ViewContext<Editor>,
12056 ) -> Task<Result<bool>>;
12057
12058 fn apply_additional_edits_for_completion(
12059 &self,
12060 buffer: Model<Buffer>,
12061 completion: Completion,
12062 push_to_history: bool,
12063 cx: &mut ViewContext<Editor>,
12064 ) -> Task<Result<Option<language::Transaction>>>;
12065
12066 fn is_completion_trigger(
12067 &self,
12068 buffer: &Model<Buffer>,
12069 position: language::Anchor,
12070 text: &str,
12071 trigger_in_words: bool,
12072 cx: &mut ViewContext<Editor>,
12073 ) -> bool;
12074
12075 fn sort_completions(&self) -> bool {
12076 true
12077 }
12078}
12079
12080fn snippet_completions(
12081 project: &Project,
12082 buffer: &Model<Buffer>,
12083 buffer_position: text::Anchor,
12084 cx: &mut AppContext,
12085) -> Vec<Completion> {
12086 let language = buffer.read(cx).language_at(buffer_position);
12087 let language_name = language.as_ref().map(|language| language.lsp_id());
12088 let snippet_store = project.snippets().read(cx);
12089 let snippets = snippet_store.snippets_for(language_name, cx);
12090
12091 if snippets.is_empty() {
12092 return vec![];
12093 }
12094 let snapshot = buffer.read(cx).text_snapshot();
12095 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12096
12097 let mut lines = chunks.lines();
12098 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12099 return vec![];
12100 };
12101
12102 let scope = language.map(|language| language.default_scope());
12103 let mut last_word = line_at
12104 .chars()
12105 .rev()
12106 .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
12107 .collect::<String>();
12108 last_word = last_word.chars().rev().collect();
12109 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12110 let to_lsp = |point: &text::Anchor| {
12111 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12112 point_to_lsp(end)
12113 };
12114 let lsp_end = to_lsp(&buffer_position);
12115 snippets
12116 .into_iter()
12117 .filter_map(|snippet| {
12118 let matching_prefix = snippet
12119 .prefix
12120 .iter()
12121 .find(|prefix| prefix.starts_with(&last_word))?;
12122 let start = as_offset - last_word.len();
12123 let start = snapshot.anchor_before(start);
12124 let range = start..buffer_position;
12125 let lsp_start = to_lsp(&start);
12126 let lsp_range = lsp::Range {
12127 start: lsp_start,
12128 end: lsp_end,
12129 };
12130 Some(Completion {
12131 old_range: range,
12132 new_text: snippet.body.clone(),
12133 label: CodeLabel {
12134 text: matching_prefix.clone(),
12135 runs: vec![],
12136 filter_range: 0..matching_prefix.len(),
12137 },
12138 server_id: LanguageServerId(usize::MAX),
12139 documentation: snippet
12140 .description
12141 .clone()
12142 .map(|description| Documentation::SingleLine(description)),
12143 lsp_completion: lsp::CompletionItem {
12144 label: snippet.prefix.first().unwrap().clone(),
12145 kind: Some(CompletionItemKind::SNIPPET),
12146 label_details: snippet.description.as_ref().map(|description| {
12147 lsp::CompletionItemLabelDetails {
12148 detail: Some(description.clone()),
12149 description: None,
12150 }
12151 }),
12152 insert_text_format: Some(InsertTextFormat::SNIPPET),
12153 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12154 lsp::InsertReplaceEdit {
12155 new_text: snippet.body.clone(),
12156 insert: lsp_range,
12157 replace: lsp_range,
12158 },
12159 )),
12160 filter_text: Some(snippet.body.clone()),
12161 sort_text: Some(char::MAX.to_string()),
12162 ..Default::default()
12163 },
12164 confirm: None,
12165 })
12166 })
12167 .collect()
12168}
12169
12170impl CompletionProvider for Model<Project> {
12171 fn completions(
12172 &self,
12173 buffer: &Model<Buffer>,
12174 buffer_position: text::Anchor,
12175 options: CompletionContext,
12176 cx: &mut ViewContext<Editor>,
12177 ) -> Task<Result<Vec<Completion>>> {
12178 self.update(cx, |project, cx| {
12179 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12180 let project_completions = project.completions(&buffer, buffer_position, options, cx);
12181 cx.background_executor().spawn(async move {
12182 let mut completions = project_completions.await?;
12183 //let snippets = snippets.into_iter().;
12184 completions.extend(snippets);
12185 Ok(completions)
12186 })
12187 })
12188 }
12189
12190 fn resolve_completions(
12191 &self,
12192 buffer: Model<Buffer>,
12193 completion_indices: Vec<usize>,
12194 completions: Arc<RwLock<Box<[Completion]>>>,
12195 cx: &mut ViewContext<Editor>,
12196 ) -> Task<Result<bool>> {
12197 self.update(cx, |project, cx| {
12198 project.resolve_completions(buffer, completion_indices, completions, cx)
12199 })
12200 }
12201
12202 fn apply_additional_edits_for_completion(
12203 &self,
12204 buffer: Model<Buffer>,
12205 completion: Completion,
12206 push_to_history: bool,
12207 cx: &mut ViewContext<Editor>,
12208 ) -> Task<Result<Option<language::Transaction>>> {
12209 self.update(cx, |project, cx| {
12210 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12211 })
12212 }
12213
12214 fn is_completion_trigger(
12215 &self,
12216 buffer: &Model<Buffer>,
12217 position: language::Anchor,
12218 text: &str,
12219 trigger_in_words: bool,
12220 cx: &mut ViewContext<Editor>,
12221 ) -> bool {
12222 if !EditorSettings::get_global(cx).show_completions_on_input {
12223 return false;
12224 }
12225
12226 let mut chars = text.chars();
12227 let char = if let Some(char) = chars.next() {
12228 char
12229 } else {
12230 return false;
12231 };
12232 if chars.next().is_some() {
12233 return false;
12234 }
12235
12236 let buffer = buffer.read(cx);
12237 let scope = buffer.snapshot().language_scope_at(position);
12238 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12239 return true;
12240 }
12241
12242 buffer
12243 .completion_triggers()
12244 .iter()
12245 .any(|string| string == text)
12246 }
12247}
12248
12249fn inlay_hint_settings(
12250 location: Anchor,
12251 snapshot: &MultiBufferSnapshot,
12252 cx: &mut ViewContext<'_, Editor>,
12253) -> InlayHintSettings {
12254 let file = snapshot.file_at(location);
12255 let language = snapshot.language_at(location);
12256 let settings = all_language_settings(file, cx);
12257 settings
12258 .language(language.map(|l| l.name()).as_deref())
12259 .inlay_hints
12260}
12261
12262fn consume_contiguous_rows(
12263 contiguous_row_selections: &mut Vec<Selection<Point>>,
12264 selection: &Selection<Point>,
12265 display_map: &DisplaySnapshot,
12266 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12267) -> (MultiBufferRow, MultiBufferRow) {
12268 contiguous_row_selections.push(selection.clone());
12269 let start_row = MultiBufferRow(selection.start.row);
12270 let mut end_row = ending_row(selection, display_map);
12271
12272 while let Some(next_selection) = selections.peek() {
12273 if next_selection.start.row <= end_row.0 {
12274 end_row = ending_row(next_selection, display_map);
12275 contiguous_row_selections.push(selections.next().unwrap().clone());
12276 } else {
12277 break;
12278 }
12279 }
12280 (start_row, end_row)
12281}
12282
12283fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12284 if next_selection.end.column > 0 || next_selection.is_empty() {
12285 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12286 } else {
12287 MultiBufferRow(next_selection.end.row)
12288 }
12289}
12290
12291impl EditorSnapshot {
12292 pub fn remote_selections_in_range<'a>(
12293 &'a self,
12294 range: &'a Range<Anchor>,
12295 collaboration_hub: &dyn CollaborationHub,
12296 cx: &'a AppContext,
12297 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12298 let participant_names = collaboration_hub.user_names(cx);
12299 let participant_indices = collaboration_hub.user_participant_indices(cx);
12300 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12301 let collaborators_by_replica_id = collaborators_by_peer_id
12302 .iter()
12303 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12304 .collect::<HashMap<_, _>>();
12305 self.buffer_snapshot
12306 .selections_in_range(range, false)
12307 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12308 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12309 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12310 let user_name = participant_names.get(&collaborator.user_id).cloned();
12311 Some(RemoteSelection {
12312 replica_id,
12313 selection,
12314 cursor_shape,
12315 line_mode,
12316 participant_index,
12317 peer_id: collaborator.peer_id,
12318 user_name,
12319 })
12320 })
12321 }
12322
12323 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12324 self.display_snapshot.buffer_snapshot.language_at(position)
12325 }
12326
12327 pub fn is_focused(&self) -> bool {
12328 self.is_focused
12329 }
12330
12331 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12332 self.placeholder_text.as_ref()
12333 }
12334
12335 pub fn scroll_position(&self) -> gpui::Point<f32> {
12336 self.scroll_anchor.scroll_position(&self.display_snapshot)
12337 }
12338
12339 fn gutter_dimensions(
12340 &self,
12341 font_id: FontId,
12342 font_size: Pixels,
12343 em_width: Pixels,
12344 max_line_number_width: Pixels,
12345 cx: &AppContext,
12346 ) -> GutterDimensions {
12347 if !self.show_gutter {
12348 return GutterDimensions::default();
12349 }
12350 let descent = cx.text_system().descent(font_id, font_size);
12351
12352 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12353 matches!(
12354 ProjectSettings::get_global(cx).git.git_gutter,
12355 Some(GitGutterSetting::TrackedFiles)
12356 )
12357 });
12358 let gutter_settings = EditorSettings::get_global(cx).gutter;
12359 let show_line_numbers = self
12360 .show_line_numbers
12361 .unwrap_or(gutter_settings.line_numbers);
12362 let line_gutter_width = if show_line_numbers {
12363 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12364 let min_width_for_number_on_gutter = em_width * 4.0;
12365 max_line_number_width.max(min_width_for_number_on_gutter)
12366 } else {
12367 0.0.into()
12368 };
12369
12370 let show_code_actions = self
12371 .show_code_actions
12372 .unwrap_or(gutter_settings.code_actions);
12373
12374 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12375
12376 let git_blame_entries_width = self
12377 .render_git_blame_gutter
12378 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12379
12380 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12381 left_padding += if show_code_actions || show_runnables {
12382 em_width * 3.0
12383 } else if show_git_gutter && show_line_numbers {
12384 em_width * 2.0
12385 } else if show_git_gutter || show_line_numbers {
12386 em_width
12387 } else {
12388 px(0.)
12389 };
12390
12391 let right_padding = if gutter_settings.folds && show_line_numbers {
12392 em_width * 4.0
12393 } else if gutter_settings.folds {
12394 em_width * 3.0
12395 } else if show_line_numbers {
12396 em_width
12397 } else {
12398 px(0.)
12399 };
12400
12401 GutterDimensions {
12402 left_padding,
12403 right_padding,
12404 width: line_gutter_width + left_padding + right_padding,
12405 margin: -descent,
12406 git_blame_entries_width,
12407 }
12408 }
12409
12410 pub fn render_fold_toggle(
12411 &self,
12412 buffer_row: MultiBufferRow,
12413 row_contains_cursor: bool,
12414 editor: View<Editor>,
12415 cx: &mut WindowContext,
12416 ) -> Option<AnyElement> {
12417 let folded = self.is_line_folded(buffer_row);
12418
12419 if let Some(crease) = self
12420 .crease_snapshot
12421 .query_row(buffer_row, &self.buffer_snapshot)
12422 {
12423 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12424 if folded {
12425 editor.update(cx, |editor, cx| {
12426 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12427 });
12428 } else {
12429 editor.update(cx, |editor, cx| {
12430 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12431 });
12432 }
12433 });
12434
12435 Some((crease.render_toggle)(
12436 buffer_row,
12437 folded,
12438 toggle_callback,
12439 cx,
12440 ))
12441 } else if folded
12442 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12443 {
12444 Some(
12445 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12446 .selected(folded)
12447 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12448 if folded {
12449 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12450 } else {
12451 this.fold_at(&FoldAt { buffer_row }, cx);
12452 }
12453 }))
12454 .into_any_element(),
12455 )
12456 } else {
12457 None
12458 }
12459 }
12460
12461 pub fn render_crease_trailer(
12462 &self,
12463 buffer_row: MultiBufferRow,
12464 cx: &mut WindowContext,
12465 ) -> Option<AnyElement> {
12466 let folded = self.is_line_folded(buffer_row);
12467 let crease = self
12468 .crease_snapshot
12469 .query_row(buffer_row, &self.buffer_snapshot)?;
12470 Some((crease.render_trailer)(buffer_row, folded, cx))
12471 }
12472}
12473
12474impl Deref for EditorSnapshot {
12475 type Target = DisplaySnapshot;
12476
12477 fn deref(&self) -> &Self::Target {
12478 &self.display_snapshot
12479 }
12480}
12481
12482#[derive(Clone, Debug, PartialEq, Eq)]
12483pub enum EditorEvent {
12484 InputIgnored {
12485 text: Arc<str>,
12486 },
12487 InputHandled {
12488 utf16_range_to_replace: Option<Range<isize>>,
12489 text: Arc<str>,
12490 },
12491 ExcerptsAdded {
12492 buffer: Model<Buffer>,
12493 predecessor: ExcerptId,
12494 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12495 },
12496 ExcerptsRemoved {
12497 ids: Vec<ExcerptId>,
12498 },
12499 ExcerptsEdited {
12500 ids: Vec<ExcerptId>,
12501 },
12502 ExcerptsExpanded {
12503 ids: Vec<ExcerptId>,
12504 },
12505 BufferEdited,
12506 Edited {
12507 transaction_id: clock::Lamport,
12508 },
12509 Reparsed(BufferId),
12510 Focused,
12511 FocusedIn,
12512 Blurred,
12513 DirtyChanged,
12514 Saved,
12515 TitleChanged,
12516 DiffBaseChanged,
12517 SelectionsChanged {
12518 local: bool,
12519 },
12520 ScrollPositionChanged {
12521 local: bool,
12522 autoscroll: bool,
12523 },
12524 Closed,
12525 TransactionUndone {
12526 transaction_id: clock::Lamport,
12527 },
12528 TransactionBegun {
12529 transaction_id: clock::Lamport,
12530 },
12531}
12532
12533impl EventEmitter<EditorEvent> for Editor {}
12534
12535impl FocusableView for Editor {
12536 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12537 self.focus_handle.clone()
12538 }
12539}
12540
12541impl Render for Editor {
12542 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12543 let settings = ThemeSettings::get_global(cx);
12544
12545 let text_style = match self.mode {
12546 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12547 color: cx.theme().colors().editor_foreground,
12548 font_family: settings.ui_font.family.clone(),
12549 font_features: settings.ui_font.features.clone(),
12550 font_fallbacks: settings.ui_font.fallbacks.clone(),
12551 font_size: rems(0.875).into(),
12552 font_weight: settings.ui_font.weight,
12553 line_height: relative(settings.buffer_line_height.value()),
12554 ..Default::default()
12555 },
12556 EditorMode::Full => TextStyle {
12557 color: cx.theme().colors().editor_foreground,
12558 font_family: settings.buffer_font.family.clone(),
12559 font_features: settings.buffer_font.features.clone(),
12560 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12561 font_size: settings.buffer_font_size(cx).into(),
12562 font_weight: settings.buffer_font.weight,
12563 line_height: relative(settings.buffer_line_height.value()),
12564 ..Default::default()
12565 },
12566 };
12567
12568 let background = match self.mode {
12569 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12570 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12571 EditorMode::Full => cx.theme().colors().editor_background,
12572 };
12573
12574 EditorElement::new(
12575 cx.view(),
12576 EditorStyle {
12577 background,
12578 local_player: cx.theme().players().local(),
12579 text: text_style,
12580 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12581 syntax: cx.theme().syntax().clone(),
12582 status: cx.theme().status().clone(),
12583 inlay_hints_style: HighlightStyle {
12584 color: Some(cx.theme().status().hint),
12585 ..HighlightStyle::default()
12586 },
12587 suggestions_style: HighlightStyle {
12588 color: Some(cx.theme().status().predictive),
12589 ..HighlightStyle::default()
12590 },
12591 },
12592 )
12593 }
12594}
12595
12596impl ViewInputHandler for Editor {
12597 fn text_for_range(
12598 &mut self,
12599 range_utf16: Range<usize>,
12600 cx: &mut ViewContext<Self>,
12601 ) -> Option<String> {
12602 Some(
12603 self.buffer
12604 .read(cx)
12605 .read(cx)
12606 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12607 .collect(),
12608 )
12609 }
12610
12611 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12612 // Prevent the IME menu from appearing when holding down an alphabetic key
12613 // while input is disabled.
12614 if !self.input_enabled {
12615 return None;
12616 }
12617
12618 let range = self.selections.newest::<OffsetUtf16>(cx).range();
12619 Some(range.start.0..range.end.0)
12620 }
12621
12622 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12623 let snapshot = self.buffer.read(cx).read(cx);
12624 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12625 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12626 }
12627
12628 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12629 self.clear_highlights::<InputComposition>(cx);
12630 self.ime_transaction.take();
12631 }
12632
12633 fn replace_text_in_range(
12634 &mut self,
12635 range_utf16: Option<Range<usize>>,
12636 text: &str,
12637 cx: &mut ViewContext<Self>,
12638 ) {
12639 if !self.input_enabled {
12640 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12641 return;
12642 }
12643
12644 self.transact(cx, |this, cx| {
12645 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12646 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12647 Some(this.selection_replacement_ranges(range_utf16, cx))
12648 } else {
12649 this.marked_text_ranges(cx)
12650 };
12651
12652 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12653 let newest_selection_id = this.selections.newest_anchor().id;
12654 this.selections
12655 .all::<OffsetUtf16>(cx)
12656 .iter()
12657 .zip(ranges_to_replace.iter())
12658 .find_map(|(selection, range)| {
12659 if selection.id == newest_selection_id {
12660 Some(
12661 (range.start.0 as isize - selection.head().0 as isize)
12662 ..(range.end.0 as isize - selection.head().0 as isize),
12663 )
12664 } else {
12665 None
12666 }
12667 })
12668 });
12669
12670 cx.emit(EditorEvent::InputHandled {
12671 utf16_range_to_replace: range_to_replace,
12672 text: text.into(),
12673 });
12674
12675 if let Some(new_selected_ranges) = new_selected_ranges {
12676 this.change_selections(None, cx, |selections| {
12677 selections.select_ranges(new_selected_ranges)
12678 });
12679 this.backspace(&Default::default(), cx);
12680 }
12681
12682 this.handle_input(text, cx);
12683 });
12684
12685 if let Some(transaction) = self.ime_transaction {
12686 self.buffer.update(cx, |buffer, cx| {
12687 buffer.group_until_transaction(transaction, cx);
12688 });
12689 }
12690
12691 self.unmark_text(cx);
12692 }
12693
12694 fn replace_and_mark_text_in_range(
12695 &mut self,
12696 range_utf16: Option<Range<usize>>,
12697 text: &str,
12698 new_selected_range_utf16: Option<Range<usize>>,
12699 cx: &mut ViewContext<Self>,
12700 ) {
12701 if !self.input_enabled {
12702 return;
12703 }
12704
12705 let transaction = self.transact(cx, |this, cx| {
12706 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12707 let snapshot = this.buffer.read(cx).read(cx);
12708 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12709 for marked_range in &mut marked_ranges {
12710 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12711 marked_range.start.0 += relative_range_utf16.start;
12712 marked_range.start =
12713 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12714 marked_range.end =
12715 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12716 }
12717 }
12718 Some(marked_ranges)
12719 } else if let Some(range_utf16) = range_utf16 {
12720 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12721 Some(this.selection_replacement_ranges(range_utf16, cx))
12722 } else {
12723 None
12724 };
12725
12726 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12727 let newest_selection_id = this.selections.newest_anchor().id;
12728 this.selections
12729 .all::<OffsetUtf16>(cx)
12730 .iter()
12731 .zip(ranges_to_replace.iter())
12732 .find_map(|(selection, range)| {
12733 if selection.id == newest_selection_id {
12734 Some(
12735 (range.start.0 as isize - selection.head().0 as isize)
12736 ..(range.end.0 as isize - selection.head().0 as isize),
12737 )
12738 } else {
12739 None
12740 }
12741 })
12742 });
12743
12744 cx.emit(EditorEvent::InputHandled {
12745 utf16_range_to_replace: range_to_replace,
12746 text: text.into(),
12747 });
12748
12749 if let Some(ranges) = ranges_to_replace {
12750 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12751 }
12752
12753 let marked_ranges = {
12754 let snapshot = this.buffer.read(cx).read(cx);
12755 this.selections
12756 .disjoint_anchors()
12757 .iter()
12758 .map(|selection| {
12759 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12760 })
12761 .collect::<Vec<_>>()
12762 };
12763
12764 if text.is_empty() {
12765 this.unmark_text(cx);
12766 } else {
12767 this.highlight_text::<InputComposition>(
12768 marked_ranges.clone(),
12769 HighlightStyle {
12770 underline: Some(UnderlineStyle {
12771 thickness: px(1.),
12772 color: None,
12773 wavy: false,
12774 }),
12775 ..Default::default()
12776 },
12777 cx,
12778 );
12779 }
12780
12781 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12782 let use_autoclose = this.use_autoclose;
12783 let use_auto_surround = this.use_auto_surround;
12784 this.set_use_autoclose(false);
12785 this.set_use_auto_surround(false);
12786 this.handle_input(text, cx);
12787 this.set_use_autoclose(use_autoclose);
12788 this.set_use_auto_surround(use_auto_surround);
12789
12790 if let Some(new_selected_range) = new_selected_range_utf16 {
12791 let snapshot = this.buffer.read(cx).read(cx);
12792 let new_selected_ranges = marked_ranges
12793 .into_iter()
12794 .map(|marked_range| {
12795 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12796 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12797 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12798 snapshot.clip_offset_utf16(new_start, Bias::Left)
12799 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12800 })
12801 .collect::<Vec<_>>();
12802
12803 drop(snapshot);
12804 this.change_selections(None, cx, |selections| {
12805 selections.select_ranges(new_selected_ranges)
12806 });
12807 }
12808 });
12809
12810 self.ime_transaction = self.ime_transaction.or(transaction);
12811 if let Some(transaction) = self.ime_transaction {
12812 self.buffer.update(cx, |buffer, cx| {
12813 buffer.group_until_transaction(transaction, cx);
12814 });
12815 }
12816
12817 if self.text_highlights::<InputComposition>(cx).is_none() {
12818 self.ime_transaction.take();
12819 }
12820 }
12821
12822 fn bounds_for_range(
12823 &mut self,
12824 range_utf16: Range<usize>,
12825 element_bounds: gpui::Bounds<Pixels>,
12826 cx: &mut ViewContext<Self>,
12827 ) -> Option<gpui::Bounds<Pixels>> {
12828 let text_layout_details = self.text_layout_details(cx);
12829 let style = &text_layout_details.editor_style;
12830 let font_id = cx.text_system().resolve_font(&style.text.font());
12831 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12832 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12833
12834 let em_width = cx
12835 .text_system()
12836 .typographic_bounds(font_id, font_size, 'm')
12837 .unwrap()
12838 .size
12839 .width;
12840
12841 let snapshot = self.snapshot(cx);
12842 let scroll_position = snapshot.scroll_position();
12843 let scroll_left = scroll_position.x * em_width;
12844
12845 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12846 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12847 + self.gutter_dimensions.width;
12848 let y = line_height * (start.row().as_f32() - scroll_position.y);
12849
12850 Some(Bounds {
12851 origin: element_bounds.origin + point(x, y),
12852 size: size(em_width, line_height),
12853 })
12854 }
12855}
12856
12857trait SelectionExt {
12858 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12859 fn spanned_rows(
12860 &self,
12861 include_end_if_at_line_start: bool,
12862 map: &DisplaySnapshot,
12863 ) -> Range<MultiBufferRow>;
12864}
12865
12866impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12867 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12868 let start = self
12869 .start
12870 .to_point(&map.buffer_snapshot)
12871 .to_display_point(map);
12872 let end = self
12873 .end
12874 .to_point(&map.buffer_snapshot)
12875 .to_display_point(map);
12876 if self.reversed {
12877 end..start
12878 } else {
12879 start..end
12880 }
12881 }
12882
12883 fn spanned_rows(
12884 &self,
12885 include_end_if_at_line_start: bool,
12886 map: &DisplaySnapshot,
12887 ) -> Range<MultiBufferRow> {
12888 let start = self.start.to_point(&map.buffer_snapshot);
12889 let mut end = self.end.to_point(&map.buffer_snapshot);
12890 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12891 end.row -= 1;
12892 }
12893
12894 let buffer_start = map.prev_line_boundary(start).0;
12895 let buffer_end = map.next_line_boundary(end).0;
12896 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12897 }
12898}
12899
12900impl<T: InvalidationRegion> InvalidationStack<T> {
12901 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12902 where
12903 S: Clone + ToOffset,
12904 {
12905 while let Some(region) = self.last() {
12906 let all_selections_inside_invalidation_ranges =
12907 if selections.len() == region.ranges().len() {
12908 selections
12909 .iter()
12910 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12911 .all(|(selection, invalidation_range)| {
12912 let head = selection.head().to_offset(buffer);
12913 invalidation_range.start <= head && invalidation_range.end >= head
12914 })
12915 } else {
12916 false
12917 };
12918
12919 if all_selections_inside_invalidation_ranges {
12920 break;
12921 } else {
12922 self.pop();
12923 }
12924 }
12925 }
12926}
12927
12928impl<T> Default for InvalidationStack<T> {
12929 fn default() -> Self {
12930 Self(Default::default())
12931 }
12932}
12933
12934impl<T> Deref for InvalidationStack<T> {
12935 type Target = Vec<T>;
12936
12937 fn deref(&self) -> &Self::Target {
12938 &self.0
12939 }
12940}
12941
12942impl<T> DerefMut for InvalidationStack<T> {
12943 fn deref_mut(&mut self) -> &mut Self::Target {
12944 &mut self.0
12945 }
12946}
12947
12948impl InvalidationRegion for SnippetState {
12949 fn ranges(&self) -> &[Range<Anchor>] {
12950 &self.ranges[self.active_index]
12951 }
12952}
12953
12954pub fn diagnostic_block_renderer(
12955 diagnostic: Diagnostic,
12956 max_message_rows: Option<u8>,
12957 allow_closing: bool,
12958 _is_valid: bool,
12959) -> RenderBlock {
12960 let (text_without_backticks, code_ranges) =
12961 highlight_diagnostic_message(&diagnostic, max_message_rows);
12962
12963 Box::new(move |cx: &mut BlockContext| {
12964 let group_id: SharedString = cx.block_id.to_string().into();
12965
12966 let mut text_style = cx.text_style().clone();
12967 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12968 let theme_settings = ThemeSettings::get_global(cx);
12969 text_style.font_family = theme_settings.buffer_font.family.clone();
12970 text_style.font_style = theme_settings.buffer_font.style;
12971 text_style.font_features = theme_settings.buffer_font.features.clone();
12972 text_style.font_weight = theme_settings.buffer_font.weight;
12973
12974 let multi_line_diagnostic = diagnostic.message.contains('\n');
12975
12976 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
12977 if multi_line_diagnostic {
12978 v_flex()
12979 } else {
12980 h_flex()
12981 }
12982 .when(allow_closing, |div| {
12983 div.children(diagnostic.is_primary.then(|| {
12984 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
12985 .icon_color(Color::Muted)
12986 .size(ButtonSize::Compact)
12987 .style(ButtonStyle::Transparent)
12988 .visible_on_hover(group_id.clone())
12989 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12990 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12991 }))
12992 })
12993 .child(
12994 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
12995 .icon_color(Color::Muted)
12996 .size(ButtonSize::Compact)
12997 .style(ButtonStyle::Transparent)
12998 .visible_on_hover(group_id.clone())
12999 .on_click({
13000 let message = diagnostic.message.clone();
13001 move |_click, cx| {
13002 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13003 }
13004 })
13005 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13006 )
13007 };
13008
13009 let icon_size = buttons(&diagnostic, cx.block_id)
13010 .into_any_element()
13011 .layout_as_root(AvailableSpace::min_size(), cx);
13012
13013 h_flex()
13014 .id(cx.block_id)
13015 .group(group_id.clone())
13016 .relative()
13017 .size_full()
13018 .pl(cx.gutter_dimensions.width)
13019 .w(cx.max_width + cx.gutter_dimensions.width)
13020 .child(
13021 div()
13022 .flex()
13023 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13024 .flex_shrink(),
13025 )
13026 .child(buttons(&diagnostic, cx.block_id))
13027 .child(div().flex().flex_shrink_0().child(
13028 StyledText::new(text_without_backticks.clone()).with_highlights(
13029 &text_style,
13030 code_ranges.iter().map(|range| {
13031 (
13032 range.clone(),
13033 HighlightStyle {
13034 font_weight: Some(FontWeight::BOLD),
13035 ..Default::default()
13036 },
13037 )
13038 }),
13039 ),
13040 ))
13041 .into_any_element()
13042 })
13043}
13044
13045pub fn highlight_diagnostic_message(
13046 diagnostic: &Diagnostic,
13047 mut max_message_rows: Option<u8>,
13048) -> (SharedString, Vec<Range<usize>>) {
13049 let mut text_without_backticks = String::new();
13050 let mut code_ranges = Vec::new();
13051
13052 if let Some(source) = &diagnostic.source {
13053 text_without_backticks.push_str(&source);
13054 code_ranges.push(0..source.len());
13055 text_without_backticks.push_str(": ");
13056 }
13057
13058 let mut prev_offset = 0;
13059 let mut in_code_block = false;
13060 let has_row_limit = max_message_rows.is_some();
13061 let mut newline_indices = diagnostic
13062 .message
13063 .match_indices('\n')
13064 .filter(|_| has_row_limit)
13065 .map(|(ix, _)| ix)
13066 .fuse()
13067 .peekable();
13068
13069 for (quote_ix, _) in diagnostic
13070 .message
13071 .match_indices('`')
13072 .chain([(diagnostic.message.len(), "")])
13073 {
13074 let mut first_newline_ix = None;
13075 let mut last_newline_ix = None;
13076 while let Some(newline_ix) = newline_indices.peek() {
13077 if *newline_ix < quote_ix {
13078 if first_newline_ix.is_none() {
13079 first_newline_ix = Some(*newline_ix);
13080 }
13081 last_newline_ix = Some(*newline_ix);
13082
13083 if let Some(rows_left) = &mut max_message_rows {
13084 if *rows_left == 0 {
13085 break;
13086 } else {
13087 *rows_left -= 1;
13088 }
13089 }
13090 let _ = newline_indices.next();
13091 } else {
13092 break;
13093 }
13094 }
13095 let prev_len = text_without_backticks.len();
13096 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13097 text_without_backticks.push_str(new_text);
13098 if in_code_block {
13099 code_ranges.push(prev_len..text_without_backticks.len());
13100 }
13101 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13102 in_code_block = !in_code_block;
13103 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13104 text_without_backticks.push_str("...");
13105 break;
13106 }
13107 }
13108
13109 (text_without_backticks.into(), code_ranges)
13110}
13111
13112fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13113 match severity {
13114 DiagnosticSeverity::ERROR => colors.error,
13115 DiagnosticSeverity::WARNING => colors.warning,
13116 DiagnosticSeverity::INFORMATION => colors.info,
13117 DiagnosticSeverity::HINT => colors.info,
13118 _ => colors.ignored,
13119 }
13120}
13121
13122pub fn styled_runs_for_code_label<'a>(
13123 label: &'a CodeLabel,
13124 syntax_theme: &'a theme::SyntaxTheme,
13125) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13126 let fade_out = HighlightStyle {
13127 fade_out: Some(0.35),
13128 ..Default::default()
13129 };
13130
13131 let mut prev_end = label.filter_range.end;
13132 label
13133 .runs
13134 .iter()
13135 .enumerate()
13136 .flat_map(move |(ix, (range, highlight_id))| {
13137 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13138 style
13139 } else {
13140 return Default::default();
13141 };
13142 let mut muted_style = style;
13143 muted_style.highlight(fade_out);
13144
13145 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13146 if range.start >= label.filter_range.end {
13147 if range.start > prev_end {
13148 runs.push((prev_end..range.start, fade_out));
13149 }
13150 runs.push((range.clone(), muted_style));
13151 } else if range.end <= label.filter_range.end {
13152 runs.push((range.clone(), style));
13153 } else {
13154 runs.push((range.start..label.filter_range.end, style));
13155 runs.push((label.filter_range.end..range.end, muted_style));
13156 }
13157 prev_end = cmp::max(prev_end, range.end);
13158
13159 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13160 runs.push((prev_end..label.text.len(), fade_out));
13161 }
13162
13163 runs
13164 })
13165}
13166
13167pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13168 let mut prev_index = 0;
13169 let mut prev_codepoint: Option<char> = None;
13170 text.char_indices()
13171 .chain([(text.len(), '\0')])
13172 .filter_map(move |(index, codepoint)| {
13173 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13174 let is_boundary = index == text.len()
13175 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13176 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13177 if is_boundary {
13178 let chunk = &text[prev_index..index];
13179 prev_index = index;
13180 Some(chunk)
13181 } else {
13182 None
13183 }
13184 })
13185}
13186
13187pub trait RangeToAnchorExt: Sized {
13188 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13189
13190 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13191 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13192 anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13193 }
13194}
13195
13196impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13197 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13198 let start_offset = self.start.to_offset(snapshot);
13199 let end_offset = self.end.to_offset(snapshot);
13200 if start_offset == end_offset {
13201 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13202 } else {
13203 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13204 }
13205 }
13206}
13207
13208pub trait RowExt {
13209 fn as_f32(&self) -> f32;
13210
13211 fn next_row(&self) -> Self;
13212
13213 fn previous_row(&self) -> Self;
13214
13215 fn minus(&self, other: Self) -> u32;
13216}
13217
13218impl RowExt for DisplayRow {
13219 fn as_f32(&self) -> f32 {
13220 self.0 as f32
13221 }
13222
13223 fn next_row(&self) -> Self {
13224 Self(self.0 + 1)
13225 }
13226
13227 fn previous_row(&self) -> Self {
13228 Self(self.0.saturating_sub(1))
13229 }
13230
13231 fn minus(&self, other: Self) -> u32 {
13232 self.0 - other.0
13233 }
13234}
13235
13236impl RowExt for MultiBufferRow {
13237 fn as_f32(&self) -> f32 {
13238 self.0 as f32
13239 }
13240
13241 fn next_row(&self) -> Self {
13242 Self(self.0 + 1)
13243 }
13244
13245 fn previous_row(&self) -> Self {
13246 Self(self.0.saturating_sub(1))
13247 }
13248
13249 fn minus(&self, other: Self) -> u32 {
13250 self.0 - other.0
13251 }
13252}
13253
13254trait RowRangeExt {
13255 type Row;
13256
13257 fn len(&self) -> usize;
13258
13259 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13260}
13261
13262impl RowRangeExt for Range<MultiBufferRow> {
13263 type Row = MultiBufferRow;
13264
13265 fn len(&self) -> usize {
13266 (self.end.0 - self.start.0) as usize
13267 }
13268
13269 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13270 (self.start.0..self.end.0).map(MultiBufferRow)
13271 }
13272}
13273
13274impl RowRangeExt for Range<DisplayRow> {
13275 type Row = DisplayRow;
13276
13277 fn len(&self) -> usize {
13278 (self.end.0 - self.start.0) as usize
13279 }
13280
13281 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13282 (self.start.0..self.end.0).map(DisplayRow)
13283 }
13284}
13285
13286fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13287 if hunk.diff_base_byte_range.is_empty() {
13288 DiffHunkStatus::Added
13289 } else if hunk.associated_range.is_empty() {
13290 DiffHunkStatus::Removed
13291 } else {
13292 DiffHunkStatus::Modified
13293 }
13294}
13295
13296/// If select range has more than one line, we
13297/// just point the cursor to range.start.
13298fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13299 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13300 range
13301 } else {
13302 range.start..range.start
13303 }
13304}