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 pub unnecessary_code_fade: f32,
388}
389
390impl Default for EditorStyle {
391 fn default() -> Self {
392 Self {
393 background: Hsla::default(),
394 local_player: PlayerColor::default(),
395 text: TextStyle::default(),
396 scrollbar_width: Pixels::default(),
397 syntax: Default::default(),
398 // HACK: Status colors don't have a real default.
399 // We should look into removing the status colors from the editor
400 // style and retrieve them directly from the theme.
401 status: StatusColors::dark(),
402 inlay_hints_style: HighlightStyle::default(),
403 suggestions_style: HighlightStyle::default(),
404 unnecessary_code_fade: Default::default(),
405 }
406 }
407}
408
409type CompletionId = usize;
410
411#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
412struct EditorActionId(usize);
413
414impl EditorActionId {
415 pub fn post_inc(&mut self) -> Self {
416 let answer = self.0;
417
418 *self = Self(answer + 1);
419
420 Self(answer)
421 }
422}
423
424// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
425// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
426
427type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
428type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
429
430#[derive(Default)]
431struct ScrollbarMarkerState {
432 scrollbar_size: Size<Pixels>,
433 dirty: bool,
434 markers: Arc<[PaintQuad]>,
435 pending_refresh: Option<Task<Result<()>>>,
436}
437
438impl ScrollbarMarkerState {
439 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
440 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
441 }
442}
443
444#[derive(Clone, Debug)]
445struct RunnableTasks {
446 templates: Vec<(TaskSourceKind, TaskTemplate)>,
447 offset: MultiBufferOffset,
448 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
449 column: u32,
450 // Values of all named captures, including those starting with '_'
451 extra_variables: HashMap<String, String>,
452 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
453 context_range: Range<BufferOffset>,
454}
455
456#[derive(Clone)]
457struct ResolvedTasks {
458 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
459 position: Anchor,
460}
461#[derive(Copy, Clone, Debug)]
462struct MultiBufferOffset(usize);
463#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
464struct BufferOffset(usize);
465/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
466///
467/// See the [module level documentation](self) for more information.
468pub struct Editor {
469 focus_handle: FocusHandle,
470 last_focused_descendant: Option<WeakFocusHandle>,
471 /// The text buffer being edited
472 buffer: Model<MultiBuffer>,
473 /// Map of how text in the buffer should be displayed.
474 /// Handles soft wraps, folds, fake inlay text insertions, etc.
475 pub display_map: Model<DisplayMap>,
476 pub selections: SelectionsCollection,
477 pub scroll_manager: ScrollManager,
478 /// When inline assist editors are linked, they all render cursors because
479 /// typing enters text into each of them, even the ones that aren't focused.
480 pub(crate) show_cursor_when_unfocused: bool,
481 columnar_selection_tail: Option<Anchor>,
482 add_selections_state: Option<AddSelectionsState>,
483 select_next_state: Option<SelectNextState>,
484 select_prev_state: Option<SelectNextState>,
485 selection_history: SelectionHistory,
486 autoclose_regions: Vec<AutocloseRegion>,
487 snippet_stack: InvalidationStack<SnippetState>,
488 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
489 ime_transaction: Option<TransactionId>,
490 active_diagnostics: Option<ActiveDiagnosticGroup>,
491 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
492 project: Option<Model<Project>>,
493 completion_provider: Option<Box<dyn CompletionProvider>>,
494 collaboration_hub: Option<Box<dyn CollaborationHub>>,
495 blink_manager: Model<BlinkManager>,
496 show_cursor_names: bool,
497 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
498 pub show_local_selections: bool,
499 mode: EditorMode,
500 show_breadcrumbs: bool,
501 show_gutter: bool,
502 show_line_numbers: Option<bool>,
503 show_git_diff_gutter: Option<bool>,
504 show_code_actions: Option<bool>,
505 show_runnables: Option<bool>,
506 show_wrap_guides: Option<bool>,
507 show_indent_guides: Option<bool>,
508 placeholder_text: Option<Arc<str>>,
509 highlight_order: usize,
510 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
511 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
512 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
513 scrollbar_marker_state: ScrollbarMarkerState,
514 active_indent_guides_state: ActiveIndentGuidesState,
515 nav_history: Option<ItemNavHistory>,
516 context_menu: RwLock<Option<ContextMenu>>,
517 mouse_context_menu: Option<MouseContextMenu>,
518 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
519 signature_help_state: SignatureHelpState,
520 auto_signature_help: Option<bool>,
521 find_all_references_task_sources: Vec<Anchor>,
522 next_completion_id: CompletionId,
523 completion_documentation_pre_resolve_debounce: DebouncedDelay,
524 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
525 code_actions_task: Option<Task<()>>,
526 document_highlights_task: Option<Task<()>>,
527 linked_editing_range_task: Option<Task<Option<()>>>,
528 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
529 pending_rename: Option<RenameState>,
530 searchable: bool,
531 cursor_shape: CursorShape,
532 current_line_highlight: Option<CurrentLineHighlight>,
533 collapse_matches: bool,
534 autoindent_mode: Option<AutoindentMode>,
535 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
536 keymap_context_layers: BTreeMap<TypeId, KeyContext>,
537 input_enabled: bool,
538 use_modal_editing: bool,
539 read_only: bool,
540 leader_peer_id: Option<PeerId>,
541 remote_id: Option<ViewId>,
542 hover_state: HoverState,
543 gutter_hovered: bool,
544 hovered_link_state: Option<HoveredLinkState>,
545 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
546 active_inline_completion: Option<(Inlay, Option<Range<Anchor>>)>,
547 show_inline_completions: bool,
548 inlay_hint_cache: InlayHintCache,
549 expanded_hunks: ExpandedHunks,
550 next_inlay_id: usize,
551 _subscriptions: Vec<Subscription>,
552 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
553 gutter_dimensions: GutterDimensions,
554 pub vim_replace_map: HashMap<Range<usize>, String>,
555 style: Option<EditorStyle>,
556 next_editor_action_id: EditorActionId,
557 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
558 use_autoclose: bool,
559 use_auto_surround: bool,
560 auto_replace_emoji_shortcode: bool,
561 show_git_blame_gutter: bool,
562 show_git_blame_inline: bool,
563 show_git_blame_inline_delay_task: Option<Task<()>>,
564 git_blame_inline_enabled: bool,
565 serialize_dirty_buffers: bool,
566 show_selection_menu: Option<bool>,
567 blame: Option<Model<GitBlame>>,
568 blame_subscription: Option<Subscription>,
569 custom_context_menu: Option<
570 Box<
571 dyn 'static
572 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
573 >,
574 >,
575 last_bounds: Option<Bounds<Pixels>>,
576 expect_bounds_change: Option<Bounds<Pixels>>,
577 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
578 tasks_update_task: Option<Task<()>>,
579 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
580 file_header_size: u32,
581 breadcrumb_header: Option<String>,
582 focused_block: Option<FocusedBlock>,
583 next_scroll_position: NextScrollCursorCenterTopBottom,
584 _scroll_cursor_center_top_bottom_task: Task<()>,
585}
586
587#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
588enum NextScrollCursorCenterTopBottom {
589 #[default]
590 Center,
591 Top,
592 Bottom,
593}
594
595impl NextScrollCursorCenterTopBottom {
596 fn next(&self) -> Self {
597 match self {
598 Self::Center => Self::Top,
599 Self::Top => Self::Bottom,
600 Self::Bottom => Self::Center,
601 }
602 }
603}
604
605#[derive(Clone)]
606pub struct EditorSnapshot {
607 pub mode: EditorMode,
608 show_gutter: bool,
609 show_line_numbers: Option<bool>,
610 show_git_diff_gutter: Option<bool>,
611 show_code_actions: Option<bool>,
612 show_runnables: Option<bool>,
613 render_git_blame_gutter: bool,
614 pub display_snapshot: DisplaySnapshot,
615 pub placeholder_text: Option<Arc<str>>,
616 is_focused: bool,
617 scroll_anchor: ScrollAnchor,
618 ongoing_scroll: OngoingScroll,
619 current_line_highlight: CurrentLineHighlight,
620 gutter_hovered: bool,
621}
622
623const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
624
625#[derive(Default, Debug, Clone, Copy)]
626pub struct GutterDimensions {
627 pub left_padding: Pixels,
628 pub right_padding: Pixels,
629 pub width: Pixels,
630 pub margin: Pixels,
631 pub git_blame_entries_width: Option<Pixels>,
632}
633
634impl GutterDimensions {
635 /// The full width of the space taken up by the gutter.
636 pub fn full_width(&self) -> Pixels {
637 self.margin + self.width
638 }
639
640 /// The width of the space reserved for the fold indicators,
641 /// use alongside 'justify_end' and `gutter_width` to
642 /// right align content with the line numbers
643 pub fn fold_area_width(&self) -> Pixels {
644 self.margin + self.right_padding
645 }
646}
647
648#[derive(Debug)]
649pub struct RemoteSelection {
650 pub replica_id: ReplicaId,
651 pub selection: Selection<Anchor>,
652 pub cursor_shape: CursorShape,
653 pub peer_id: PeerId,
654 pub line_mode: bool,
655 pub participant_index: Option<ParticipantIndex>,
656 pub user_name: Option<SharedString>,
657}
658
659#[derive(Clone, Debug)]
660struct SelectionHistoryEntry {
661 selections: Arc<[Selection<Anchor>]>,
662 select_next_state: Option<SelectNextState>,
663 select_prev_state: Option<SelectNextState>,
664 add_selections_state: Option<AddSelectionsState>,
665}
666
667enum SelectionHistoryMode {
668 Normal,
669 Undoing,
670 Redoing,
671}
672
673#[derive(Clone, PartialEq, Eq, Hash)]
674struct HoveredCursor {
675 replica_id: u16,
676 selection_id: usize,
677}
678
679impl Default for SelectionHistoryMode {
680 fn default() -> Self {
681 Self::Normal
682 }
683}
684
685#[derive(Default)]
686struct SelectionHistory {
687 #[allow(clippy::type_complexity)]
688 selections_by_transaction:
689 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
690 mode: SelectionHistoryMode,
691 undo_stack: VecDeque<SelectionHistoryEntry>,
692 redo_stack: VecDeque<SelectionHistoryEntry>,
693}
694
695impl SelectionHistory {
696 fn insert_transaction(
697 &mut self,
698 transaction_id: TransactionId,
699 selections: Arc<[Selection<Anchor>]>,
700 ) {
701 self.selections_by_transaction
702 .insert(transaction_id, (selections, None));
703 }
704
705 #[allow(clippy::type_complexity)]
706 fn transaction(
707 &self,
708 transaction_id: TransactionId,
709 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
710 self.selections_by_transaction.get(&transaction_id)
711 }
712
713 #[allow(clippy::type_complexity)]
714 fn transaction_mut(
715 &mut self,
716 transaction_id: TransactionId,
717 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
718 self.selections_by_transaction.get_mut(&transaction_id)
719 }
720
721 fn push(&mut self, entry: SelectionHistoryEntry) {
722 if !entry.selections.is_empty() {
723 match self.mode {
724 SelectionHistoryMode::Normal => {
725 self.push_undo(entry);
726 self.redo_stack.clear();
727 }
728 SelectionHistoryMode::Undoing => self.push_redo(entry),
729 SelectionHistoryMode::Redoing => self.push_undo(entry),
730 }
731 }
732 }
733
734 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
735 if self
736 .undo_stack
737 .back()
738 .map_or(true, |e| e.selections != entry.selections)
739 {
740 self.undo_stack.push_back(entry);
741 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
742 self.undo_stack.pop_front();
743 }
744 }
745 }
746
747 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
748 if self
749 .redo_stack
750 .back()
751 .map_or(true, |e| e.selections != entry.selections)
752 {
753 self.redo_stack.push_back(entry);
754 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
755 self.redo_stack.pop_front();
756 }
757 }
758 }
759}
760
761struct RowHighlight {
762 index: usize,
763 range: RangeInclusive<Anchor>,
764 color: Option<Hsla>,
765 should_autoscroll: bool,
766}
767
768#[derive(Clone, Debug)]
769struct AddSelectionsState {
770 above: bool,
771 stack: Vec<usize>,
772}
773
774#[derive(Clone)]
775struct SelectNextState {
776 query: AhoCorasick,
777 wordwise: bool,
778 done: bool,
779}
780
781impl std::fmt::Debug for SelectNextState {
782 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
783 f.debug_struct(std::any::type_name::<Self>())
784 .field("wordwise", &self.wordwise)
785 .field("done", &self.done)
786 .finish()
787 }
788}
789
790#[derive(Debug)]
791struct AutocloseRegion {
792 selection_id: usize,
793 range: Range<Anchor>,
794 pair: BracketPair,
795}
796
797#[derive(Debug)]
798struct SnippetState {
799 ranges: Vec<Vec<Range<Anchor>>>,
800 active_index: usize,
801}
802
803#[doc(hidden)]
804pub struct RenameState {
805 pub range: Range<Anchor>,
806 pub old_name: Arc<str>,
807 pub editor: View<Editor>,
808 block_id: CustomBlockId,
809}
810
811struct InvalidationStack<T>(Vec<T>);
812
813struct RegisteredInlineCompletionProvider {
814 provider: Arc<dyn InlineCompletionProviderHandle>,
815 _subscription: Subscription,
816}
817
818enum ContextMenu {
819 Completions(CompletionsMenu),
820 CodeActions(CodeActionsMenu),
821}
822
823impl ContextMenu {
824 fn select_first(
825 &mut self,
826 project: Option<&Model<Project>>,
827 cx: &mut ViewContext<Editor>,
828 ) -> bool {
829 if self.visible() {
830 match self {
831 ContextMenu::Completions(menu) => menu.select_first(project, cx),
832 ContextMenu::CodeActions(menu) => menu.select_first(cx),
833 }
834 true
835 } else {
836 false
837 }
838 }
839
840 fn select_prev(
841 &mut self,
842 project: Option<&Model<Project>>,
843 cx: &mut ViewContext<Editor>,
844 ) -> bool {
845 if self.visible() {
846 match self {
847 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
848 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
849 }
850 true
851 } else {
852 false
853 }
854 }
855
856 fn select_next(
857 &mut self,
858 project: Option<&Model<Project>>,
859 cx: &mut ViewContext<Editor>,
860 ) -> bool {
861 if self.visible() {
862 match self {
863 ContextMenu::Completions(menu) => menu.select_next(project, cx),
864 ContextMenu::CodeActions(menu) => menu.select_next(cx),
865 }
866 true
867 } else {
868 false
869 }
870 }
871
872 fn select_last(
873 &mut self,
874 project: Option<&Model<Project>>,
875 cx: &mut ViewContext<Editor>,
876 ) -> bool {
877 if self.visible() {
878 match self {
879 ContextMenu::Completions(menu) => menu.select_last(project, cx),
880 ContextMenu::CodeActions(menu) => menu.select_last(cx),
881 }
882 true
883 } else {
884 false
885 }
886 }
887
888 fn visible(&self) -> bool {
889 match self {
890 ContextMenu::Completions(menu) => menu.visible(),
891 ContextMenu::CodeActions(menu) => menu.visible(),
892 }
893 }
894
895 fn render(
896 &self,
897 cursor_position: DisplayPoint,
898 style: &EditorStyle,
899 max_height: Pixels,
900 workspace: Option<WeakView<Workspace>>,
901 cx: &mut ViewContext<Editor>,
902 ) -> (ContextMenuOrigin, AnyElement) {
903 match self {
904 ContextMenu::Completions(menu) => (
905 ContextMenuOrigin::EditorPoint(cursor_position),
906 menu.render(style, max_height, workspace, cx),
907 ),
908 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
909 }
910 }
911}
912
913enum ContextMenuOrigin {
914 EditorPoint(DisplayPoint),
915 GutterIndicator(DisplayRow),
916}
917
918#[derive(Clone)]
919struct CompletionsMenu {
920 id: CompletionId,
921 sort_completions: bool,
922 initial_position: Anchor,
923 buffer: Model<Buffer>,
924 completions: Arc<RwLock<Box<[Completion]>>>,
925 match_candidates: Arc<[StringMatchCandidate]>,
926 matches: Arc<[StringMatch]>,
927 selected_item: usize,
928 scroll_handle: UniformListScrollHandle,
929 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
930}
931
932impl CompletionsMenu {
933 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
934 self.selected_item = 0;
935 self.scroll_handle.scroll_to_item(self.selected_item);
936 self.attempt_resolve_selected_completion_documentation(project, cx);
937 cx.notify();
938 }
939
940 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
941 if self.selected_item > 0 {
942 self.selected_item -= 1;
943 } else {
944 self.selected_item = self.matches.len() - 1;
945 }
946 self.scroll_handle.scroll_to_item(self.selected_item);
947 self.attempt_resolve_selected_completion_documentation(project, cx);
948 cx.notify();
949 }
950
951 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
952 if self.selected_item + 1 < self.matches.len() {
953 self.selected_item += 1;
954 } else {
955 self.selected_item = 0;
956 }
957 self.scroll_handle.scroll_to_item(self.selected_item);
958 self.attempt_resolve_selected_completion_documentation(project, cx);
959 cx.notify();
960 }
961
962 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
963 self.selected_item = self.matches.len() - 1;
964 self.scroll_handle.scroll_to_item(self.selected_item);
965 self.attempt_resolve_selected_completion_documentation(project, cx);
966 cx.notify();
967 }
968
969 fn pre_resolve_completion_documentation(
970 buffer: Model<Buffer>,
971 completions: Arc<RwLock<Box<[Completion]>>>,
972 matches: Arc<[StringMatch]>,
973 editor: &Editor,
974 cx: &mut ViewContext<Editor>,
975 ) -> Task<()> {
976 let settings = EditorSettings::get_global(cx);
977 if !settings.show_completion_documentation {
978 return Task::ready(());
979 }
980
981 let Some(provider) = editor.completion_provider.as_ref() else {
982 return Task::ready(());
983 };
984
985 let resolve_task = provider.resolve_completions(
986 buffer,
987 matches.iter().map(|m| m.candidate_id).collect(),
988 completions.clone(),
989 cx,
990 );
991
992 return cx.spawn(move |this, mut cx| async move {
993 if let Some(true) = resolve_task.await.log_err() {
994 this.update(&mut cx, |_, cx| cx.notify()).ok();
995 }
996 });
997 }
998
999 fn attempt_resolve_selected_completion_documentation(
1000 &mut self,
1001 project: Option<&Model<Project>>,
1002 cx: &mut ViewContext<Editor>,
1003 ) {
1004 let settings = EditorSettings::get_global(cx);
1005 if !settings.show_completion_documentation {
1006 return;
1007 }
1008
1009 let completion_index = self.matches[self.selected_item].candidate_id;
1010 let Some(project) = project else {
1011 return;
1012 };
1013
1014 let resolve_task = project.update(cx, |project, cx| {
1015 project.resolve_completions(
1016 self.buffer.clone(),
1017 vec![completion_index],
1018 self.completions.clone(),
1019 cx,
1020 )
1021 });
1022
1023 let delay_ms =
1024 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1025 let delay = Duration::from_millis(delay_ms);
1026
1027 self.selected_completion_documentation_resolve_debounce
1028 .lock()
1029 .fire_new(delay, cx, |_, cx| {
1030 cx.spawn(move |this, mut cx| async move {
1031 if let Some(true) = resolve_task.await.log_err() {
1032 this.update(&mut cx, |_, cx| cx.notify()).ok();
1033 }
1034 })
1035 });
1036 }
1037
1038 fn visible(&self) -> bool {
1039 !self.matches.is_empty()
1040 }
1041
1042 fn render(
1043 &self,
1044 style: &EditorStyle,
1045 max_height: Pixels,
1046 workspace: Option<WeakView<Workspace>>,
1047 cx: &mut ViewContext<Editor>,
1048 ) -> AnyElement {
1049 let settings = EditorSettings::get_global(cx);
1050 let show_completion_documentation = settings.show_completion_documentation;
1051
1052 let widest_completion_ix = self
1053 .matches
1054 .iter()
1055 .enumerate()
1056 .max_by_key(|(_, mat)| {
1057 let completions = self.completions.read();
1058 let completion = &completions[mat.candidate_id];
1059 let documentation = &completion.documentation;
1060
1061 let mut len = completion.label.text.chars().count();
1062 if let Some(Documentation::SingleLine(text)) = documentation {
1063 if show_completion_documentation {
1064 len += text.chars().count();
1065 }
1066 }
1067
1068 len
1069 })
1070 .map(|(ix, _)| ix);
1071
1072 let completions = self.completions.clone();
1073 let matches = self.matches.clone();
1074 let selected_item = self.selected_item;
1075 let style = style.clone();
1076
1077 let multiline_docs = if show_completion_documentation {
1078 let mat = &self.matches[selected_item];
1079 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1080 Some(Documentation::MultiLinePlainText(text)) => {
1081 Some(div().child(SharedString::from(text.clone())))
1082 }
1083 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1084 Some(div().child(render_parsed_markdown(
1085 "completions_markdown",
1086 parsed,
1087 &style,
1088 workspace,
1089 cx,
1090 )))
1091 }
1092 _ => None,
1093 };
1094 multiline_docs.map(|div| {
1095 div.id("multiline_docs")
1096 .max_h(max_height)
1097 .flex_1()
1098 .px_1p5()
1099 .py_1()
1100 .min_w(px(260.))
1101 .max_w(px(640.))
1102 .w(px(500.))
1103 .overflow_y_scroll()
1104 .occlude()
1105 })
1106 } else {
1107 None
1108 };
1109
1110 let list = uniform_list(
1111 cx.view().clone(),
1112 "completions",
1113 matches.len(),
1114 move |_editor, range, cx| {
1115 let start_ix = range.start;
1116 let completions_guard = completions.read();
1117
1118 matches[range]
1119 .iter()
1120 .enumerate()
1121 .map(|(ix, mat)| {
1122 let item_ix = start_ix + ix;
1123 let candidate_id = mat.candidate_id;
1124 let completion = &completions_guard[candidate_id];
1125
1126 let documentation = if show_completion_documentation {
1127 &completion.documentation
1128 } else {
1129 &None
1130 };
1131
1132 let highlights = gpui::combine_highlights(
1133 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1134 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1135 |(range, mut highlight)| {
1136 // Ignore font weight for syntax highlighting, as we'll use it
1137 // for fuzzy matches.
1138 highlight.font_weight = None;
1139
1140 if completion.lsp_completion.deprecated.unwrap_or(false) {
1141 highlight.strikethrough = Some(StrikethroughStyle {
1142 thickness: 1.0.into(),
1143 ..Default::default()
1144 });
1145 highlight.color = Some(cx.theme().colors().text_muted);
1146 }
1147
1148 (range, highlight)
1149 },
1150 ),
1151 );
1152 let completion_label = StyledText::new(completion.label.text.clone())
1153 .with_highlights(&style.text, highlights);
1154 let documentation_label =
1155 if let Some(Documentation::SingleLine(text)) = documentation {
1156 if text.trim().is_empty() {
1157 None
1158 } else {
1159 Some(
1160 Label::new(text.clone())
1161 .ml_4()
1162 .size(LabelSize::Small)
1163 .color(Color::Muted),
1164 )
1165 }
1166 } else {
1167 None
1168 };
1169
1170 div().min_w(px(220.)).max_w(px(540.)).child(
1171 ListItem::new(mat.candidate_id)
1172 .inset(true)
1173 .selected(item_ix == selected_item)
1174 .on_click(cx.listener(move |editor, _event, cx| {
1175 cx.stop_propagation();
1176 if let Some(task) = editor.confirm_completion(
1177 &ConfirmCompletion {
1178 item_ix: Some(item_ix),
1179 },
1180 cx,
1181 ) {
1182 task.detach_and_log_err(cx)
1183 }
1184 }))
1185 .child(h_flex().overflow_hidden().child(completion_label))
1186 .end_slot::<Label>(documentation_label),
1187 )
1188 })
1189 .collect()
1190 },
1191 )
1192 .occlude()
1193 .max_h(max_height)
1194 .track_scroll(self.scroll_handle.clone())
1195 .with_width_from_item(widest_completion_ix)
1196 .with_sizing_behavior(ListSizingBehavior::Infer);
1197
1198 Popover::new()
1199 .child(list)
1200 .when_some(multiline_docs, |popover, multiline_docs| {
1201 popover.aside(multiline_docs)
1202 })
1203 .into_any_element()
1204 }
1205
1206 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1207 let mut matches = if let Some(query) = query {
1208 fuzzy::match_strings(
1209 &self.match_candidates,
1210 query,
1211 query.chars().any(|c| c.is_uppercase()),
1212 100,
1213 &Default::default(),
1214 executor,
1215 )
1216 .await
1217 } else {
1218 self.match_candidates
1219 .iter()
1220 .enumerate()
1221 .map(|(candidate_id, candidate)| StringMatch {
1222 candidate_id,
1223 score: Default::default(),
1224 positions: Default::default(),
1225 string: candidate.string.clone(),
1226 })
1227 .collect()
1228 };
1229
1230 // Remove all candidates where the query's start does not match the start of any word in the candidate
1231 if let Some(query) = query {
1232 if let Some(query_start) = query.chars().next() {
1233 matches.retain(|string_match| {
1234 split_words(&string_match.string).any(|word| {
1235 // Check that the first codepoint of the word as lowercase matches the first
1236 // codepoint of the query as lowercase
1237 word.chars()
1238 .flat_map(|codepoint| codepoint.to_lowercase())
1239 .zip(query_start.to_lowercase())
1240 .all(|(word_cp, query_cp)| word_cp == query_cp)
1241 })
1242 });
1243 }
1244 }
1245
1246 let completions = self.completions.read();
1247 if self.sort_completions {
1248 matches.sort_unstable_by_key(|mat| {
1249 // We do want to strike a balance here between what the language server tells us
1250 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1251 // `Creat` and there is a local variable called `CreateComponent`).
1252 // So what we do is: we bucket all matches into two buckets
1253 // - Strong matches
1254 // - Weak matches
1255 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1256 // and the Weak matches are the rest.
1257 //
1258 // For the strong matches, we sort by the language-servers score first and for the weak
1259 // matches, we prefer our fuzzy finder first.
1260 //
1261 // The thinking behind that: it's useless to take the sort_text the language-server gives
1262 // us into account when it's obviously a bad match.
1263
1264 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1265 enum MatchScore<'a> {
1266 Strong {
1267 sort_text: Option<&'a str>,
1268 score: Reverse<OrderedFloat<f64>>,
1269 sort_key: (usize, &'a str),
1270 },
1271 Weak {
1272 score: Reverse<OrderedFloat<f64>>,
1273 sort_text: Option<&'a str>,
1274 sort_key: (usize, &'a str),
1275 },
1276 }
1277
1278 let completion = &completions[mat.candidate_id];
1279 let sort_key = completion.sort_key();
1280 let sort_text = completion.lsp_completion.sort_text.as_deref();
1281 let score = Reverse(OrderedFloat(mat.score));
1282
1283 if mat.score >= 0.2 {
1284 MatchScore::Strong {
1285 sort_text,
1286 score,
1287 sort_key,
1288 }
1289 } else {
1290 MatchScore::Weak {
1291 score,
1292 sort_text,
1293 sort_key,
1294 }
1295 }
1296 });
1297 }
1298
1299 for mat in &mut matches {
1300 let completion = &completions[mat.candidate_id];
1301 mat.string.clone_from(&completion.label.text);
1302 for position in &mut mat.positions {
1303 *position += completion.label.filter_range.start;
1304 }
1305 }
1306 drop(completions);
1307
1308 self.matches = matches.into();
1309 self.selected_item = 0;
1310 }
1311}
1312
1313#[derive(Clone)]
1314struct CodeActionContents {
1315 tasks: Option<Arc<ResolvedTasks>>,
1316 actions: Option<Arc<[CodeAction]>>,
1317}
1318
1319impl CodeActionContents {
1320 fn len(&self) -> usize {
1321 match (&self.tasks, &self.actions) {
1322 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1323 (Some(tasks), None) => tasks.templates.len(),
1324 (None, Some(actions)) => actions.len(),
1325 (None, None) => 0,
1326 }
1327 }
1328
1329 fn is_empty(&self) -> bool {
1330 match (&self.tasks, &self.actions) {
1331 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1332 (Some(tasks), None) => tasks.templates.is_empty(),
1333 (None, Some(actions)) => actions.is_empty(),
1334 (None, None) => true,
1335 }
1336 }
1337
1338 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1339 self.tasks
1340 .iter()
1341 .flat_map(|tasks| {
1342 tasks
1343 .templates
1344 .iter()
1345 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1346 })
1347 .chain(self.actions.iter().flat_map(|actions| {
1348 actions
1349 .iter()
1350 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1351 }))
1352 }
1353 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1354 match (&self.tasks, &self.actions) {
1355 (Some(tasks), Some(actions)) => {
1356 if index < tasks.templates.len() {
1357 tasks
1358 .templates
1359 .get(index)
1360 .cloned()
1361 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1362 } else {
1363 actions
1364 .get(index - tasks.templates.len())
1365 .cloned()
1366 .map(CodeActionsItem::CodeAction)
1367 }
1368 }
1369 (Some(tasks), None) => tasks
1370 .templates
1371 .get(index)
1372 .cloned()
1373 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1374 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1375 (None, None) => None,
1376 }
1377 }
1378}
1379
1380#[allow(clippy::large_enum_variant)]
1381#[derive(Clone)]
1382enum CodeActionsItem {
1383 Task(TaskSourceKind, ResolvedTask),
1384 CodeAction(CodeAction),
1385}
1386
1387impl CodeActionsItem {
1388 fn as_task(&self) -> Option<&ResolvedTask> {
1389 let Self::Task(_, task) = self else {
1390 return None;
1391 };
1392 Some(task)
1393 }
1394 fn as_code_action(&self) -> Option<&CodeAction> {
1395 let Self::CodeAction(action) = self else {
1396 return None;
1397 };
1398 Some(action)
1399 }
1400 fn label(&self) -> String {
1401 match self {
1402 Self::CodeAction(action) => action.lsp_action.title.clone(),
1403 Self::Task(_, task) => task.resolved_label.clone(),
1404 }
1405 }
1406}
1407
1408struct CodeActionsMenu {
1409 actions: CodeActionContents,
1410 buffer: Model<Buffer>,
1411 selected_item: usize,
1412 scroll_handle: UniformListScrollHandle,
1413 deployed_from_indicator: Option<DisplayRow>,
1414}
1415
1416impl CodeActionsMenu {
1417 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1418 self.selected_item = 0;
1419 self.scroll_handle.scroll_to_item(self.selected_item);
1420 cx.notify()
1421 }
1422
1423 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1424 if self.selected_item > 0 {
1425 self.selected_item -= 1;
1426 } else {
1427 self.selected_item = self.actions.len() - 1;
1428 }
1429 self.scroll_handle.scroll_to_item(self.selected_item);
1430 cx.notify();
1431 }
1432
1433 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1434 if self.selected_item + 1 < self.actions.len() {
1435 self.selected_item += 1;
1436 } else {
1437 self.selected_item = 0;
1438 }
1439 self.scroll_handle.scroll_to_item(self.selected_item);
1440 cx.notify();
1441 }
1442
1443 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1444 self.selected_item = self.actions.len() - 1;
1445 self.scroll_handle.scroll_to_item(self.selected_item);
1446 cx.notify()
1447 }
1448
1449 fn visible(&self) -> bool {
1450 !self.actions.is_empty()
1451 }
1452
1453 fn render(
1454 &self,
1455 cursor_position: DisplayPoint,
1456 _style: &EditorStyle,
1457 max_height: Pixels,
1458 cx: &mut ViewContext<Editor>,
1459 ) -> (ContextMenuOrigin, AnyElement) {
1460 let actions = self.actions.clone();
1461 let selected_item = self.selected_item;
1462 let element = uniform_list(
1463 cx.view().clone(),
1464 "code_actions_menu",
1465 self.actions.len(),
1466 move |_this, range, cx| {
1467 actions
1468 .iter()
1469 .skip(range.start)
1470 .take(range.end - range.start)
1471 .enumerate()
1472 .map(|(ix, action)| {
1473 let item_ix = range.start + ix;
1474 let selected = selected_item == item_ix;
1475 let colors = cx.theme().colors();
1476 div()
1477 .px_2()
1478 .text_color(colors.text)
1479 .when(selected, |style| {
1480 style
1481 .bg(colors.element_active)
1482 .text_color(colors.text_accent)
1483 })
1484 .hover(|style| {
1485 style
1486 .bg(colors.element_hover)
1487 .text_color(colors.text_accent)
1488 })
1489 .whitespace_nowrap()
1490 .when_some(action.as_code_action(), |this, action| {
1491 this.on_mouse_down(
1492 MouseButton::Left,
1493 cx.listener(move |editor, _, cx| {
1494 cx.stop_propagation();
1495 if let Some(task) = editor.confirm_code_action(
1496 &ConfirmCodeAction {
1497 item_ix: Some(item_ix),
1498 },
1499 cx,
1500 ) {
1501 task.detach_and_log_err(cx)
1502 }
1503 }),
1504 )
1505 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1506 .child(SharedString::from(action.lsp_action.title.clone()))
1507 })
1508 .when_some(action.as_task(), |this, task| {
1509 this.on_mouse_down(
1510 MouseButton::Left,
1511 cx.listener(move |editor, _, cx| {
1512 cx.stop_propagation();
1513 if let Some(task) = editor.confirm_code_action(
1514 &ConfirmCodeAction {
1515 item_ix: Some(item_ix),
1516 },
1517 cx,
1518 ) {
1519 task.detach_and_log_err(cx)
1520 }
1521 }),
1522 )
1523 .child(SharedString::from(task.resolved_label.clone()))
1524 })
1525 })
1526 .collect()
1527 },
1528 )
1529 .elevation_1(cx)
1530 .px_2()
1531 .py_1()
1532 .max_h(max_height)
1533 .occlude()
1534 .track_scroll(self.scroll_handle.clone())
1535 .with_width_from_item(
1536 self.actions
1537 .iter()
1538 .enumerate()
1539 .max_by_key(|(_, action)| match action {
1540 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1541 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1542 })
1543 .map(|(ix, _)| ix),
1544 )
1545 .with_sizing_behavior(ListSizingBehavior::Infer)
1546 .into_any_element();
1547
1548 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1549 ContextMenuOrigin::GutterIndicator(row)
1550 } else {
1551 ContextMenuOrigin::EditorPoint(cursor_position)
1552 };
1553
1554 (cursor_position, element)
1555 }
1556}
1557
1558#[derive(Debug)]
1559struct ActiveDiagnosticGroup {
1560 primary_range: Range<Anchor>,
1561 primary_message: String,
1562 group_id: usize,
1563 blocks: HashMap<CustomBlockId, Diagnostic>,
1564 is_valid: bool,
1565}
1566
1567#[derive(Serialize, Deserialize, Clone, Debug)]
1568pub struct ClipboardSelection {
1569 pub len: usize,
1570 pub is_entire_line: bool,
1571 pub first_line_indent: u32,
1572}
1573
1574#[derive(Debug)]
1575pub(crate) struct NavigationData {
1576 cursor_anchor: Anchor,
1577 cursor_position: Point,
1578 scroll_anchor: ScrollAnchor,
1579 scroll_top_row: u32,
1580}
1581
1582#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1583enum GotoDefinitionKind {
1584 Symbol,
1585 Declaration,
1586 Type,
1587 Implementation,
1588}
1589
1590#[derive(Debug, Clone)]
1591enum InlayHintRefreshReason {
1592 Toggle(bool),
1593 SettingsChange(InlayHintSettings),
1594 NewLinesShown,
1595 BufferEdited(HashSet<Arc<Language>>),
1596 RefreshRequested,
1597 ExcerptsRemoved(Vec<ExcerptId>),
1598}
1599
1600impl InlayHintRefreshReason {
1601 fn description(&self) -> &'static str {
1602 match self {
1603 Self::Toggle(_) => "toggle",
1604 Self::SettingsChange(_) => "settings change",
1605 Self::NewLinesShown => "new lines shown",
1606 Self::BufferEdited(_) => "buffer edited",
1607 Self::RefreshRequested => "refresh requested",
1608 Self::ExcerptsRemoved(_) => "excerpts removed",
1609 }
1610 }
1611}
1612
1613pub(crate) struct FocusedBlock {
1614 id: BlockId,
1615 focus_handle: WeakFocusHandle,
1616}
1617
1618impl Editor {
1619 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1620 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1621 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1622 Self::new(
1623 EditorMode::SingleLine { auto_width: false },
1624 buffer,
1625 None,
1626 false,
1627 cx,
1628 )
1629 }
1630
1631 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1632 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1633 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1634 Self::new(EditorMode::Full, buffer, None, false, cx)
1635 }
1636
1637 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1638 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1639 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1640 Self::new(
1641 EditorMode::SingleLine { auto_width: true },
1642 buffer,
1643 None,
1644 false,
1645 cx,
1646 )
1647 }
1648
1649 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1650 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1651 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1652 Self::new(
1653 EditorMode::AutoHeight { max_lines },
1654 buffer,
1655 None,
1656 false,
1657 cx,
1658 )
1659 }
1660
1661 pub fn for_buffer(
1662 buffer: Model<Buffer>,
1663 project: Option<Model<Project>>,
1664 cx: &mut ViewContext<Self>,
1665 ) -> Self {
1666 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1667 Self::new(EditorMode::Full, buffer, project, false, cx)
1668 }
1669
1670 pub fn for_multibuffer(
1671 buffer: Model<MultiBuffer>,
1672 project: Option<Model<Project>>,
1673 show_excerpt_controls: bool,
1674 cx: &mut ViewContext<Self>,
1675 ) -> Self {
1676 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1677 }
1678
1679 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1680 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1681 let mut clone = Self::new(
1682 self.mode,
1683 self.buffer.clone(),
1684 self.project.clone(),
1685 show_excerpt_controls,
1686 cx,
1687 );
1688 self.display_map.update(cx, |display_map, cx| {
1689 let snapshot = display_map.snapshot(cx);
1690 clone.display_map.update(cx, |display_map, cx| {
1691 display_map.set_state(&snapshot, cx);
1692 });
1693 });
1694 clone.selections.clone_state(&self.selections);
1695 clone.scroll_manager.clone_state(&self.scroll_manager);
1696 clone.searchable = self.searchable;
1697 clone
1698 }
1699
1700 pub fn new(
1701 mode: EditorMode,
1702 buffer: Model<MultiBuffer>,
1703 project: Option<Model<Project>>,
1704 show_excerpt_controls: bool,
1705 cx: &mut ViewContext<Self>,
1706 ) -> Self {
1707 let style = cx.text_style();
1708 let font_size = style.font_size.to_pixels(cx.rem_size());
1709 let editor = cx.view().downgrade();
1710 let fold_placeholder = FoldPlaceholder {
1711 constrain_width: true,
1712 render: Arc::new(move |fold_id, fold_range, cx| {
1713 let editor = editor.clone();
1714 div()
1715 .id(fold_id)
1716 .bg(cx.theme().colors().ghost_element_background)
1717 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1718 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1719 .rounded_sm()
1720 .size_full()
1721 .cursor_pointer()
1722 .child("⋯")
1723 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1724 .on_click(move |_, cx| {
1725 editor
1726 .update(cx, |editor, cx| {
1727 editor.unfold_ranges(
1728 [fold_range.start..fold_range.end],
1729 true,
1730 false,
1731 cx,
1732 );
1733 cx.stop_propagation();
1734 })
1735 .ok();
1736 })
1737 .into_any()
1738 }),
1739 merge_adjacent: true,
1740 };
1741 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1742 let display_map = cx.new_model(|cx| {
1743 DisplayMap::new(
1744 buffer.clone(),
1745 style.font(),
1746 font_size,
1747 None,
1748 show_excerpt_controls,
1749 file_header_size,
1750 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1751 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1752 fold_placeholder,
1753 cx,
1754 )
1755 });
1756
1757 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1758
1759 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1760
1761 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1762 .then(|| language_settings::SoftWrap::PreferLine);
1763
1764 let mut project_subscriptions = Vec::new();
1765 if mode == EditorMode::Full {
1766 if let Some(project) = project.as_ref() {
1767 if buffer.read(cx).is_singleton() {
1768 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1769 cx.emit(EditorEvent::TitleChanged);
1770 }));
1771 }
1772 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1773 if let project::Event::RefreshInlayHints = event {
1774 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1775 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1776 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1777 let focus_handle = editor.focus_handle(cx);
1778 if focus_handle.is_focused(cx) {
1779 let snapshot = buffer.read(cx).snapshot();
1780 for (range, snippet) in snippet_edits {
1781 let editor_range =
1782 language::range_from_lsp(*range).to_offset(&snapshot);
1783 editor
1784 .insert_snippet(&[editor_range], snippet.clone(), cx)
1785 .ok();
1786 }
1787 }
1788 }
1789 }
1790 }));
1791 let task_inventory = project.read(cx).task_inventory().clone();
1792 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1793 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1794 }));
1795 }
1796 }
1797
1798 let inlay_hint_settings = inlay_hint_settings(
1799 selections.newest_anchor().head(),
1800 &buffer.read(cx).snapshot(cx),
1801 cx,
1802 );
1803 let focus_handle = cx.focus_handle();
1804 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1805 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1806 .detach();
1807 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1808 .detach();
1809 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1810
1811 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1812 Some(false)
1813 } else {
1814 None
1815 };
1816
1817 let mut this = Self {
1818 focus_handle,
1819 show_cursor_when_unfocused: false,
1820 last_focused_descendant: None,
1821 buffer: buffer.clone(),
1822 display_map: display_map.clone(),
1823 selections,
1824 scroll_manager: ScrollManager::new(cx),
1825 columnar_selection_tail: None,
1826 add_selections_state: None,
1827 select_next_state: None,
1828 select_prev_state: None,
1829 selection_history: Default::default(),
1830 autoclose_regions: Default::default(),
1831 snippet_stack: Default::default(),
1832 select_larger_syntax_node_stack: Vec::new(),
1833 ime_transaction: Default::default(),
1834 active_diagnostics: None,
1835 soft_wrap_mode_override,
1836 completion_provider: project.clone().map(|project| Box::new(project) as _),
1837 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1838 project,
1839 blink_manager: blink_manager.clone(),
1840 show_local_selections: true,
1841 mode,
1842 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1843 show_gutter: mode == EditorMode::Full,
1844 show_line_numbers: None,
1845 show_git_diff_gutter: None,
1846 show_code_actions: None,
1847 show_runnables: None,
1848 show_wrap_guides: None,
1849 show_indent_guides,
1850 placeholder_text: None,
1851 highlight_order: 0,
1852 highlighted_rows: HashMap::default(),
1853 background_highlights: Default::default(),
1854 gutter_highlights: TreeMap::default(),
1855 scrollbar_marker_state: ScrollbarMarkerState::default(),
1856 active_indent_guides_state: ActiveIndentGuidesState::default(),
1857 nav_history: None,
1858 context_menu: RwLock::new(None),
1859 mouse_context_menu: None,
1860 completion_tasks: Default::default(),
1861 signature_help_state: SignatureHelpState::default(),
1862 auto_signature_help: None,
1863 find_all_references_task_sources: Vec::new(),
1864 next_completion_id: 0,
1865 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1866 next_inlay_id: 0,
1867 available_code_actions: Default::default(),
1868 code_actions_task: Default::default(),
1869 document_highlights_task: Default::default(),
1870 linked_editing_range_task: Default::default(),
1871 pending_rename: Default::default(),
1872 searchable: true,
1873 cursor_shape: Default::default(),
1874 current_line_highlight: None,
1875 autoindent_mode: Some(AutoindentMode::EachLine),
1876 collapse_matches: false,
1877 workspace: None,
1878 keymap_context_layers: Default::default(),
1879 input_enabled: true,
1880 use_modal_editing: mode == EditorMode::Full,
1881 read_only: false,
1882 use_autoclose: true,
1883 use_auto_surround: true,
1884 auto_replace_emoji_shortcode: false,
1885 leader_peer_id: None,
1886 remote_id: None,
1887 hover_state: Default::default(),
1888 hovered_link_state: Default::default(),
1889 inline_completion_provider: None,
1890 active_inline_completion: None,
1891 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1892 expanded_hunks: ExpandedHunks::default(),
1893 gutter_hovered: false,
1894 pixel_position_of_newest_cursor: None,
1895 last_bounds: None,
1896 expect_bounds_change: None,
1897 gutter_dimensions: GutterDimensions::default(),
1898 style: None,
1899 show_cursor_names: false,
1900 hovered_cursors: Default::default(),
1901 next_editor_action_id: EditorActionId::default(),
1902 editor_actions: Rc::default(),
1903 vim_replace_map: Default::default(),
1904 show_inline_completions: mode == EditorMode::Full,
1905 custom_context_menu: None,
1906 show_git_blame_gutter: false,
1907 show_git_blame_inline: false,
1908 show_selection_menu: None,
1909 show_git_blame_inline_delay_task: None,
1910 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1911 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1912 .session
1913 .restore_unsaved_buffers,
1914 blame: None,
1915 blame_subscription: None,
1916 file_header_size,
1917 tasks: Default::default(),
1918 _subscriptions: vec![
1919 cx.observe(&buffer, Self::on_buffer_changed),
1920 cx.subscribe(&buffer, Self::on_buffer_event),
1921 cx.observe(&display_map, Self::on_display_map_changed),
1922 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1923 cx.observe_global::<SettingsStore>(Self::settings_changed),
1924 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1925 cx.observe_window_activation(|editor, cx| {
1926 let active = cx.is_window_active();
1927 editor.blink_manager.update(cx, |blink_manager, cx| {
1928 if active {
1929 blink_manager.enable(cx);
1930 } else {
1931 blink_manager.disable(cx);
1932 }
1933 });
1934 }),
1935 ],
1936 tasks_update_task: None,
1937 linked_edit_ranges: Default::default(),
1938 previous_search_ranges: None,
1939 breadcrumb_header: None,
1940 focused_block: None,
1941 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1942 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1943 };
1944 this.tasks_update_task = Some(this.refresh_runnables(cx));
1945 this._subscriptions.extend(project_subscriptions);
1946
1947 this.end_selection(cx);
1948 this.scroll_manager.show_scrollbar(cx);
1949
1950 if mode == EditorMode::Full {
1951 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
1952 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
1953
1954 if this.git_blame_inline_enabled {
1955 this.git_blame_inline_enabled = true;
1956 this.start_git_blame_inline(false, cx);
1957 }
1958 }
1959
1960 this.report_editor_event("open", None, cx);
1961 this
1962 }
1963
1964 pub fn mouse_menu_is_focused(&self, cx: &mut WindowContext) -> bool {
1965 self.mouse_context_menu
1966 .as_ref()
1967 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
1968 }
1969
1970 fn key_context(&self, cx: &AppContext) -> KeyContext {
1971 let mut key_context = KeyContext::new_with_defaults();
1972 key_context.add("Editor");
1973 let mode = match self.mode {
1974 EditorMode::SingleLine { .. } => "single_line",
1975 EditorMode::AutoHeight { .. } => "auto_height",
1976 EditorMode::Full => "full",
1977 };
1978
1979 if EditorSettings::jupyter_enabled(cx) {
1980 key_context.add("jupyter");
1981 }
1982
1983 key_context.set("mode", mode);
1984 if self.pending_rename.is_some() {
1985 key_context.add("renaming");
1986 }
1987 if self.context_menu_visible() {
1988 match self.context_menu.read().as_ref() {
1989 Some(ContextMenu::Completions(_)) => {
1990 key_context.add("menu");
1991 key_context.add("showing_completions")
1992 }
1993 Some(ContextMenu::CodeActions(_)) => {
1994 key_context.add("menu");
1995 key_context.add("showing_code_actions")
1996 }
1997 None => {}
1998 }
1999 }
2000
2001 for layer in self.keymap_context_layers.values() {
2002 key_context.extend(layer);
2003 }
2004
2005 if let Some(extension) = self
2006 .buffer
2007 .read(cx)
2008 .as_singleton()
2009 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2010 {
2011 key_context.set("extension", extension.to_string());
2012 }
2013
2014 if self.has_active_inline_completion(cx) {
2015 key_context.add("copilot_suggestion");
2016 key_context.add("inline_completion");
2017 }
2018
2019 key_context
2020 }
2021
2022 pub fn new_file(
2023 workspace: &mut Workspace,
2024 _: &workspace::NewFile,
2025 cx: &mut ViewContext<Workspace>,
2026 ) {
2027 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2028 "Failed to create buffer",
2029 cx,
2030 |e, _| match e.error_code() {
2031 ErrorCode::RemoteUpgradeRequired => Some(format!(
2032 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2033 e.error_tag("required").unwrap_or("the latest version")
2034 )),
2035 _ => None,
2036 },
2037 );
2038 }
2039
2040 pub fn new_in_workspace(
2041 workspace: &mut Workspace,
2042 cx: &mut ViewContext<Workspace>,
2043 ) -> Task<Result<View<Editor>>> {
2044 let project = workspace.project().clone();
2045 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2046
2047 cx.spawn(|workspace, mut cx| async move {
2048 let buffer = create.await?;
2049 workspace.update(&mut cx, |workspace, cx| {
2050 let editor =
2051 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2052 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2053 editor
2054 })
2055 })
2056 }
2057
2058 pub fn new_file_in_direction(
2059 workspace: &mut Workspace,
2060 action: &workspace::NewFileInDirection,
2061 cx: &mut ViewContext<Workspace>,
2062 ) {
2063 let project = workspace.project().clone();
2064 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2065 let direction = action.0;
2066
2067 cx.spawn(|workspace, mut cx| async move {
2068 let buffer = create.await?;
2069 workspace.update(&mut cx, move |workspace, cx| {
2070 workspace.split_item(
2071 direction,
2072 Box::new(
2073 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2074 ),
2075 cx,
2076 )
2077 })?;
2078 anyhow::Ok(())
2079 })
2080 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2081 ErrorCode::RemoteUpgradeRequired => Some(format!(
2082 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2083 e.error_tag("required").unwrap_or("the latest version")
2084 )),
2085 _ => None,
2086 });
2087 }
2088
2089 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2090 self.buffer.read(cx).replica_id()
2091 }
2092
2093 pub fn leader_peer_id(&self) -> Option<PeerId> {
2094 self.leader_peer_id
2095 }
2096
2097 pub fn buffer(&self) -> &Model<MultiBuffer> {
2098 &self.buffer
2099 }
2100
2101 pub fn workspace(&self) -> Option<View<Workspace>> {
2102 self.workspace.as_ref()?.0.upgrade()
2103 }
2104
2105 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2106 self.buffer().read(cx).title(cx)
2107 }
2108
2109 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2110 EditorSnapshot {
2111 mode: self.mode,
2112 show_gutter: self.show_gutter,
2113 show_line_numbers: self.show_line_numbers,
2114 show_git_diff_gutter: self.show_git_diff_gutter,
2115 show_code_actions: self.show_code_actions,
2116 show_runnables: self.show_runnables,
2117 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2118 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2119 scroll_anchor: self.scroll_manager.anchor(),
2120 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2121 placeholder_text: self.placeholder_text.clone(),
2122 is_focused: self.focus_handle.is_focused(cx),
2123 current_line_highlight: self
2124 .current_line_highlight
2125 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2126 gutter_hovered: self.gutter_hovered,
2127 }
2128 }
2129
2130 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2131 self.buffer.read(cx).language_at(point, cx)
2132 }
2133
2134 pub fn file_at<T: ToOffset>(
2135 &self,
2136 point: T,
2137 cx: &AppContext,
2138 ) -> Option<Arc<dyn language::File>> {
2139 self.buffer.read(cx).read(cx).file_at(point).cloned()
2140 }
2141
2142 pub fn active_excerpt(
2143 &self,
2144 cx: &AppContext,
2145 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2146 self.buffer
2147 .read(cx)
2148 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2149 }
2150
2151 pub fn mode(&self) -> EditorMode {
2152 self.mode
2153 }
2154
2155 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2156 self.collaboration_hub.as_deref()
2157 }
2158
2159 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2160 self.collaboration_hub = Some(hub);
2161 }
2162
2163 pub fn set_custom_context_menu(
2164 &mut self,
2165 f: impl 'static
2166 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2167 ) {
2168 self.custom_context_menu = Some(Box::new(f))
2169 }
2170
2171 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2172 self.completion_provider = Some(provider);
2173 }
2174
2175 pub fn set_inline_completion_provider<T>(
2176 &mut self,
2177 provider: Option<Model<T>>,
2178 cx: &mut ViewContext<Self>,
2179 ) where
2180 T: InlineCompletionProvider,
2181 {
2182 self.inline_completion_provider =
2183 provider.map(|provider| RegisteredInlineCompletionProvider {
2184 _subscription: cx.observe(&provider, |this, _, cx| {
2185 if this.focus_handle.is_focused(cx) {
2186 this.update_visible_inline_completion(cx);
2187 }
2188 }),
2189 provider: Arc::new(provider),
2190 });
2191 self.refresh_inline_completion(false, cx);
2192 }
2193
2194 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2195 self.placeholder_text.as_deref()
2196 }
2197
2198 pub fn set_placeholder_text(
2199 &mut self,
2200 placeholder_text: impl Into<Arc<str>>,
2201 cx: &mut ViewContext<Self>,
2202 ) {
2203 let placeholder_text = Some(placeholder_text.into());
2204 if self.placeholder_text != placeholder_text {
2205 self.placeholder_text = placeholder_text;
2206 cx.notify();
2207 }
2208 }
2209
2210 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2211 self.cursor_shape = cursor_shape;
2212
2213 // Disrupt blink for immediate user feedback that the cursor shape has changed
2214 self.blink_manager.update(cx, BlinkManager::show_cursor);
2215
2216 cx.notify();
2217 }
2218
2219 pub fn set_current_line_highlight(
2220 &mut self,
2221 current_line_highlight: Option<CurrentLineHighlight>,
2222 ) {
2223 self.current_line_highlight = current_line_highlight;
2224 }
2225
2226 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2227 self.collapse_matches = collapse_matches;
2228 }
2229
2230 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2231 if self.collapse_matches {
2232 return range.start..range.start;
2233 }
2234 range.clone()
2235 }
2236
2237 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2238 if self.display_map.read(cx).clip_at_line_ends != clip {
2239 self.display_map
2240 .update(cx, |map, _| map.clip_at_line_ends = clip);
2241 }
2242 }
2243
2244 pub fn set_keymap_context_layer<Tag: 'static>(
2245 &mut self,
2246 context: KeyContext,
2247 cx: &mut ViewContext<Self>,
2248 ) {
2249 self.keymap_context_layers
2250 .insert(TypeId::of::<Tag>(), context);
2251 cx.notify();
2252 }
2253
2254 pub fn remove_keymap_context_layer<Tag: 'static>(&mut self, cx: &mut ViewContext<Self>) {
2255 self.keymap_context_layers.remove(&TypeId::of::<Tag>());
2256 cx.notify();
2257 }
2258
2259 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2260 self.input_enabled = input_enabled;
2261 }
2262
2263 pub fn set_autoindent(&mut self, autoindent: bool) {
2264 if autoindent {
2265 self.autoindent_mode = Some(AutoindentMode::EachLine);
2266 } else {
2267 self.autoindent_mode = None;
2268 }
2269 }
2270
2271 pub fn read_only(&self, cx: &AppContext) -> bool {
2272 self.read_only || self.buffer.read(cx).read_only()
2273 }
2274
2275 pub fn set_read_only(&mut self, read_only: bool) {
2276 self.read_only = read_only;
2277 }
2278
2279 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2280 self.use_autoclose = autoclose;
2281 }
2282
2283 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2284 self.use_auto_surround = auto_surround;
2285 }
2286
2287 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2288 self.auto_replace_emoji_shortcode = auto_replace;
2289 }
2290
2291 pub fn set_show_inline_completions(&mut self, show_inline_completions: bool) {
2292 self.show_inline_completions = show_inline_completions;
2293 }
2294
2295 pub fn set_use_modal_editing(&mut self, to: bool) {
2296 self.use_modal_editing = to;
2297 }
2298
2299 pub fn use_modal_editing(&self) -> bool {
2300 self.use_modal_editing
2301 }
2302
2303 fn selections_did_change(
2304 &mut self,
2305 local: bool,
2306 old_cursor_position: &Anchor,
2307 show_completions: bool,
2308 cx: &mut ViewContext<Self>,
2309 ) {
2310 // Copy selections to primary selection buffer
2311 #[cfg(target_os = "linux")]
2312 if local {
2313 let selections = self.selections.all::<usize>(cx);
2314 let buffer_handle = self.buffer.read(cx).read(cx);
2315
2316 let mut text = String::new();
2317 for (index, selection) in selections.iter().enumerate() {
2318 let text_for_selection = buffer_handle
2319 .text_for_range(selection.start..selection.end)
2320 .collect::<String>();
2321
2322 text.push_str(&text_for_selection);
2323 if index != selections.len() - 1 {
2324 text.push('\n');
2325 }
2326 }
2327
2328 if !text.is_empty() {
2329 cx.write_to_primary(ClipboardItem::new_string(text));
2330 }
2331 }
2332
2333 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2334 self.buffer.update(cx, |buffer, cx| {
2335 buffer.set_active_selections(
2336 &self.selections.disjoint_anchors(),
2337 self.selections.line_mode,
2338 self.cursor_shape,
2339 cx,
2340 )
2341 });
2342 }
2343 let display_map = self
2344 .display_map
2345 .update(cx, |display_map, cx| display_map.snapshot(cx));
2346 let buffer = &display_map.buffer_snapshot;
2347 self.add_selections_state = None;
2348 self.select_next_state = None;
2349 self.select_prev_state = None;
2350 self.select_larger_syntax_node_stack.clear();
2351 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2352 self.snippet_stack
2353 .invalidate(&self.selections.disjoint_anchors(), buffer);
2354 self.take_rename(false, cx);
2355
2356 let new_cursor_position = self.selections.newest_anchor().head();
2357
2358 self.push_to_nav_history(
2359 *old_cursor_position,
2360 Some(new_cursor_position.to_point(buffer)),
2361 cx,
2362 );
2363
2364 if local {
2365 let new_cursor_position = self.selections.newest_anchor().head();
2366 let mut context_menu = self.context_menu.write();
2367 let completion_menu = match context_menu.as_ref() {
2368 Some(ContextMenu::Completions(menu)) => Some(menu),
2369
2370 _ => {
2371 *context_menu = None;
2372 None
2373 }
2374 };
2375
2376 if let Some(completion_menu) = completion_menu {
2377 let cursor_position = new_cursor_position.to_offset(buffer);
2378 let (word_range, kind) = buffer.surrounding_word(completion_menu.initial_position);
2379 if kind == Some(CharKind::Word)
2380 && word_range.to_inclusive().contains(&cursor_position)
2381 {
2382 let mut completion_menu = completion_menu.clone();
2383 drop(context_menu);
2384
2385 let query = Self::completion_query(buffer, cursor_position);
2386 cx.spawn(move |this, mut cx| async move {
2387 completion_menu
2388 .filter(query.as_deref(), cx.background_executor().clone())
2389 .await;
2390
2391 this.update(&mut cx, |this, cx| {
2392 let mut context_menu = this.context_menu.write();
2393 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2394 return;
2395 };
2396
2397 if menu.id > completion_menu.id {
2398 return;
2399 }
2400
2401 *context_menu = Some(ContextMenu::Completions(completion_menu));
2402 drop(context_menu);
2403 cx.notify();
2404 })
2405 })
2406 .detach();
2407
2408 if show_completions {
2409 self.show_completions(&ShowCompletions { trigger: None }, cx);
2410 }
2411 } else {
2412 drop(context_menu);
2413 self.hide_context_menu(cx);
2414 }
2415 } else {
2416 drop(context_menu);
2417 }
2418
2419 hide_hover(self, cx);
2420
2421 if old_cursor_position.to_display_point(&display_map).row()
2422 != new_cursor_position.to_display_point(&display_map).row()
2423 {
2424 self.available_code_actions.take();
2425 }
2426 self.refresh_code_actions(cx);
2427 self.refresh_document_highlights(cx);
2428 refresh_matching_bracket_highlights(self, cx);
2429 self.discard_inline_completion(false, cx);
2430 linked_editing_ranges::refresh_linked_ranges(self, cx);
2431 if self.git_blame_inline_enabled {
2432 self.start_inline_blame_timer(cx);
2433 }
2434 }
2435
2436 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2437 cx.emit(EditorEvent::SelectionsChanged { local });
2438
2439 if self.selections.disjoint_anchors().len() == 1 {
2440 cx.emit(SearchEvent::ActiveMatchChanged)
2441 }
2442 cx.notify();
2443 }
2444
2445 pub fn change_selections<R>(
2446 &mut self,
2447 autoscroll: Option<Autoscroll>,
2448 cx: &mut ViewContext<Self>,
2449 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2450 ) -> R {
2451 self.change_selections_inner(autoscroll, true, cx, change)
2452 }
2453
2454 pub fn change_selections_inner<R>(
2455 &mut self,
2456 autoscroll: Option<Autoscroll>,
2457 request_completions: bool,
2458 cx: &mut ViewContext<Self>,
2459 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2460 ) -> R {
2461 let old_cursor_position = self.selections.newest_anchor().head();
2462 self.push_to_selection_history();
2463
2464 let (changed, result) = self.selections.change_with(cx, change);
2465
2466 if changed {
2467 if let Some(autoscroll) = autoscroll {
2468 self.request_autoscroll(autoscroll, cx);
2469 }
2470 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2471
2472 if self.should_open_signature_help_automatically(
2473 &old_cursor_position,
2474 self.signature_help_state.backspace_pressed(),
2475 cx,
2476 ) {
2477 self.show_signature_help(&ShowSignatureHelp, cx);
2478 }
2479 self.signature_help_state.set_backspace_pressed(false);
2480 }
2481
2482 result
2483 }
2484
2485 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2486 where
2487 I: IntoIterator<Item = (Range<S>, T)>,
2488 S: ToOffset,
2489 T: Into<Arc<str>>,
2490 {
2491 if self.read_only(cx) {
2492 return;
2493 }
2494
2495 self.buffer
2496 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2497 }
2498
2499 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2500 where
2501 I: IntoIterator<Item = (Range<S>, T)>,
2502 S: ToOffset,
2503 T: Into<Arc<str>>,
2504 {
2505 if self.read_only(cx) {
2506 return;
2507 }
2508
2509 self.buffer.update(cx, |buffer, cx| {
2510 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2511 });
2512 }
2513
2514 pub fn edit_with_block_indent<I, S, T>(
2515 &mut self,
2516 edits: I,
2517 original_indent_columns: Vec<u32>,
2518 cx: &mut ViewContext<Self>,
2519 ) where
2520 I: IntoIterator<Item = (Range<S>, T)>,
2521 S: ToOffset,
2522 T: Into<Arc<str>>,
2523 {
2524 if self.read_only(cx) {
2525 return;
2526 }
2527
2528 self.buffer.update(cx, |buffer, cx| {
2529 buffer.edit(
2530 edits,
2531 Some(AutoindentMode::Block {
2532 original_indent_columns,
2533 }),
2534 cx,
2535 )
2536 });
2537 }
2538
2539 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2540 self.hide_context_menu(cx);
2541
2542 match phase {
2543 SelectPhase::Begin {
2544 position,
2545 add,
2546 click_count,
2547 } => self.begin_selection(position, add, click_count, cx),
2548 SelectPhase::BeginColumnar {
2549 position,
2550 goal_column,
2551 reset,
2552 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2553 SelectPhase::Extend {
2554 position,
2555 click_count,
2556 } => self.extend_selection(position, click_count, cx),
2557 SelectPhase::Update {
2558 position,
2559 goal_column,
2560 scroll_delta,
2561 } => self.update_selection(position, goal_column, scroll_delta, cx),
2562 SelectPhase::End => self.end_selection(cx),
2563 }
2564 }
2565
2566 fn extend_selection(
2567 &mut self,
2568 position: DisplayPoint,
2569 click_count: usize,
2570 cx: &mut ViewContext<Self>,
2571 ) {
2572 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2573 let tail = self.selections.newest::<usize>(cx).tail();
2574 self.begin_selection(position, false, click_count, cx);
2575
2576 let position = position.to_offset(&display_map, Bias::Left);
2577 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2578
2579 let mut pending_selection = self
2580 .selections
2581 .pending_anchor()
2582 .expect("extend_selection not called with pending selection");
2583 if position >= tail {
2584 pending_selection.start = tail_anchor;
2585 } else {
2586 pending_selection.end = tail_anchor;
2587 pending_selection.reversed = true;
2588 }
2589
2590 let mut pending_mode = self.selections.pending_mode().unwrap();
2591 match &mut pending_mode {
2592 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2593 _ => {}
2594 }
2595
2596 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2597 s.set_pending(pending_selection, pending_mode)
2598 });
2599 }
2600
2601 fn begin_selection(
2602 &mut self,
2603 position: DisplayPoint,
2604 add: bool,
2605 click_count: usize,
2606 cx: &mut ViewContext<Self>,
2607 ) {
2608 if !self.focus_handle.is_focused(cx) {
2609 self.last_focused_descendant = None;
2610 cx.focus(&self.focus_handle);
2611 }
2612
2613 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2614 let buffer = &display_map.buffer_snapshot;
2615 let newest_selection = self.selections.newest_anchor().clone();
2616 let position = display_map.clip_point(position, Bias::Left);
2617
2618 let start;
2619 let end;
2620 let mode;
2621 let auto_scroll;
2622 match click_count {
2623 1 => {
2624 start = buffer.anchor_before(position.to_point(&display_map));
2625 end = start;
2626 mode = SelectMode::Character;
2627 auto_scroll = true;
2628 }
2629 2 => {
2630 let range = movement::surrounding_word(&display_map, position);
2631 start = buffer.anchor_before(range.start.to_point(&display_map));
2632 end = buffer.anchor_before(range.end.to_point(&display_map));
2633 mode = SelectMode::Word(start..end);
2634 auto_scroll = true;
2635 }
2636 3 => {
2637 let position = display_map
2638 .clip_point(position, Bias::Left)
2639 .to_point(&display_map);
2640 let line_start = display_map.prev_line_boundary(position).0;
2641 let next_line_start = buffer.clip_point(
2642 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2643 Bias::Left,
2644 );
2645 start = buffer.anchor_before(line_start);
2646 end = buffer.anchor_before(next_line_start);
2647 mode = SelectMode::Line(start..end);
2648 auto_scroll = true;
2649 }
2650 _ => {
2651 start = buffer.anchor_before(0);
2652 end = buffer.anchor_before(buffer.len());
2653 mode = SelectMode::All;
2654 auto_scroll = false;
2655 }
2656 }
2657
2658 let point_to_delete: Option<usize> = {
2659 let selected_points: Vec<Selection<Point>> =
2660 self.selections.disjoint_in_range(start..end, cx);
2661
2662 if !add || click_count > 1 {
2663 None
2664 } else if selected_points.len() > 0 {
2665 Some(selected_points[0].id)
2666 } else {
2667 let clicked_point_already_selected =
2668 self.selections.disjoint.iter().find(|selection| {
2669 selection.start.to_point(buffer) == start.to_point(buffer)
2670 || selection.end.to_point(buffer) == end.to_point(buffer)
2671 });
2672
2673 if let Some(selection) = clicked_point_already_selected {
2674 Some(selection.id)
2675 } else {
2676 None
2677 }
2678 }
2679 };
2680
2681 let selections_count = self.selections.count();
2682
2683 self.change_selections(auto_scroll.then(|| Autoscroll::newest()), cx, |s| {
2684 if let Some(point_to_delete) = point_to_delete {
2685 s.delete(point_to_delete);
2686
2687 if selections_count == 1 {
2688 s.set_pending_anchor_range(start..end, mode);
2689 }
2690 } else {
2691 if !add {
2692 s.clear_disjoint();
2693 } else if click_count > 1 {
2694 s.delete(newest_selection.id)
2695 }
2696
2697 s.set_pending_anchor_range(start..end, mode);
2698 }
2699 });
2700 }
2701
2702 fn begin_columnar_selection(
2703 &mut self,
2704 position: DisplayPoint,
2705 goal_column: u32,
2706 reset: bool,
2707 cx: &mut ViewContext<Self>,
2708 ) {
2709 if !self.focus_handle.is_focused(cx) {
2710 self.last_focused_descendant = None;
2711 cx.focus(&self.focus_handle);
2712 }
2713
2714 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2715
2716 if reset {
2717 let pointer_position = display_map
2718 .buffer_snapshot
2719 .anchor_before(position.to_point(&display_map));
2720
2721 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2722 s.clear_disjoint();
2723 s.set_pending_anchor_range(
2724 pointer_position..pointer_position,
2725 SelectMode::Character,
2726 );
2727 });
2728 }
2729
2730 let tail = self.selections.newest::<Point>(cx).tail();
2731 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2732
2733 if !reset {
2734 self.select_columns(
2735 tail.to_display_point(&display_map),
2736 position,
2737 goal_column,
2738 &display_map,
2739 cx,
2740 );
2741 }
2742 }
2743
2744 fn update_selection(
2745 &mut self,
2746 position: DisplayPoint,
2747 goal_column: u32,
2748 scroll_delta: gpui::Point<f32>,
2749 cx: &mut ViewContext<Self>,
2750 ) {
2751 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2752
2753 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2754 let tail = tail.to_display_point(&display_map);
2755 self.select_columns(tail, position, goal_column, &display_map, cx);
2756 } else if let Some(mut pending) = self.selections.pending_anchor() {
2757 let buffer = self.buffer.read(cx).snapshot(cx);
2758 let head;
2759 let tail;
2760 let mode = self.selections.pending_mode().unwrap();
2761 match &mode {
2762 SelectMode::Character => {
2763 head = position.to_point(&display_map);
2764 tail = pending.tail().to_point(&buffer);
2765 }
2766 SelectMode::Word(original_range) => {
2767 let original_display_range = original_range.start.to_display_point(&display_map)
2768 ..original_range.end.to_display_point(&display_map);
2769 let original_buffer_range = original_display_range.start.to_point(&display_map)
2770 ..original_display_range.end.to_point(&display_map);
2771 if movement::is_inside_word(&display_map, position)
2772 || original_display_range.contains(&position)
2773 {
2774 let word_range = movement::surrounding_word(&display_map, position);
2775 if word_range.start < original_display_range.start {
2776 head = word_range.start.to_point(&display_map);
2777 } else {
2778 head = word_range.end.to_point(&display_map);
2779 }
2780 } else {
2781 head = position.to_point(&display_map);
2782 }
2783
2784 if head <= original_buffer_range.start {
2785 tail = original_buffer_range.end;
2786 } else {
2787 tail = original_buffer_range.start;
2788 }
2789 }
2790 SelectMode::Line(original_range) => {
2791 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2792
2793 let position = display_map
2794 .clip_point(position, Bias::Left)
2795 .to_point(&display_map);
2796 let line_start = display_map.prev_line_boundary(position).0;
2797 let next_line_start = buffer.clip_point(
2798 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2799 Bias::Left,
2800 );
2801
2802 if line_start < original_range.start {
2803 head = line_start
2804 } else {
2805 head = next_line_start
2806 }
2807
2808 if head <= original_range.start {
2809 tail = original_range.end;
2810 } else {
2811 tail = original_range.start;
2812 }
2813 }
2814 SelectMode::All => {
2815 return;
2816 }
2817 };
2818
2819 if head < tail {
2820 pending.start = buffer.anchor_before(head);
2821 pending.end = buffer.anchor_before(tail);
2822 pending.reversed = true;
2823 } else {
2824 pending.start = buffer.anchor_before(tail);
2825 pending.end = buffer.anchor_before(head);
2826 pending.reversed = false;
2827 }
2828
2829 self.change_selections(None, cx, |s| {
2830 s.set_pending(pending, mode);
2831 });
2832 } else {
2833 log::error!("update_selection dispatched with no pending selection");
2834 return;
2835 }
2836
2837 self.apply_scroll_delta(scroll_delta, cx);
2838 cx.notify();
2839 }
2840
2841 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2842 self.columnar_selection_tail.take();
2843 if self.selections.pending_anchor().is_some() {
2844 let selections = self.selections.all::<usize>(cx);
2845 self.change_selections(None, cx, |s| {
2846 s.select(selections);
2847 s.clear_pending();
2848 });
2849 }
2850 }
2851
2852 fn select_columns(
2853 &mut self,
2854 tail: DisplayPoint,
2855 head: DisplayPoint,
2856 goal_column: u32,
2857 display_map: &DisplaySnapshot,
2858 cx: &mut ViewContext<Self>,
2859 ) {
2860 let start_row = cmp::min(tail.row(), head.row());
2861 let end_row = cmp::max(tail.row(), head.row());
2862 let start_column = cmp::min(tail.column(), goal_column);
2863 let end_column = cmp::max(tail.column(), goal_column);
2864 let reversed = start_column < tail.column();
2865
2866 let selection_ranges = (start_row.0..=end_row.0)
2867 .map(DisplayRow)
2868 .filter_map(|row| {
2869 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2870 let start = display_map
2871 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2872 .to_point(display_map);
2873 let end = display_map
2874 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2875 .to_point(display_map);
2876 if reversed {
2877 Some(end..start)
2878 } else {
2879 Some(start..end)
2880 }
2881 } else {
2882 None
2883 }
2884 })
2885 .collect::<Vec<_>>();
2886
2887 self.change_selections(None, cx, |s| {
2888 s.select_ranges(selection_ranges);
2889 });
2890 cx.notify();
2891 }
2892
2893 pub fn has_pending_nonempty_selection(&self) -> bool {
2894 let pending_nonempty_selection = match self.selections.pending_anchor() {
2895 Some(Selection { start, end, .. }) => start != end,
2896 None => false,
2897 };
2898
2899 pending_nonempty_selection
2900 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2901 }
2902
2903 pub fn has_pending_selection(&self) -> bool {
2904 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2905 }
2906
2907 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
2908 if self.clear_clicked_diff_hunks(cx) {
2909 cx.notify();
2910 return;
2911 }
2912 if self.dismiss_menus_and_popups(true, cx) {
2913 return;
2914 }
2915
2916 if self.mode == EditorMode::Full {
2917 if self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel()) {
2918 return;
2919 }
2920 }
2921
2922 cx.propagate();
2923 }
2924
2925 pub fn dismiss_menus_and_popups(
2926 &mut self,
2927 should_report_inline_completion_event: bool,
2928 cx: &mut ViewContext<Self>,
2929 ) -> bool {
2930 if self.take_rename(false, cx).is_some() {
2931 return true;
2932 }
2933
2934 if hide_hover(self, cx) {
2935 return true;
2936 }
2937
2938 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
2939 return true;
2940 }
2941
2942 if self.hide_context_menu(cx).is_some() {
2943 return true;
2944 }
2945
2946 if self.mouse_context_menu.take().is_some() {
2947 return true;
2948 }
2949
2950 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
2951 return true;
2952 }
2953
2954 if self.snippet_stack.pop().is_some() {
2955 return true;
2956 }
2957
2958 if self.mode == EditorMode::Full {
2959 if self.active_diagnostics.is_some() {
2960 self.dismiss_diagnostics(cx);
2961 return true;
2962 }
2963 }
2964
2965 false
2966 }
2967
2968 fn linked_editing_ranges_for(
2969 &self,
2970 selection: Range<text::Anchor>,
2971 cx: &AppContext,
2972 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
2973 if self.linked_edit_ranges.is_empty() {
2974 return None;
2975 }
2976 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
2977 selection.end.buffer_id.and_then(|end_buffer_id| {
2978 if selection.start.buffer_id != Some(end_buffer_id) {
2979 return None;
2980 }
2981 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
2982 let snapshot = buffer.read(cx).snapshot();
2983 self.linked_edit_ranges
2984 .get(end_buffer_id, selection.start..selection.end, &snapshot)
2985 .map(|ranges| (ranges, snapshot, buffer))
2986 })?;
2987 use text::ToOffset as TO;
2988 // find offset from the start of current range to current cursor position
2989 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
2990
2991 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
2992 let start_difference = start_offset - start_byte_offset;
2993 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
2994 let end_difference = end_offset - start_byte_offset;
2995 // Current range has associated linked ranges.
2996 let mut linked_edits = HashMap::<_, Vec<_>>::default();
2997 for range in linked_ranges.iter() {
2998 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
2999 let end_offset = start_offset + end_difference;
3000 let start_offset = start_offset + start_difference;
3001 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3002 continue;
3003 }
3004 let start = buffer_snapshot.anchor_after(start_offset);
3005 let end = buffer_snapshot.anchor_after(end_offset);
3006 linked_edits
3007 .entry(buffer.clone())
3008 .or_default()
3009 .push(start..end);
3010 }
3011 Some(linked_edits)
3012 }
3013
3014 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3015 let text: Arc<str> = text.into();
3016
3017 if self.read_only(cx) {
3018 return;
3019 }
3020
3021 let selections = self.selections.all_adjusted(cx);
3022 let mut bracket_inserted = false;
3023 let mut edits = Vec::new();
3024 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3025 let mut new_selections = Vec::with_capacity(selections.len());
3026 let mut new_autoclose_regions = Vec::new();
3027 let snapshot = self.buffer.read(cx).read(cx);
3028
3029 for (selection, autoclose_region) in
3030 self.selections_with_autoclose_regions(selections, &snapshot)
3031 {
3032 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3033 // Determine if the inserted text matches the opening or closing
3034 // bracket of any of this language's bracket pairs.
3035 let mut bracket_pair = None;
3036 let mut is_bracket_pair_start = false;
3037 let mut is_bracket_pair_end = false;
3038 if !text.is_empty() {
3039 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3040 // and they are removing the character that triggered IME popup.
3041 for (pair, enabled) in scope.brackets() {
3042 if !pair.close && !pair.surround {
3043 continue;
3044 }
3045
3046 if enabled && pair.start.ends_with(text.as_ref()) {
3047 bracket_pair = Some(pair.clone());
3048 is_bracket_pair_start = true;
3049 break;
3050 }
3051 if pair.end.as_str() == text.as_ref() {
3052 bracket_pair = Some(pair.clone());
3053 is_bracket_pair_end = true;
3054 break;
3055 }
3056 }
3057 }
3058
3059 if let Some(bracket_pair) = bracket_pair {
3060 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3061 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3062 let auto_surround =
3063 self.use_auto_surround && snapshot_settings.use_auto_surround;
3064 if selection.is_empty() {
3065 if is_bracket_pair_start {
3066 let prefix_len = bracket_pair.start.len() - text.len();
3067
3068 // If the inserted text is a suffix of an opening bracket and the
3069 // selection is preceded by the rest of the opening bracket, then
3070 // insert the closing bracket.
3071 let following_text_allows_autoclose = snapshot
3072 .chars_at(selection.start)
3073 .next()
3074 .map_or(true, |c| scope.should_autoclose_before(c));
3075 let preceding_text_matches_prefix = prefix_len == 0
3076 || (selection.start.column >= (prefix_len as u32)
3077 && snapshot.contains_str_at(
3078 Point::new(
3079 selection.start.row,
3080 selection.start.column - (prefix_len as u32),
3081 ),
3082 &bracket_pair.start[..prefix_len],
3083 ));
3084
3085 if autoclose
3086 && bracket_pair.close
3087 && following_text_allows_autoclose
3088 && preceding_text_matches_prefix
3089 {
3090 let anchor = snapshot.anchor_before(selection.end);
3091 new_selections.push((selection.map(|_| anchor), text.len()));
3092 new_autoclose_regions.push((
3093 anchor,
3094 text.len(),
3095 selection.id,
3096 bracket_pair.clone(),
3097 ));
3098 edits.push((
3099 selection.range(),
3100 format!("{}{}", text, bracket_pair.end).into(),
3101 ));
3102 bracket_inserted = true;
3103 continue;
3104 }
3105 }
3106
3107 if let Some(region) = autoclose_region {
3108 // If the selection is followed by an auto-inserted closing bracket,
3109 // then don't insert that closing bracket again; just move the selection
3110 // past the closing bracket.
3111 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3112 && text.as_ref() == region.pair.end.as_str();
3113 if should_skip {
3114 let anchor = snapshot.anchor_after(selection.end);
3115 new_selections
3116 .push((selection.map(|_| anchor), region.pair.end.len()));
3117 continue;
3118 }
3119 }
3120
3121 let always_treat_brackets_as_autoclosed = snapshot
3122 .settings_at(selection.start, cx)
3123 .always_treat_brackets_as_autoclosed;
3124 if always_treat_brackets_as_autoclosed
3125 && is_bracket_pair_end
3126 && snapshot.contains_str_at(selection.end, text.as_ref())
3127 {
3128 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3129 // and the inserted text is a closing bracket and the selection is followed
3130 // by the closing bracket then move the selection past the closing bracket.
3131 let anchor = snapshot.anchor_after(selection.end);
3132 new_selections.push((selection.map(|_| anchor), text.len()));
3133 continue;
3134 }
3135 }
3136 // If an opening bracket is 1 character long and is typed while
3137 // text is selected, then surround that text with the bracket pair.
3138 else if auto_surround
3139 && bracket_pair.surround
3140 && is_bracket_pair_start
3141 && bracket_pair.start.chars().count() == 1
3142 {
3143 edits.push((selection.start..selection.start, text.clone()));
3144 edits.push((
3145 selection.end..selection.end,
3146 bracket_pair.end.as_str().into(),
3147 ));
3148 bracket_inserted = true;
3149 new_selections.push((
3150 Selection {
3151 id: selection.id,
3152 start: snapshot.anchor_after(selection.start),
3153 end: snapshot.anchor_before(selection.end),
3154 reversed: selection.reversed,
3155 goal: selection.goal,
3156 },
3157 0,
3158 ));
3159 continue;
3160 }
3161 }
3162 }
3163
3164 if self.auto_replace_emoji_shortcode
3165 && selection.is_empty()
3166 && text.as_ref().ends_with(':')
3167 {
3168 if let Some(possible_emoji_short_code) =
3169 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3170 {
3171 if !possible_emoji_short_code.is_empty() {
3172 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3173 let emoji_shortcode_start = Point::new(
3174 selection.start.row,
3175 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3176 );
3177
3178 // Remove shortcode from buffer
3179 edits.push((
3180 emoji_shortcode_start..selection.start,
3181 "".to_string().into(),
3182 ));
3183 new_selections.push((
3184 Selection {
3185 id: selection.id,
3186 start: snapshot.anchor_after(emoji_shortcode_start),
3187 end: snapshot.anchor_before(selection.start),
3188 reversed: selection.reversed,
3189 goal: selection.goal,
3190 },
3191 0,
3192 ));
3193
3194 // Insert emoji
3195 let selection_start_anchor = snapshot.anchor_after(selection.start);
3196 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3197 edits.push((selection.start..selection.end, emoji.to_string().into()));
3198
3199 continue;
3200 }
3201 }
3202 }
3203 }
3204
3205 // If not handling any auto-close operation, then just replace the selected
3206 // text with the given input and move the selection to the end of the
3207 // newly inserted text.
3208 let anchor = snapshot.anchor_after(selection.end);
3209 if !self.linked_edit_ranges.is_empty() {
3210 let start_anchor = snapshot.anchor_before(selection.start);
3211
3212 let is_word_char = text.chars().next().map_or(true, |char| {
3213 let scope = snapshot.language_scope_at(start_anchor.to_offset(&snapshot));
3214 let kind = char_kind(&scope, char);
3215
3216 kind == CharKind::Word
3217 });
3218
3219 if is_word_char {
3220 if let Some(ranges) = self
3221 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3222 {
3223 for (buffer, edits) in ranges {
3224 linked_edits
3225 .entry(buffer.clone())
3226 .or_default()
3227 .extend(edits.into_iter().map(|range| (range, text.clone())));
3228 }
3229 }
3230 }
3231 }
3232
3233 new_selections.push((selection.map(|_| anchor), 0));
3234 edits.push((selection.start..selection.end, text.clone()));
3235 }
3236
3237 drop(snapshot);
3238
3239 self.transact(cx, |this, cx| {
3240 this.buffer.update(cx, |buffer, cx| {
3241 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3242 });
3243 for (buffer, edits) in linked_edits {
3244 buffer.update(cx, |buffer, cx| {
3245 let snapshot = buffer.snapshot();
3246 let edits = edits
3247 .into_iter()
3248 .map(|(range, text)| {
3249 use text::ToPoint as TP;
3250 let end_point = TP::to_point(&range.end, &snapshot);
3251 let start_point = TP::to_point(&range.start, &snapshot);
3252 (start_point..end_point, text)
3253 })
3254 .sorted_by_key(|(range, _)| range.start)
3255 .collect::<Vec<_>>();
3256 buffer.edit(edits, None, cx);
3257 })
3258 }
3259 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3260 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3261 let snapshot = this.buffer.read(cx).read(cx);
3262 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3263 .zip(new_selection_deltas)
3264 .map(|(selection, delta)| Selection {
3265 id: selection.id,
3266 start: selection.start + delta,
3267 end: selection.end + delta,
3268 reversed: selection.reversed,
3269 goal: SelectionGoal::None,
3270 })
3271 .collect::<Vec<_>>();
3272
3273 let mut i = 0;
3274 for (position, delta, selection_id, pair) in new_autoclose_regions {
3275 let position = position.to_offset(&snapshot) + delta;
3276 let start = snapshot.anchor_before(position);
3277 let end = snapshot.anchor_after(position);
3278 while let Some(existing_state) = this.autoclose_regions.get(i) {
3279 match existing_state.range.start.cmp(&start, &snapshot) {
3280 Ordering::Less => i += 1,
3281 Ordering::Greater => break,
3282 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3283 Ordering::Less => i += 1,
3284 Ordering::Equal => break,
3285 Ordering::Greater => break,
3286 },
3287 }
3288 }
3289 this.autoclose_regions.insert(
3290 i,
3291 AutocloseRegion {
3292 selection_id,
3293 range: start..end,
3294 pair,
3295 },
3296 );
3297 }
3298
3299 drop(snapshot);
3300 let had_active_inline_completion = this.has_active_inline_completion(cx);
3301 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3302 s.select(new_selections)
3303 });
3304
3305 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3306 if let Some(on_type_format_task) =
3307 this.trigger_on_type_formatting(text.to_string(), cx)
3308 {
3309 on_type_format_task.detach_and_log_err(cx);
3310 }
3311 }
3312
3313 let editor_settings = EditorSettings::get_global(cx);
3314 if bracket_inserted
3315 && (editor_settings.auto_signature_help
3316 || editor_settings.show_signature_help_after_edits)
3317 {
3318 this.show_signature_help(&ShowSignatureHelp, cx);
3319 }
3320
3321 let trigger_in_words = !had_active_inline_completion;
3322 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3323 linked_editing_ranges::refresh_linked_ranges(this, cx);
3324 this.refresh_inline_completion(true, cx);
3325 });
3326 }
3327
3328 fn find_possible_emoji_shortcode_at_position(
3329 snapshot: &MultiBufferSnapshot,
3330 position: Point,
3331 ) -> Option<String> {
3332 let mut chars = Vec::new();
3333 let mut found_colon = false;
3334 for char in snapshot.reversed_chars_at(position).take(100) {
3335 // Found a possible emoji shortcode in the middle of the buffer
3336 if found_colon {
3337 if char.is_whitespace() {
3338 chars.reverse();
3339 return Some(chars.iter().collect());
3340 }
3341 // If the previous character is not a whitespace, we are in the middle of a word
3342 // and we only want to complete the shortcode if the word is made up of other emojis
3343 let mut containing_word = String::new();
3344 for ch in snapshot
3345 .reversed_chars_at(position)
3346 .skip(chars.len() + 1)
3347 .take(100)
3348 {
3349 if ch.is_whitespace() {
3350 break;
3351 }
3352 containing_word.push(ch);
3353 }
3354 let containing_word = containing_word.chars().rev().collect::<String>();
3355 if util::word_consists_of_emojis(containing_word.as_str()) {
3356 chars.reverse();
3357 return Some(chars.iter().collect());
3358 }
3359 }
3360
3361 if char.is_whitespace() || !char.is_ascii() {
3362 return None;
3363 }
3364 if char == ':' {
3365 found_colon = true;
3366 } else {
3367 chars.push(char);
3368 }
3369 }
3370 // Found a possible emoji shortcode at the beginning of the buffer
3371 chars.reverse();
3372 Some(chars.iter().collect())
3373 }
3374
3375 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3376 self.transact(cx, |this, cx| {
3377 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3378 let selections = this.selections.all::<usize>(cx);
3379 let multi_buffer = this.buffer.read(cx);
3380 let buffer = multi_buffer.snapshot(cx);
3381 selections
3382 .iter()
3383 .map(|selection| {
3384 let start_point = selection.start.to_point(&buffer);
3385 let mut indent =
3386 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3387 indent.len = cmp::min(indent.len, start_point.column);
3388 let start = selection.start;
3389 let end = selection.end;
3390 let selection_is_empty = start == end;
3391 let language_scope = buffer.language_scope_at(start);
3392 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3393 &language_scope
3394 {
3395 let leading_whitespace_len = buffer
3396 .reversed_chars_at(start)
3397 .take_while(|c| c.is_whitespace() && *c != '\n')
3398 .map(|c| c.len_utf8())
3399 .sum::<usize>();
3400
3401 let trailing_whitespace_len = buffer
3402 .chars_at(end)
3403 .take_while(|c| c.is_whitespace() && *c != '\n')
3404 .map(|c| c.len_utf8())
3405 .sum::<usize>();
3406
3407 let insert_extra_newline =
3408 language.brackets().any(|(pair, enabled)| {
3409 let pair_start = pair.start.trim_end();
3410 let pair_end = pair.end.trim_start();
3411
3412 enabled
3413 && pair.newline
3414 && buffer.contains_str_at(
3415 end + trailing_whitespace_len,
3416 pair_end,
3417 )
3418 && buffer.contains_str_at(
3419 (start - leading_whitespace_len)
3420 .saturating_sub(pair_start.len()),
3421 pair_start,
3422 )
3423 });
3424
3425 // Comment extension on newline is allowed only for cursor selections
3426 let comment_delimiter = maybe!({
3427 if !selection_is_empty {
3428 return None;
3429 }
3430
3431 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3432 return None;
3433 }
3434
3435 let delimiters = language.line_comment_prefixes();
3436 let max_len_of_delimiter =
3437 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3438 let (snapshot, range) =
3439 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3440
3441 let mut index_of_first_non_whitespace = 0;
3442 let comment_candidate = snapshot
3443 .chars_for_range(range)
3444 .skip_while(|c| {
3445 let should_skip = c.is_whitespace();
3446 if should_skip {
3447 index_of_first_non_whitespace += 1;
3448 }
3449 should_skip
3450 })
3451 .take(max_len_of_delimiter)
3452 .collect::<String>();
3453 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3454 comment_candidate.starts_with(comment_prefix.as_ref())
3455 })?;
3456 let cursor_is_placed_after_comment_marker =
3457 index_of_first_non_whitespace + comment_prefix.len()
3458 <= start_point.column as usize;
3459 if cursor_is_placed_after_comment_marker {
3460 Some(comment_prefix.clone())
3461 } else {
3462 None
3463 }
3464 });
3465 (comment_delimiter, insert_extra_newline)
3466 } else {
3467 (None, false)
3468 };
3469
3470 let capacity_for_delimiter = comment_delimiter
3471 .as_deref()
3472 .map(str::len)
3473 .unwrap_or_default();
3474 let mut new_text =
3475 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3476 new_text.push_str("\n");
3477 new_text.extend(indent.chars());
3478 if let Some(delimiter) = &comment_delimiter {
3479 new_text.push_str(&delimiter);
3480 }
3481 if insert_extra_newline {
3482 new_text = new_text.repeat(2);
3483 }
3484
3485 let anchor = buffer.anchor_after(end);
3486 let new_selection = selection.map(|_| anchor);
3487 (
3488 (start..end, new_text),
3489 (insert_extra_newline, new_selection),
3490 )
3491 })
3492 .unzip()
3493 };
3494
3495 this.edit_with_autoindent(edits, cx);
3496 let buffer = this.buffer.read(cx).snapshot(cx);
3497 let new_selections = selection_fixup_info
3498 .into_iter()
3499 .map(|(extra_newline_inserted, new_selection)| {
3500 let mut cursor = new_selection.end.to_point(&buffer);
3501 if extra_newline_inserted {
3502 cursor.row -= 1;
3503 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3504 }
3505 new_selection.map(|_| cursor)
3506 })
3507 .collect();
3508
3509 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3510 this.refresh_inline_completion(true, cx);
3511 });
3512 }
3513
3514 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3515 let buffer = self.buffer.read(cx);
3516 let snapshot = buffer.snapshot(cx);
3517
3518 let mut edits = Vec::new();
3519 let mut rows = Vec::new();
3520
3521 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3522 let cursor = selection.head();
3523 let row = cursor.row;
3524
3525 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3526
3527 let newline = "\n".to_string();
3528 edits.push((start_of_line..start_of_line, newline));
3529
3530 rows.push(row + rows_inserted as u32);
3531 }
3532
3533 self.transact(cx, |editor, cx| {
3534 editor.edit(edits, cx);
3535
3536 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3537 let mut index = 0;
3538 s.move_cursors_with(|map, _, _| {
3539 let row = rows[index];
3540 index += 1;
3541
3542 let point = Point::new(row, 0);
3543 let boundary = map.next_line_boundary(point).1;
3544 let clipped = map.clip_point(boundary, Bias::Left);
3545
3546 (clipped, SelectionGoal::None)
3547 });
3548 });
3549
3550 let mut indent_edits = Vec::new();
3551 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3552 for row in rows {
3553 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3554 for (row, indent) in indents {
3555 if indent.len == 0 {
3556 continue;
3557 }
3558
3559 let text = match indent.kind {
3560 IndentKind::Space => " ".repeat(indent.len as usize),
3561 IndentKind::Tab => "\t".repeat(indent.len as usize),
3562 };
3563 let point = Point::new(row.0, 0);
3564 indent_edits.push((point..point, text));
3565 }
3566 }
3567 editor.edit(indent_edits, cx);
3568 });
3569 }
3570
3571 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3572 let buffer = self.buffer.read(cx);
3573 let snapshot = buffer.snapshot(cx);
3574
3575 let mut edits = Vec::new();
3576 let mut rows = Vec::new();
3577 let mut rows_inserted = 0;
3578
3579 for selection in self.selections.all_adjusted(cx) {
3580 let cursor = selection.head();
3581 let row = cursor.row;
3582
3583 let point = Point::new(row + 1, 0);
3584 let start_of_line = snapshot.clip_point(point, Bias::Left);
3585
3586 let newline = "\n".to_string();
3587 edits.push((start_of_line..start_of_line, newline));
3588
3589 rows_inserted += 1;
3590 rows.push(row + rows_inserted);
3591 }
3592
3593 self.transact(cx, |editor, cx| {
3594 editor.edit(edits, cx);
3595
3596 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3597 let mut index = 0;
3598 s.move_cursors_with(|map, _, _| {
3599 let row = rows[index];
3600 index += 1;
3601
3602 let point = Point::new(row, 0);
3603 let boundary = map.next_line_boundary(point).1;
3604 let clipped = map.clip_point(boundary, Bias::Left);
3605
3606 (clipped, SelectionGoal::None)
3607 });
3608 });
3609
3610 let mut indent_edits = Vec::new();
3611 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3612 for row in rows {
3613 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3614 for (row, indent) in indents {
3615 if indent.len == 0 {
3616 continue;
3617 }
3618
3619 let text = match indent.kind {
3620 IndentKind::Space => " ".repeat(indent.len as usize),
3621 IndentKind::Tab => "\t".repeat(indent.len as usize),
3622 };
3623 let point = Point::new(row.0, 0);
3624 indent_edits.push((point..point, text));
3625 }
3626 }
3627 editor.edit(indent_edits, cx);
3628 });
3629 }
3630
3631 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3632 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3633 original_indent_columns: Vec::new(),
3634 });
3635 self.insert_with_autoindent_mode(text, autoindent, cx);
3636 }
3637
3638 fn insert_with_autoindent_mode(
3639 &mut self,
3640 text: &str,
3641 autoindent_mode: Option<AutoindentMode>,
3642 cx: &mut ViewContext<Self>,
3643 ) {
3644 if self.read_only(cx) {
3645 return;
3646 }
3647
3648 let text: Arc<str> = text.into();
3649 self.transact(cx, |this, cx| {
3650 let old_selections = this.selections.all_adjusted(cx);
3651 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3652 let anchors = {
3653 let snapshot = buffer.read(cx);
3654 old_selections
3655 .iter()
3656 .map(|s| {
3657 let anchor = snapshot.anchor_after(s.head());
3658 s.map(|_| anchor)
3659 })
3660 .collect::<Vec<_>>()
3661 };
3662 buffer.edit(
3663 old_selections
3664 .iter()
3665 .map(|s| (s.start..s.end, text.clone())),
3666 autoindent_mode,
3667 cx,
3668 );
3669 anchors
3670 });
3671
3672 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3673 s.select_anchors(selection_anchors);
3674 })
3675 });
3676 }
3677
3678 fn trigger_completion_on_input(
3679 &mut self,
3680 text: &str,
3681 trigger_in_words: bool,
3682 cx: &mut ViewContext<Self>,
3683 ) {
3684 if self.is_completion_trigger(text, trigger_in_words, cx) {
3685 self.show_completions(
3686 &ShowCompletions {
3687 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3688 },
3689 cx,
3690 );
3691 } else {
3692 self.hide_context_menu(cx);
3693 }
3694 }
3695
3696 fn is_completion_trigger(
3697 &self,
3698 text: &str,
3699 trigger_in_words: bool,
3700 cx: &mut ViewContext<Self>,
3701 ) -> bool {
3702 let position = self.selections.newest_anchor().head();
3703 let multibuffer = self.buffer.read(cx);
3704 let Some(buffer) = position
3705 .buffer_id
3706 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3707 else {
3708 return false;
3709 };
3710
3711 if let Some(completion_provider) = &self.completion_provider {
3712 completion_provider.is_completion_trigger(
3713 &buffer,
3714 position.text_anchor,
3715 text,
3716 trigger_in_words,
3717 cx,
3718 )
3719 } else {
3720 false
3721 }
3722 }
3723
3724 /// If any empty selections is touching the start of its innermost containing autoclose
3725 /// region, expand it to select the brackets.
3726 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3727 let selections = self.selections.all::<usize>(cx);
3728 let buffer = self.buffer.read(cx).read(cx);
3729 let new_selections = self
3730 .selections_with_autoclose_regions(selections, &buffer)
3731 .map(|(mut selection, region)| {
3732 if !selection.is_empty() {
3733 return selection;
3734 }
3735
3736 if let Some(region) = region {
3737 let mut range = region.range.to_offset(&buffer);
3738 if selection.start == range.start && range.start >= region.pair.start.len() {
3739 range.start -= region.pair.start.len();
3740 if buffer.contains_str_at(range.start, ®ion.pair.start)
3741 && buffer.contains_str_at(range.end, ®ion.pair.end)
3742 {
3743 range.end += region.pair.end.len();
3744 selection.start = range.start;
3745 selection.end = range.end;
3746
3747 return selection;
3748 }
3749 }
3750 }
3751
3752 let always_treat_brackets_as_autoclosed = buffer
3753 .settings_at(selection.start, cx)
3754 .always_treat_brackets_as_autoclosed;
3755
3756 if !always_treat_brackets_as_autoclosed {
3757 return selection;
3758 }
3759
3760 if let Some(scope) = buffer.language_scope_at(selection.start) {
3761 for (pair, enabled) in scope.brackets() {
3762 if !enabled || !pair.close {
3763 continue;
3764 }
3765
3766 if buffer.contains_str_at(selection.start, &pair.end) {
3767 let pair_start_len = pair.start.len();
3768 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3769 {
3770 selection.start -= pair_start_len;
3771 selection.end += pair.end.len();
3772
3773 return selection;
3774 }
3775 }
3776 }
3777 }
3778
3779 selection
3780 })
3781 .collect();
3782
3783 drop(buffer);
3784 self.change_selections(None, cx, |selections| selections.select(new_selections));
3785 }
3786
3787 /// Iterate the given selections, and for each one, find the smallest surrounding
3788 /// autoclose region. This uses the ordering of the selections and the autoclose
3789 /// regions to avoid repeated comparisons.
3790 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3791 &'a self,
3792 selections: impl IntoIterator<Item = Selection<D>>,
3793 buffer: &'a MultiBufferSnapshot,
3794 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3795 let mut i = 0;
3796 let mut regions = self.autoclose_regions.as_slice();
3797 selections.into_iter().map(move |selection| {
3798 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3799
3800 let mut enclosing = None;
3801 while let Some(pair_state) = regions.get(i) {
3802 if pair_state.range.end.to_offset(buffer) < range.start {
3803 regions = ®ions[i + 1..];
3804 i = 0;
3805 } else if pair_state.range.start.to_offset(buffer) > range.end {
3806 break;
3807 } else {
3808 if pair_state.selection_id == selection.id {
3809 enclosing = Some(pair_state);
3810 }
3811 i += 1;
3812 }
3813 }
3814
3815 (selection.clone(), enclosing)
3816 })
3817 }
3818
3819 /// Remove any autoclose regions that no longer contain their selection.
3820 fn invalidate_autoclose_regions(
3821 &mut self,
3822 mut selections: &[Selection<Anchor>],
3823 buffer: &MultiBufferSnapshot,
3824 ) {
3825 self.autoclose_regions.retain(|state| {
3826 let mut i = 0;
3827 while let Some(selection) = selections.get(i) {
3828 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3829 selections = &selections[1..];
3830 continue;
3831 }
3832 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3833 break;
3834 }
3835 if selection.id == state.selection_id {
3836 return true;
3837 } else {
3838 i += 1;
3839 }
3840 }
3841 false
3842 });
3843 }
3844
3845 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3846 let offset = position.to_offset(buffer);
3847 let (word_range, kind) = buffer.surrounding_word(offset);
3848 if offset > word_range.start && kind == Some(CharKind::Word) {
3849 Some(
3850 buffer
3851 .text_for_range(word_range.start..offset)
3852 .collect::<String>(),
3853 )
3854 } else {
3855 None
3856 }
3857 }
3858
3859 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3860 self.refresh_inlay_hints(
3861 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3862 cx,
3863 );
3864 }
3865
3866 pub fn inlay_hints_enabled(&self) -> bool {
3867 self.inlay_hint_cache.enabled
3868 }
3869
3870 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3871 if self.project.is_none() || self.mode != EditorMode::Full {
3872 return;
3873 }
3874
3875 let reason_description = reason.description();
3876 let ignore_debounce = matches!(
3877 reason,
3878 InlayHintRefreshReason::SettingsChange(_)
3879 | InlayHintRefreshReason::Toggle(_)
3880 | InlayHintRefreshReason::ExcerptsRemoved(_)
3881 );
3882 let (invalidate_cache, required_languages) = match reason {
3883 InlayHintRefreshReason::Toggle(enabled) => {
3884 self.inlay_hint_cache.enabled = enabled;
3885 if enabled {
3886 (InvalidationStrategy::RefreshRequested, None)
3887 } else {
3888 self.inlay_hint_cache.clear();
3889 self.splice_inlays(
3890 self.visible_inlay_hints(cx)
3891 .iter()
3892 .map(|inlay| inlay.id)
3893 .collect(),
3894 Vec::new(),
3895 cx,
3896 );
3897 return;
3898 }
3899 }
3900 InlayHintRefreshReason::SettingsChange(new_settings) => {
3901 match self.inlay_hint_cache.update_settings(
3902 &self.buffer,
3903 new_settings,
3904 self.visible_inlay_hints(cx),
3905 cx,
3906 ) {
3907 ControlFlow::Break(Some(InlaySplice {
3908 to_remove,
3909 to_insert,
3910 })) => {
3911 self.splice_inlays(to_remove, to_insert, cx);
3912 return;
3913 }
3914 ControlFlow::Break(None) => return,
3915 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
3916 }
3917 }
3918 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
3919 if let Some(InlaySplice {
3920 to_remove,
3921 to_insert,
3922 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
3923 {
3924 self.splice_inlays(to_remove, to_insert, cx);
3925 }
3926 return;
3927 }
3928 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
3929 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
3930 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
3931 }
3932 InlayHintRefreshReason::RefreshRequested => {
3933 (InvalidationStrategy::RefreshRequested, None)
3934 }
3935 };
3936
3937 if let Some(InlaySplice {
3938 to_remove,
3939 to_insert,
3940 }) = self.inlay_hint_cache.spawn_hint_refresh(
3941 reason_description,
3942 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
3943 invalidate_cache,
3944 ignore_debounce,
3945 cx,
3946 ) {
3947 self.splice_inlays(to_remove, to_insert, cx);
3948 }
3949 }
3950
3951 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
3952 self.display_map
3953 .read(cx)
3954 .current_inlays()
3955 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
3956 .cloned()
3957 .collect()
3958 }
3959
3960 pub fn excerpts_for_inlay_hints_query(
3961 &self,
3962 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
3963 cx: &mut ViewContext<Editor>,
3964 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
3965 let Some(project) = self.project.as_ref() else {
3966 return HashMap::default();
3967 };
3968 let project = project.read(cx);
3969 let multi_buffer = self.buffer().read(cx);
3970 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
3971 let multi_buffer_visible_start = self
3972 .scroll_manager
3973 .anchor()
3974 .anchor
3975 .to_point(&multi_buffer_snapshot);
3976 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
3977 multi_buffer_visible_start
3978 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
3979 Bias::Left,
3980 );
3981 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
3982 multi_buffer
3983 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
3984 .into_iter()
3985 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
3986 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
3987 let buffer = buffer_handle.read(cx);
3988 let buffer_file = project::File::from_dyn(buffer.file())?;
3989 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
3990 let worktree_entry = buffer_worktree
3991 .read(cx)
3992 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
3993 if worktree_entry.is_ignored {
3994 return None;
3995 }
3996
3997 let language = buffer.language()?;
3998 if let Some(restrict_to_languages) = restrict_to_languages {
3999 if !restrict_to_languages.contains(language) {
4000 return None;
4001 }
4002 }
4003 Some((
4004 excerpt_id,
4005 (
4006 buffer_handle,
4007 buffer.version().clone(),
4008 excerpt_visible_range,
4009 ),
4010 ))
4011 })
4012 .collect()
4013 }
4014
4015 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4016 TextLayoutDetails {
4017 text_system: cx.text_system().clone(),
4018 editor_style: self.style.clone().unwrap(),
4019 rem_size: cx.rem_size(),
4020 scroll_anchor: self.scroll_manager.anchor(),
4021 visible_rows: self.visible_line_count(),
4022 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4023 }
4024 }
4025
4026 fn splice_inlays(
4027 &self,
4028 to_remove: Vec<InlayId>,
4029 to_insert: Vec<Inlay>,
4030 cx: &mut ViewContext<Self>,
4031 ) {
4032 self.display_map.update(cx, |display_map, cx| {
4033 display_map.splice_inlays(to_remove, to_insert, cx);
4034 });
4035 cx.notify();
4036 }
4037
4038 fn trigger_on_type_formatting(
4039 &self,
4040 input: String,
4041 cx: &mut ViewContext<Self>,
4042 ) -> Option<Task<Result<()>>> {
4043 if input.len() != 1 {
4044 return None;
4045 }
4046
4047 let project = self.project.as_ref()?;
4048 let position = self.selections.newest_anchor().head();
4049 let (buffer, buffer_position) = self
4050 .buffer
4051 .read(cx)
4052 .text_anchor_for_position(position, cx)?;
4053
4054 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4055 // hence we do LSP request & edit on host side only — add formats to host's history.
4056 let push_to_lsp_host_history = true;
4057 // If this is not the host, append its history with new edits.
4058 let push_to_client_history = project.read(cx).is_remote();
4059
4060 let on_type_formatting = project.update(cx, |project, cx| {
4061 project.on_type_format(
4062 buffer.clone(),
4063 buffer_position,
4064 input,
4065 push_to_lsp_host_history,
4066 cx,
4067 )
4068 });
4069 Some(cx.spawn(|editor, mut cx| async move {
4070 if let Some(transaction) = on_type_formatting.await? {
4071 if push_to_client_history {
4072 buffer
4073 .update(&mut cx, |buffer, _| {
4074 buffer.push_transaction(transaction, Instant::now());
4075 })
4076 .ok();
4077 }
4078 editor.update(&mut cx, |editor, cx| {
4079 editor.refresh_document_highlights(cx);
4080 })?;
4081 }
4082 Ok(())
4083 }))
4084 }
4085
4086 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4087 if self.pending_rename.is_some() {
4088 return;
4089 }
4090
4091 let Some(provider) = self.completion_provider.as_ref() else {
4092 return;
4093 };
4094
4095 let position = self.selections.newest_anchor().head();
4096 let (buffer, buffer_position) =
4097 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4098 output
4099 } else {
4100 return;
4101 };
4102
4103 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4104 let is_followup_invoke = {
4105 let context_menu_state = self.context_menu.read();
4106 matches!(
4107 context_menu_state.deref(),
4108 Some(ContextMenu::Completions(_))
4109 )
4110 };
4111 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4112 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4113 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(&trigger) => {
4114 CompletionTriggerKind::TRIGGER_CHARACTER
4115 }
4116
4117 _ => CompletionTriggerKind::INVOKED,
4118 };
4119 let completion_context = CompletionContext {
4120 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4121 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4122 Some(String::from(trigger))
4123 } else {
4124 None
4125 }
4126 }),
4127 trigger_kind,
4128 };
4129 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4130 let sort_completions = provider.sort_completions();
4131
4132 let id = post_inc(&mut self.next_completion_id);
4133 let task = cx.spawn(|this, mut cx| {
4134 async move {
4135 this.update(&mut cx, |this, _| {
4136 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4137 })?;
4138 let completions = completions.await.log_err();
4139 let menu = if let Some(completions) = completions {
4140 let mut menu = CompletionsMenu {
4141 id,
4142 sort_completions,
4143 initial_position: position,
4144 match_candidates: completions
4145 .iter()
4146 .enumerate()
4147 .map(|(id, completion)| {
4148 StringMatchCandidate::new(
4149 id,
4150 completion.label.text[completion.label.filter_range.clone()]
4151 .into(),
4152 )
4153 })
4154 .collect(),
4155 buffer: buffer.clone(),
4156 completions: Arc::new(RwLock::new(completions.into())),
4157 matches: Vec::new().into(),
4158 selected_item: 0,
4159 scroll_handle: UniformListScrollHandle::new(),
4160 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4161 DebouncedDelay::new(),
4162 )),
4163 };
4164 menu.filter(query.as_deref(), cx.background_executor().clone())
4165 .await;
4166
4167 if menu.matches.is_empty() {
4168 None
4169 } else {
4170 this.update(&mut cx, |editor, cx| {
4171 let completions = menu.completions.clone();
4172 let matches = menu.matches.clone();
4173
4174 let delay_ms = EditorSettings::get_global(cx)
4175 .completion_documentation_secondary_query_debounce;
4176 let delay = Duration::from_millis(delay_ms);
4177 editor
4178 .completion_documentation_pre_resolve_debounce
4179 .fire_new(delay, cx, |editor, cx| {
4180 CompletionsMenu::pre_resolve_completion_documentation(
4181 buffer,
4182 completions,
4183 matches,
4184 editor,
4185 cx,
4186 )
4187 });
4188 })
4189 .ok();
4190 Some(menu)
4191 }
4192 } else {
4193 None
4194 };
4195
4196 this.update(&mut cx, |this, cx| {
4197 let mut context_menu = this.context_menu.write();
4198 match context_menu.as_ref() {
4199 None => {}
4200
4201 Some(ContextMenu::Completions(prev_menu)) => {
4202 if prev_menu.id > id {
4203 return;
4204 }
4205 }
4206
4207 _ => return,
4208 }
4209
4210 if this.focus_handle.is_focused(cx) && menu.is_some() {
4211 let menu = menu.unwrap();
4212 *context_menu = Some(ContextMenu::Completions(menu));
4213 drop(context_menu);
4214 this.discard_inline_completion(false, cx);
4215 cx.notify();
4216 } else if this.completion_tasks.len() <= 1 {
4217 // If there are no more completion tasks and the last menu was
4218 // empty, we should hide it. If it was already hidden, we should
4219 // also show the copilot completion when available.
4220 drop(context_menu);
4221 if this.hide_context_menu(cx).is_none() {
4222 this.update_visible_inline_completion(cx);
4223 }
4224 }
4225 })?;
4226
4227 Ok::<_, anyhow::Error>(())
4228 }
4229 .log_err()
4230 });
4231
4232 self.completion_tasks.push((id, task));
4233 }
4234
4235 pub fn confirm_completion(
4236 &mut self,
4237 action: &ConfirmCompletion,
4238 cx: &mut ViewContext<Self>,
4239 ) -> Option<Task<Result<()>>> {
4240 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4241 }
4242
4243 pub fn compose_completion(
4244 &mut self,
4245 action: &ComposeCompletion,
4246 cx: &mut ViewContext<Self>,
4247 ) -> Option<Task<Result<()>>> {
4248 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4249 }
4250
4251 fn do_completion(
4252 &mut self,
4253 item_ix: Option<usize>,
4254 intent: CompletionIntent,
4255 cx: &mut ViewContext<Editor>,
4256 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4257 use language::ToOffset as _;
4258
4259 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4260 menu
4261 } else {
4262 return None;
4263 };
4264
4265 let mat = completions_menu
4266 .matches
4267 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4268 let buffer_handle = completions_menu.buffer;
4269 let completions = completions_menu.completions.read();
4270 let completion = completions.get(mat.candidate_id)?;
4271 cx.stop_propagation();
4272
4273 let snippet;
4274 let text;
4275
4276 if completion.is_snippet() {
4277 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4278 text = snippet.as_ref().unwrap().text.clone();
4279 } else {
4280 snippet = None;
4281 text = completion.new_text.clone();
4282 };
4283 let selections = self.selections.all::<usize>(cx);
4284 let buffer = buffer_handle.read(cx);
4285 let old_range = completion.old_range.to_offset(buffer);
4286 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4287
4288 let newest_selection = self.selections.newest_anchor();
4289 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4290 return None;
4291 }
4292
4293 let lookbehind = newest_selection
4294 .start
4295 .text_anchor
4296 .to_offset(buffer)
4297 .saturating_sub(old_range.start);
4298 let lookahead = old_range
4299 .end
4300 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4301 let mut common_prefix_len = old_text
4302 .bytes()
4303 .zip(text.bytes())
4304 .take_while(|(a, b)| a == b)
4305 .count();
4306
4307 let snapshot = self.buffer.read(cx).snapshot(cx);
4308 let mut range_to_replace: Option<Range<isize>> = None;
4309 let mut ranges = Vec::new();
4310 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4311 for selection in &selections {
4312 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4313 let start = selection.start.saturating_sub(lookbehind);
4314 let end = selection.end + lookahead;
4315 if selection.id == newest_selection.id {
4316 range_to_replace = Some(
4317 ((start + common_prefix_len) as isize - selection.start as isize)
4318 ..(end as isize - selection.start as isize),
4319 );
4320 }
4321 ranges.push(start + common_prefix_len..end);
4322 } else {
4323 common_prefix_len = 0;
4324 ranges.clear();
4325 ranges.extend(selections.iter().map(|s| {
4326 if s.id == newest_selection.id {
4327 range_to_replace = Some(
4328 old_range.start.to_offset_utf16(&snapshot).0 as isize
4329 - selection.start as isize
4330 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4331 - selection.start as isize,
4332 );
4333 old_range.clone()
4334 } else {
4335 s.start..s.end
4336 }
4337 }));
4338 break;
4339 }
4340 if !self.linked_edit_ranges.is_empty() {
4341 let start_anchor = snapshot.anchor_before(selection.head());
4342 let end_anchor = snapshot.anchor_after(selection.tail());
4343 if let Some(ranges) = self
4344 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4345 {
4346 for (buffer, edits) in ranges {
4347 linked_edits.entry(buffer.clone()).or_default().extend(
4348 edits
4349 .into_iter()
4350 .map(|range| (range, text[common_prefix_len..].to_owned())),
4351 );
4352 }
4353 }
4354 }
4355 }
4356 let text = &text[common_prefix_len..];
4357
4358 cx.emit(EditorEvent::InputHandled {
4359 utf16_range_to_replace: range_to_replace,
4360 text: text.into(),
4361 });
4362
4363 self.transact(cx, |this, cx| {
4364 if let Some(mut snippet) = snippet {
4365 snippet.text = text.to_string();
4366 for tabstop in snippet.tabstops.iter_mut().flatten() {
4367 tabstop.start -= common_prefix_len as isize;
4368 tabstop.end -= common_prefix_len as isize;
4369 }
4370
4371 this.insert_snippet(&ranges, snippet, cx).log_err();
4372 } else {
4373 this.buffer.update(cx, |buffer, cx| {
4374 buffer.edit(
4375 ranges.iter().map(|range| (range.clone(), text)),
4376 this.autoindent_mode.clone(),
4377 cx,
4378 );
4379 });
4380 }
4381 for (buffer, edits) in linked_edits {
4382 buffer.update(cx, |buffer, cx| {
4383 let snapshot = buffer.snapshot();
4384 let edits = edits
4385 .into_iter()
4386 .map(|(range, text)| {
4387 use text::ToPoint as TP;
4388 let end_point = TP::to_point(&range.end, &snapshot);
4389 let start_point = TP::to_point(&range.start, &snapshot);
4390 (start_point..end_point, text)
4391 })
4392 .sorted_by_key(|(range, _)| range.start)
4393 .collect::<Vec<_>>();
4394 buffer.edit(edits, None, cx);
4395 })
4396 }
4397
4398 this.refresh_inline_completion(true, cx);
4399 });
4400
4401 let show_new_completions_on_confirm = completion
4402 .confirm
4403 .as_ref()
4404 .map_or(false, |confirm| confirm(intent, cx));
4405 if show_new_completions_on_confirm {
4406 self.show_completions(&ShowCompletions { trigger: None }, cx);
4407 }
4408
4409 let provider = self.completion_provider.as_ref()?;
4410 let apply_edits = provider.apply_additional_edits_for_completion(
4411 buffer_handle,
4412 completion.clone(),
4413 true,
4414 cx,
4415 );
4416
4417 let editor_settings = EditorSettings::get_global(cx);
4418 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4419 // After the code completion is finished, users often want to know what signatures are needed.
4420 // so we should automatically call signature_help
4421 self.show_signature_help(&ShowSignatureHelp, cx);
4422 }
4423
4424 Some(cx.foreground_executor().spawn(async move {
4425 apply_edits.await?;
4426 Ok(())
4427 }))
4428 }
4429
4430 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4431 let mut context_menu = self.context_menu.write();
4432 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4433 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4434 // Toggle if we're selecting the same one
4435 *context_menu = None;
4436 cx.notify();
4437 return;
4438 } else {
4439 // Otherwise, clear it and start a new one
4440 *context_menu = None;
4441 cx.notify();
4442 }
4443 }
4444 drop(context_menu);
4445 let snapshot = self.snapshot(cx);
4446 let deployed_from_indicator = action.deployed_from_indicator;
4447 let mut task = self.code_actions_task.take();
4448 let action = action.clone();
4449 cx.spawn(|editor, mut cx| async move {
4450 while let Some(prev_task) = task {
4451 prev_task.await;
4452 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4453 }
4454
4455 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4456 if editor.focus_handle.is_focused(cx) {
4457 let multibuffer_point = action
4458 .deployed_from_indicator
4459 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4460 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4461 let (buffer, buffer_row) = snapshot
4462 .buffer_snapshot
4463 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4464 .and_then(|(buffer_snapshot, range)| {
4465 editor
4466 .buffer
4467 .read(cx)
4468 .buffer(buffer_snapshot.remote_id())
4469 .map(|buffer| (buffer, range.start.row))
4470 })?;
4471 let (_, code_actions) = editor
4472 .available_code_actions
4473 .clone()
4474 .and_then(|(location, code_actions)| {
4475 let snapshot = location.buffer.read(cx).snapshot();
4476 let point_range = location.range.to_point(&snapshot);
4477 let point_range = point_range.start.row..=point_range.end.row;
4478 if point_range.contains(&buffer_row) {
4479 Some((location, code_actions))
4480 } else {
4481 None
4482 }
4483 })
4484 .unzip();
4485 let buffer_id = buffer.read(cx).remote_id();
4486 let tasks = editor
4487 .tasks
4488 .get(&(buffer_id, buffer_row))
4489 .map(|t| Arc::new(t.to_owned()));
4490 if tasks.is_none() && code_actions.is_none() {
4491 return None;
4492 }
4493
4494 editor.completion_tasks.clear();
4495 editor.discard_inline_completion(false, cx);
4496 let task_context =
4497 tasks
4498 .as_ref()
4499 .zip(editor.project.clone())
4500 .map(|(tasks, project)| {
4501 let position = Point::new(buffer_row, tasks.column);
4502 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4503 let location = Location {
4504 buffer: buffer.clone(),
4505 range: range_start..range_start,
4506 };
4507 // Fill in the environmental variables from the tree-sitter captures
4508 let mut captured_task_variables = TaskVariables::default();
4509 for (capture_name, value) in tasks.extra_variables.clone() {
4510 captured_task_variables.insert(
4511 task::VariableName::Custom(capture_name.into()),
4512 value.clone(),
4513 );
4514 }
4515 project.update(cx, |project, cx| {
4516 project.task_context_for_location(
4517 captured_task_variables,
4518 location,
4519 cx,
4520 )
4521 })
4522 });
4523
4524 Some(cx.spawn(|editor, mut cx| async move {
4525 let task_context = match task_context {
4526 Some(task_context) => task_context.await,
4527 None => None,
4528 };
4529 let resolved_tasks =
4530 tasks.zip(task_context).map(|(tasks, task_context)| {
4531 Arc::new(ResolvedTasks {
4532 templates: tasks
4533 .templates
4534 .iter()
4535 .filter_map(|(kind, template)| {
4536 template
4537 .resolve_task(&kind.to_id_base(), &task_context)
4538 .map(|task| (kind.clone(), task))
4539 })
4540 .collect(),
4541 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4542 multibuffer_point.row,
4543 tasks.column,
4544 )),
4545 })
4546 });
4547 let spawn_straight_away = resolved_tasks
4548 .as_ref()
4549 .map_or(false, |tasks| tasks.templates.len() == 1)
4550 && code_actions
4551 .as_ref()
4552 .map_or(true, |actions| actions.is_empty());
4553 if let Some(task) = editor
4554 .update(&mut cx, |editor, cx| {
4555 *editor.context_menu.write() =
4556 Some(ContextMenu::CodeActions(CodeActionsMenu {
4557 buffer,
4558 actions: CodeActionContents {
4559 tasks: resolved_tasks,
4560 actions: code_actions,
4561 },
4562 selected_item: Default::default(),
4563 scroll_handle: UniformListScrollHandle::default(),
4564 deployed_from_indicator,
4565 }));
4566 if spawn_straight_away {
4567 if let Some(task) = editor.confirm_code_action(
4568 &ConfirmCodeAction { item_ix: Some(0) },
4569 cx,
4570 ) {
4571 cx.notify();
4572 return task;
4573 }
4574 }
4575 cx.notify();
4576 Task::ready(Ok(()))
4577 })
4578 .ok()
4579 {
4580 task.await
4581 } else {
4582 Ok(())
4583 }
4584 }))
4585 } else {
4586 Some(Task::ready(Ok(())))
4587 }
4588 })?;
4589 if let Some(task) = spawned_test_task {
4590 task.await?;
4591 }
4592
4593 Ok::<_, anyhow::Error>(())
4594 })
4595 .detach_and_log_err(cx);
4596 }
4597
4598 pub fn confirm_code_action(
4599 &mut self,
4600 action: &ConfirmCodeAction,
4601 cx: &mut ViewContext<Self>,
4602 ) -> Option<Task<Result<()>>> {
4603 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4604 menu
4605 } else {
4606 return None;
4607 };
4608 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4609 let action = actions_menu.actions.get(action_ix)?;
4610 let title = action.label();
4611 let buffer = actions_menu.buffer;
4612 let workspace = self.workspace()?;
4613
4614 match action {
4615 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4616 workspace.update(cx, |workspace, cx| {
4617 workspace::tasks::schedule_resolved_task(
4618 workspace,
4619 task_source_kind,
4620 resolved_task,
4621 false,
4622 cx,
4623 );
4624
4625 Some(Task::ready(Ok(())))
4626 })
4627 }
4628 CodeActionsItem::CodeAction(action) => {
4629 let apply_code_actions = workspace
4630 .read(cx)
4631 .project()
4632 .clone()
4633 .update(cx, |project, cx| {
4634 project.apply_code_action(buffer, action, true, cx)
4635 });
4636 let workspace = workspace.downgrade();
4637 Some(cx.spawn(|editor, cx| async move {
4638 let project_transaction = apply_code_actions.await?;
4639 Self::open_project_transaction(
4640 &editor,
4641 workspace,
4642 project_transaction,
4643 title,
4644 cx,
4645 )
4646 .await
4647 }))
4648 }
4649 }
4650 }
4651
4652 pub async fn open_project_transaction(
4653 this: &WeakView<Editor>,
4654 workspace: WeakView<Workspace>,
4655 transaction: ProjectTransaction,
4656 title: String,
4657 mut cx: AsyncWindowContext,
4658 ) -> Result<()> {
4659 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4660
4661 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4662 cx.update(|cx| {
4663 entries.sort_unstable_by_key(|(buffer, _)| {
4664 buffer.read(cx).file().map(|f| f.path().clone())
4665 });
4666 })?;
4667
4668 // If the project transaction's edits are all contained within this editor, then
4669 // avoid opening a new editor to display them.
4670
4671 if let Some((buffer, transaction)) = entries.first() {
4672 if entries.len() == 1 {
4673 let excerpt = this.update(&mut cx, |editor, cx| {
4674 editor
4675 .buffer()
4676 .read(cx)
4677 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4678 })?;
4679 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4680 if excerpted_buffer == *buffer {
4681 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4682 let excerpt_range = excerpt_range.to_offset(buffer);
4683 buffer
4684 .edited_ranges_for_transaction::<usize>(transaction)
4685 .all(|range| {
4686 excerpt_range.start <= range.start
4687 && excerpt_range.end >= range.end
4688 })
4689 })?;
4690
4691 if all_edits_within_excerpt {
4692 return Ok(());
4693 }
4694 }
4695 }
4696 }
4697 } else {
4698 return Ok(());
4699 }
4700
4701 let mut ranges_to_highlight = Vec::new();
4702 let excerpt_buffer = cx.new_model(|cx| {
4703 let mut multibuffer =
4704 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4705 for (buffer_handle, transaction) in &entries {
4706 let buffer = buffer_handle.read(cx);
4707 ranges_to_highlight.extend(
4708 multibuffer.push_excerpts_with_context_lines(
4709 buffer_handle.clone(),
4710 buffer
4711 .edited_ranges_for_transaction::<usize>(transaction)
4712 .collect(),
4713 DEFAULT_MULTIBUFFER_CONTEXT,
4714 cx,
4715 ),
4716 );
4717 }
4718 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4719 multibuffer
4720 })?;
4721
4722 workspace.update(&mut cx, |workspace, cx| {
4723 let project = workspace.project().clone();
4724 let editor =
4725 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4726 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4727 editor.update(cx, |editor, cx| {
4728 editor.highlight_background::<Self>(
4729 &ranges_to_highlight,
4730 |theme| theme.editor_highlighted_line_background,
4731 cx,
4732 );
4733 });
4734 })?;
4735
4736 Ok(())
4737 }
4738
4739 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4740 let project = self.project.clone()?;
4741 let buffer = self.buffer.read(cx);
4742 let newest_selection = self.selections.newest_anchor().clone();
4743 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4744 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4745 if start_buffer != end_buffer {
4746 return None;
4747 }
4748
4749 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4750 cx.background_executor()
4751 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4752 .await;
4753
4754 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4755 project.code_actions(&start_buffer, start..end, cx)
4756 }) {
4757 code_actions.await
4758 } else {
4759 Vec::new()
4760 };
4761
4762 this.update(&mut cx, |this, cx| {
4763 this.available_code_actions = if actions.is_empty() {
4764 None
4765 } else {
4766 Some((
4767 Location {
4768 buffer: start_buffer,
4769 range: start..end,
4770 },
4771 actions.into(),
4772 ))
4773 };
4774 cx.notify();
4775 })
4776 .log_err();
4777 }));
4778 None
4779 }
4780
4781 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4782 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4783 self.show_git_blame_inline = false;
4784
4785 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4786 cx.background_executor().timer(delay).await;
4787
4788 this.update(&mut cx, |this, cx| {
4789 this.show_git_blame_inline = true;
4790 cx.notify();
4791 })
4792 .log_err();
4793 }));
4794 }
4795 }
4796
4797 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4798 if self.pending_rename.is_some() {
4799 return None;
4800 }
4801
4802 let project = self.project.clone()?;
4803 let buffer = self.buffer.read(cx);
4804 let newest_selection = self.selections.newest_anchor().clone();
4805 let cursor_position = newest_selection.head();
4806 let (cursor_buffer, cursor_buffer_position) =
4807 buffer.text_anchor_for_position(cursor_position, cx)?;
4808 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4809 if cursor_buffer != tail_buffer {
4810 return None;
4811 }
4812
4813 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4814 cx.background_executor()
4815 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4816 .await;
4817
4818 let highlights = if let Some(highlights) = project
4819 .update(&mut cx, |project, cx| {
4820 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4821 })
4822 .log_err()
4823 {
4824 highlights.await.log_err()
4825 } else {
4826 None
4827 };
4828
4829 if let Some(highlights) = highlights {
4830 this.update(&mut cx, |this, cx| {
4831 if this.pending_rename.is_some() {
4832 return;
4833 }
4834
4835 let buffer_id = cursor_position.buffer_id;
4836 let buffer = this.buffer.read(cx);
4837 if !buffer
4838 .text_anchor_for_position(cursor_position, cx)
4839 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4840 {
4841 return;
4842 }
4843
4844 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4845 let mut write_ranges = Vec::new();
4846 let mut read_ranges = Vec::new();
4847 for highlight in highlights {
4848 for (excerpt_id, excerpt_range) in
4849 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4850 {
4851 let start = highlight
4852 .range
4853 .start
4854 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4855 let end = highlight
4856 .range
4857 .end
4858 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4859 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4860 continue;
4861 }
4862
4863 let range = Anchor {
4864 buffer_id,
4865 excerpt_id,
4866 text_anchor: start,
4867 }..Anchor {
4868 buffer_id,
4869 excerpt_id,
4870 text_anchor: end,
4871 };
4872 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4873 write_ranges.push(range);
4874 } else {
4875 read_ranges.push(range);
4876 }
4877 }
4878 }
4879
4880 this.highlight_background::<DocumentHighlightRead>(
4881 &read_ranges,
4882 |theme| theme.editor_document_highlight_read_background,
4883 cx,
4884 );
4885 this.highlight_background::<DocumentHighlightWrite>(
4886 &write_ranges,
4887 |theme| theme.editor_document_highlight_write_background,
4888 cx,
4889 );
4890 cx.notify();
4891 })
4892 .log_err();
4893 }
4894 }));
4895 None
4896 }
4897
4898 fn refresh_inline_completion(
4899 &mut self,
4900 debounce: bool,
4901 cx: &mut ViewContext<Self>,
4902 ) -> Option<()> {
4903 let provider = self.inline_completion_provider()?;
4904 let cursor = self.selections.newest_anchor().head();
4905 let (buffer, cursor_buffer_position) =
4906 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4907 if !self.show_inline_completions
4908 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4909 {
4910 self.discard_inline_completion(false, cx);
4911 return None;
4912 }
4913
4914 self.update_visible_inline_completion(cx);
4915 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
4916 Some(())
4917 }
4918
4919 fn cycle_inline_completion(
4920 &mut self,
4921 direction: Direction,
4922 cx: &mut ViewContext<Self>,
4923 ) -> Option<()> {
4924 let provider = self.inline_completion_provider()?;
4925 let cursor = self.selections.newest_anchor().head();
4926 let (buffer, cursor_buffer_position) =
4927 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
4928 if !self.show_inline_completions
4929 || !provider.is_enabled(&buffer, cursor_buffer_position, cx)
4930 {
4931 return None;
4932 }
4933
4934 provider.cycle(buffer, cursor_buffer_position, direction, cx);
4935 self.update_visible_inline_completion(cx);
4936
4937 Some(())
4938 }
4939
4940 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
4941 if !self.has_active_inline_completion(cx) {
4942 self.refresh_inline_completion(false, cx);
4943 return;
4944 }
4945
4946 self.update_visible_inline_completion(cx);
4947 }
4948
4949 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
4950 self.show_cursor_names(cx);
4951 }
4952
4953 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
4954 self.show_cursor_names = true;
4955 cx.notify();
4956 cx.spawn(|this, mut cx| async move {
4957 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
4958 this.update(&mut cx, |this, cx| {
4959 this.show_cursor_names = false;
4960 cx.notify()
4961 })
4962 .ok()
4963 })
4964 .detach();
4965 }
4966
4967 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
4968 if self.has_active_inline_completion(cx) {
4969 self.cycle_inline_completion(Direction::Next, cx);
4970 } else {
4971 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4972 if is_copilot_disabled {
4973 cx.propagate();
4974 }
4975 }
4976 }
4977
4978 pub fn previous_inline_completion(
4979 &mut self,
4980 _: &PreviousInlineCompletion,
4981 cx: &mut ViewContext<Self>,
4982 ) {
4983 if self.has_active_inline_completion(cx) {
4984 self.cycle_inline_completion(Direction::Prev, cx);
4985 } else {
4986 let is_copilot_disabled = self.refresh_inline_completion(false, cx).is_none();
4987 if is_copilot_disabled {
4988 cx.propagate();
4989 }
4990 }
4991 }
4992
4993 pub fn accept_inline_completion(
4994 &mut self,
4995 _: &AcceptInlineCompletion,
4996 cx: &mut ViewContext<Self>,
4997 ) {
4998 let Some((completion, delete_range)) = self.take_active_inline_completion(cx) else {
4999 return;
5000 };
5001 if let Some(provider) = self.inline_completion_provider() {
5002 provider.accept(cx);
5003 }
5004
5005 cx.emit(EditorEvent::InputHandled {
5006 utf16_range_to_replace: None,
5007 text: completion.text.to_string().into(),
5008 });
5009
5010 if let Some(range) = delete_range {
5011 self.change_selections(None, cx, |s| s.select_ranges([range]))
5012 }
5013 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5014 self.refresh_inline_completion(true, cx);
5015 cx.notify();
5016 }
5017
5018 pub fn accept_partial_inline_completion(
5019 &mut self,
5020 _: &AcceptPartialInlineCompletion,
5021 cx: &mut ViewContext<Self>,
5022 ) {
5023 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5024 if let Some((completion, delete_range)) = self.take_active_inline_completion(cx) {
5025 let mut partial_completion = completion
5026 .text
5027 .chars()
5028 .by_ref()
5029 .take_while(|c| c.is_alphabetic())
5030 .collect::<String>();
5031 if partial_completion.is_empty() {
5032 partial_completion = completion
5033 .text
5034 .chars()
5035 .by_ref()
5036 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5037 .collect::<String>();
5038 }
5039
5040 cx.emit(EditorEvent::InputHandled {
5041 utf16_range_to_replace: None,
5042 text: partial_completion.clone().into(),
5043 });
5044
5045 if let Some(range) = delete_range {
5046 self.change_selections(None, cx, |s| s.select_ranges([range]))
5047 }
5048 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5049
5050 self.refresh_inline_completion(true, cx);
5051 cx.notify();
5052 }
5053 }
5054 }
5055
5056 fn discard_inline_completion(
5057 &mut self,
5058 should_report_inline_completion_event: bool,
5059 cx: &mut ViewContext<Self>,
5060 ) -> bool {
5061 if let Some(provider) = self.inline_completion_provider() {
5062 provider.discard(should_report_inline_completion_event, cx);
5063 }
5064
5065 self.take_active_inline_completion(cx).is_some()
5066 }
5067
5068 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5069 if let Some(completion) = self.active_inline_completion.as_ref() {
5070 let buffer = self.buffer.read(cx).read(cx);
5071 completion.0.position.is_valid(&buffer)
5072 } else {
5073 false
5074 }
5075 }
5076
5077 fn take_active_inline_completion(
5078 &mut self,
5079 cx: &mut ViewContext<Self>,
5080 ) -> Option<(Inlay, Option<Range<Anchor>>)> {
5081 let completion = self.active_inline_completion.take()?;
5082 self.display_map.update(cx, |map, cx| {
5083 map.splice_inlays(vec![completion.0.id], Default::default(), cx);
5084 });
5085 let buffer = self.buffer.read(cx).read(cx);
5086
5087 if completion.0.position.is_valid(&buffer) {
5088 Some(completion)
5089 } else {
5090 None
5091 }
5092 }
5093
5094 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5095 let selection = self.selections.newest_anchor();
5096 let cursor = selection.head();
5097
5098 let excerpt_id = cursor.excerpt_id;
5099
5100 if self.context_menu.read().is_none()
5101 && self.completion_tasks.is_empty()
5102 && selection.start == selection.end
5103 {
5104 if let Some(provider) = self.inline_completion_provider() {
5105 if let Some((buffer, cursor_buffer_position)) =
5106 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5107 {
5108 if let Some((text, text_anchor_range)) =
5109 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5110 {
5111 let text = Rope::from(text);
5112 let mut to_remove = Vec::new();
5113 if let Some(completion) = self.active_inline_completion.take() {
5114 to_remove.push(completion.0.id);
5115 }
5116
5117 let completion_inlay =
5118 Inlay::suggestion(post_inc(&mut self.next_inlay_id), cursor, text);
5119
5120 let multibuffer_anchor_range = text_anchor_range.and_then(|range| {
5121 let snapshot = self.buffer.read(cx).snapshot(cx);
5122 Some(
5123 snapshot.anchor_in_excerpt(excerpt_id, range.start)?
5124 ..snapshot.anchor_in_excerpt(excerpt_id, range.end)?,
5125 )
5126 });
5127 self.active_inline_completion =
5128 Some((completion_inlay.clone(), multibuffer_anchor_range));
5129
5130 self.display_map.update(cx, move |map, cx| {
5131 map.splice_inlays(to_remove, vec![completion_inlay], cx)
5132 });
5133 cx.notify();
5134 return;
5135 }
5136 }
5137 }
5138 }
5139
5140 self.discard_inline_completion(false, cx);
5141 }
5142
5143 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5144 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5145 }
5146
5147 fn render_code_actions_indicator(
5148 &self,
5149 _style: &EditorStyle,
5150 row: DisplayRow,
5151 is_active: bool,
5152 cx: &mut ViewContext<Self>,
5153 ) -> Option<IconButton> {
5154 if self.available_code_actions.is_some() {
5155 Some(
5156 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5157 .shape(ui::IconButtonShape::Square)
5158 .icon_size(IconSize::XSmall)
5159 .icon_color(Color::Muted)
5160 .selected(is_active)
5161 .on_click(cx.listener(move |editor, _e, cx| {
5162 editor.focus(cx);
5163 editor.toggle_code_actions(
5164 &ToggleCodeActions {
5165 deployed_from_indicator: Some(row),
5166 },
5167 cx,
5168 );
5169 })),
5170 )
5171 } else {
5172 None
5173 }
5174 }
5175
5176 fn clear_tasks(&mut self) {
5177 self.tasks.clear()
5178 }
5179
5180 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5181 if let Some(_) = self.tasks.insert(key, value) {
5182 // This case should hopefully be rare, but just in case...
5183 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5184 }
5185 }
5186
5187 fn render_run_indicator(
5188 &self,
5189 _style: &EditorStyle,
5190 is_active: bool,
5191 row: DisplayRow,
5192 cx: &mut ViewContext<Self>,
5193 ) -> IconButton {
5194 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5195 .shape(ui::IconButtonShape::Square)
5196 .icon_size(IconSize::XSmall)
5197 .icon_color(Color::Muted)
5198 .selected(is_active)
5199 .on_click(cx.listener(move |editor, _e, cx| {
5200 editor.focus(cx);
5201 editor.toggle_code_actions(
5202 &ToggleCodeActions {
5203 deployed_from_indicator: Some(row),
5204 },
5205 cx,
5206 );
5207 }))
5208 }
5209
5210 fn close_hunk_diff_button(
5211 &self,
5212 hunk: HoveredHunk,
5213 row: DisplayRow,
5214 cx: &mut ViewContext<Self>,
5215 ) -> IconButton {
5216 IconButton::new(
5217 ("close_hunk_diff_indicator", row.0 as usize),
5218 ui::IconName::Close,
5219 )
5220 .shape(ui::IconButtonShape::Square)
5221 .icon_size(IconSize::XSmall)
5222 .icon_color(Color::Muted)
5223 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5224 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5225 }
5226
5227 pub fn context_menu_visible(&self) -> bool {
5228 self.context_menu
5229 .read()
5230 .as_ref()
5231 .map_or(false, |menu| menu.visible())
5232 }
5233
5234 fn render_context_menu(
5235 &self,
5236 cursor_position: DisplayPoint,
5237 style: &EditorStyle,
5238 max_height: Pixels,
5239 cx: &mut ViewContext<Editor>,
5240 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5241 self.context_menu.read().as_ref().map(|menu| {
5242 menu.render(
5243 cursor_position,
5244 style,
5245 max_height,
5246 self.workspace.as_ref().map(|(w, _)| w.clone()),
5247 cx,
5248 )
5249 })
5250 }
5251
5252 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5253 cx.notify();
5254 self.completion_tasks.clear();
5255 let context_menu = self.context_menu.write().take();
5256 if context_menu.is_some() {
5257 self.update_visible_inline_completion(cx);
5258 }
5259 context_menu
5260 }
5261
5262 pub fn insert_snippet(
5263 &mut self,
5264 insertion_ranges: &[Range<usize>],
5265 snippet: Snippet,
5266 cx: &mut ViewContext<Self>,
5267 ) -> Result<()> {
5268 struct Tabstop<T> {
5269 is_end_tabstop: bool,
5270 ranges: Vec<Range<T>>,
5271 }
5272
5273 let tabstops = self.buffer.update(cx, |buffer, cx| {
5274 let snippet_text: Arc<str> = snippet.text.clone().into();
5275 buffer.edit(
5276 insertion_ranges
5277 .iter()
5278 .cloned()
5279 .map(|range| (range, snippet_text.clone())),
5280 Some(AutoindentMode::EachLine),
5281 cx,
5282 );
5283
5284 let snapshot = &*buffer.read(cx);
5285 let snippet = &snippet;
5286 snippet
5287 .tabstops
5288 .iter()
5289 .map(|tabstop| {
5290 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5291 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5292 });
5293 let mut tabstop_ranges = tabstop
5294 .iter()
5295 .flat_map(|tabstop_range| {
5296 let mut delta = 0_isize;
5297 insertion_ranges.iter().map(move |insertion_range| {
5298 let insertion_start = insertion_range.start as isize + delta;
5299 delta +=
5300 snippet.text.len() as isize - insertion_range.len() as isize;
5301
5302 let start = ((insertion_start + tabstop_range.start) as usize)
5303 .min(snapshot.len());
5304 let end = ((insertion_start + tabstop_range.end) as usize)
5305 .min(snapshot.len());
5306 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5307 })
5308 })
5309 .collect::<Vec<_>>();
5310 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5311
5312 Tabstop {
5313 is_end_tabstop,
5314 ranges: tabstop_ranges,
5315 }
5316 })
5317 .collect::<Vec<_>>()
5318 });
5319 if let Some(tabstop) = tabstops.first() {
5320 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5321 s.select_ranges(tabstop.ranges.iter().cloned());
5322 });
5323
5324 // If we're already at the last tabstop and it's at the end of the snippet,
5325 // we're done, we don't need to keep the state around.
5326 if !tabstop.is_end_tabstop {
5327 let ranges = tabstops
5328 .into_iter()
5329 .map(|tabstop| tabstop.ranges)
5330 .collect::<Vec<_>>();
5331 self.snippet_stack.push(SnippetState {
5332 active_index: 0,
5333 ranges,
5334 });
5335 }
5336
5337 // Check whether the just-entered snippet ends with an auto-closable bracket.
5338 if self.autoclose_regions.is_empty() {
5339 let snapshot = self.buffer.read(cx).snapshot(cx);
5340 for selection in &mut self.selections.all::<Point>(cx) {
5341 let selection_head = selection.head();
5342 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5343 continue;
5344 };
5345
5346 let mut bracket_pair = None;
5347 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5348 let prev_chars = snapshot
5349 .reversed_chars_at(selection_head)
5350 .collect::<String>();
5351 for (pair, enabled) in scope.brackets() {
5352 if enabled
5353 && pair.close
5354 && prev_chars.starts_with(pair.start.as_str())
5355 && next_chars.starts_with(pair.end.as_str())
5356 {
5357 bracket_pair = Some(pair.clone());
5358 break;
5359 }
5360 }
5361 if let Some(pair) = bracket_pair {
5362 let start = snapshot.anchor_after(selection_head);
5363 let end = snapshot.anchor_after(selection_head);
5364 self.autoclose_regions.push(AutocloseRegion {
5365 selection_id: selection.id,
5366 range: start..end,
5367 pair,
5368 });
5369 }
5370 }
5371 }
5372 }
5373 Ok(())
5374 }
5375
5376 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5377 self.move_to_snippet_tabstop(Bias::Right, cx)
5378 }
5379
5380 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5381 self.move_to_snippet_tabstop(Bias::Left, cx)
5382 }
5383
5384 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5385 if let Some(mut snippet) = self.snippet_stack.pop() {
5386 match bias {
5387 Bias::Left => {
5388 if snippet.active_index > 0 {
5389 snippet.active_index -= 1;
5390 } else {
5391 self.snippet_stack.push(snippet);
5392 return false;
5393 }
5394 }
5395 Bias::Right => {
5396 if snippet.active_index + 1 < snippet.ranges.len() {
5397 snippet.active_index += 1;
5398 } else {
5399 self.snippet_stack.push(snippet);
5400 return false;
5401 }
5402 }
5403 }
5404 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5405 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5406 s.select_anchor_ranges(current_ranges.iter().cloned())
5407 });
5408 // If snippet state is not at the last tabstop, push it back on the stack
5409 if snippet.active_index + 1 < snippet.ranges.len() {
5410 self.snippet_stack.push(snippet);
5411 }
5412 return true;
5413 }
5414 }
5415
5416 false
5417 }
5418
5419 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5420 self.transact(cx, |this, cx| {
5421 this.select_all(&SelectAll, cx);
5422 this.insert("", cx);
5423 });
5424 }
5425
5426 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5427 self.transact(cx, |this, cx| {
5428 this.select_autoclose_pair(cx);
5429 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5430 if !this.linked_edit_ranges.is_empty() {
5431 let selections = this.selections.all::<MultiBufferPoint>(cx);
5432 let snapshot = this.buffer.read(cx).snapshot(cx);
5433
5434 for selection in selections.iter() {
5435 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5436 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5437 if selection_start.buffer_id != selection_end.buffer_id {
5438 continue;
5439 }
5440 if let Some(ranges) =
5441 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5442 {
5443 for (buffer, entries) in ranges {
5444 linked_ranges.entry(buffer).or_default().extend(entries);
5445 }
5446 }
5447 }
5448 }
5449
5450 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5451 if !this.selections.line_mode {
5452 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5453 for selection in &mut selections {
5454 if selection.is_empty() {
5455 let old_head = selection.head();
5456 let mut new_head =
5457 movement::left(&display_map, old_head.to_display_point(&display_map))
5458 .to_point(&display_map);
5459 if let Some((buffer, line_buffer_range)) = display_map
5460 .buffer_snapshot
5461 .buffer_line_for_row(MultiBufferRow(old_head.row))
5462 {
5463 let indent_size =
5464 buffer.indent_size_for_line(line_buffer_range.start.row);
5465 let indent_len = match indent_size.kind {
5466 IndentKind::Space => {
5467 buffer.settings_at(line_buffer_range.start, cx).tab_size
5468 }
5469 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5470 };
5471 if old_head.column <= indent_size.len && old_head.column > 0 {
5472 let indent_len = indent_len.get();
5473 new_head = cmp::min(
5474 new_head,
5475 MultiBufferPoint::new(
5476 old_head.row,
5477 ((old_head.column - 1) / indent_len) * indent_len,
5478 ),
5479 );
5480 }
5481 }
5482
5483 selection.set_head(new_head, SelectionGoal::None);
5484 }
5485 }
5486 }
5487
5488 this.signature_help_state.set_backspace_pressed(true);
5489 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5490 this.insert("", cx);
5491 let empty_str: Arc<str> = Arc::from("");
5492 for (buffer, edits) in linked_ranges {
5493 let snapshot = buffer.read(cx).snapshot();
5494 use text::ToPoint as TP;
5495
5496 let edits = edits
5497 .into_iter()
5498 .map(|range| {
5499 let end_point = TP::to_point(&range.end, &snapshot);
5500 let mut start_point = TP::to_point(&range.start, &snapshot);
5501
5502 if end_point == start_point {
5503 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5504 .saturating_sub(1);
5505 start_point = TP::to_point(&offset, &snapshot);
5506 };
5507
5508 (start_point..end_point, empty_str.clone())
5509 })
5510 .sorted_by_key(|(range, _)| range.start)
5511 .collect::<Vec<_>>();
5512 buffer.update(cx, |this, cx| {
5513 this.edit(edits, None, cx);
5514 })
5515 }
5516 this.refresh_inline_completion(true, cx);
5517 linked_editing_ranges::refresh_linked_ranges(this, cx);
5518 });
5519 }
5520
5521 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5522 self.transact(cx, |this, cx| {
5523 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5524 let line_mode = s.line_mode;
5525 s.move_with(|map, selection| {
5526 if selection.is_empty() && !line_mode {
5527 let cursor = movement::right(map, selection.head());
5528 selection.end = cursor;
5529 selection.reversed = true;
5530 selection.goal = SelectionGoal::None;
5531 }
5532 })
5533 });
5534 this.insert("", cx);
5535 this.refresh_inline_completion(true, cx);
5536 });
5537 }
5538
5539 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5540 if self.move_to_prev_snippet_tabstop(cx) {
5541 return;
5542 }
5543
5544 self.outdent(&Outdent, cx);
5545 }
5546
5547 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5548 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5549 return;
5550 }
5551
5552 let mut selections = self.selections.all_adjusted(cx);
5553 let buffer = self.buffer.read(cx);
5554 let snapshot = buffer.snapshot(cx);
5555 let rows_iter = selections.iter().map(|s| s.head().row);
5556 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5557
5558 let mut edits = Vec::new();
5559 let mut prev_edited_row = 0;
5560 let mut row_delta = 0;
5561 for selection in &mut selections {
5562 if selection.start.row != prev_edited_row {
5563 row_delta = 0;
5564 }
5565 prev_edited_row = selection.end.row;
5566
5567 // If the selection is non-empty, then increase the indentation of the selected lines.
5568 if !selection.is_empty() {
5569 row_delta =
5570 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5571 continue;
5572 }
5573
5574 // If the selection is empty and the cursor is in the leading whitespace before the
5575 // suggested indentation, then auto-indent the line.
5576 let cursor = selection.head();
5577 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5578 if let Some(suggested_indent) =
5579 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5580 {
5581 if cursor.column < suggested_indent.len
5582 && cursor.column <= current_indent.len
5583 && current_indent.len <= suggested_indent.len
5584 {
5585 selection.start = Point::new(cursor.row, suggested_indent.len);
5586 selection.end = selection.start;
5587 if row_delta == 0 {
5588 edits.extend(Buffer::edit_for_indent_size_adjustment(
5589 cursor.row,
5590 current_indent,
5591 suggested_indent,
5592 ));
5593 row_delta = suggested_indent.len - current_indent.len;
5594 }
5595 continue;
5596 }
5597 }
5598
5599 // Otherwise, insert a hard or soft tab.
5600 let settings = buffer.settings_at(cursor, cx);
5601 let tab_size = if settings.hard_tabs {
5602 IndentSize::tab()
5603 } else {
5604 let tab_size = settings.tab_size.get();
5605 let char_column = snapshot
5606 .text_for_range(Point::new(cursor.row, 0)..cursor)
5607 .flat_map(str::chars)
5608 .count()
5609 + row_delta as usize;
5610 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5611 IndentSize::spaces(chars_to_next_tab_stop)
5612 };
5613 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5614 selection.end = selection.start;
5615 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5616 row_delta += tab_size.len;
5617 }
5618
5619 self.transact(cx, |this, cx| {
5620 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5621 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5622 this.refresh_inline_completion(true, cx);
5623 });
5624 }
5625
5626 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5627 if self.read_only(cx) {
5628 return;
5629 }
5630 let mut selections = self.selections.all::<Point>(cx);
5631 let mut prev_edited_row = 0;
5632 let mut row_delta = 0;
5633 let mut edits = Vec::new();
5634 let buffer = self.buffer.read(cx);
5635 let snapshot = buffer.snapshot(cx);
5636 for selection in &mut selections {
5637 if selection.start.row != prev_edited_row {
5638 row_delta = 0;
5639 }
5640 prev_edited_row = selection.end.row;
5641
5642 row_delta =
5643 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5644 }
5645
5646 self.transact(cx, |this, cx| {
5647 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5648 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5649 });
5650 }
5651
5652 fn indent_selection(
5653 buffer: &MultiBuffer,
5654 snapshot: &MultiBufferSnapshot,
5655 selection: &mut Selection<Point>,
5656 edits: &mut Vec<(Range<Point>, String)>,
5657 delta_for_start_row: u32,
5658 cx: &AppContext,
5659 ) -> u32 {
5660 let settings = buffer.settings_at(selection.start, cx);
5661 let tab_size = settings.tab_size.get();
5662 let indent_kind = if settings.hard_tabs {
5663 IndentKind::Tab
5664 } else {
5665 IndentKind::Space
5666 };
5667 let mut start_row = selection.start.row;
5668 let mut end_row = selection.end.row + 1;
5669
5670 // If a selection ends at the beginning of a line, don't indent
5671 // that last line.
5672 if selection.end.column == 0 && selection.end.row > selection.start.row {
5673 end_row -= 1;
5674 }
5675
5676 // Avoid re-indenting a row that has already been indented by a
5677 // previous selection, but still update this selection's column
5678 // to reflect that indentation.
5679 if delta_for_start_row > 0 {
5680 start_row += 1;
5681 selection.start.column += delta_for_start_row;
5682 if selection.end.row == selection.start.row {
5683 selection.end.column += delta_for_start_row;
5684 }
5685 }
5686
5687 let mut delta_for_end_row = 0;
5688 let has_multiple_rows = start_row + 1 != end_row;
5689 for row in start_row..end_row {
5690 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5691 let indent_delta = match (current_indent.kind, indent_kind) {
5692 (IndentKind::Space, IndentKind::Space) => {
5693 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5694 IndentSize::spaces(columns_to_next_tab_stop)
5695 }
5696 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5697 (_, IndentKind::Tab) => IndentSize::tab(),
5698 };
5699
5700 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5701 0
5702 } else {
5703 selection.start.column
5704 };
5705 let row_start = Point::new(row, start);
5706 edits.push((
5707 row_start..row_start,
5708 indent_delta.chars().collect::<String>(),
5709 ));
5710
5711 // Update this selection's endpoints to reflect the indentation.
5712 if row == selection.start.row {
5713 selection.start.column += indent_delta.len;
5714 }
5715 if row == selection.end.row {
5716 selection.end.column += indent_delta.len;
5717 delta_for_end_row = indent_delta.len;
5718 }
5719 }
5720
5721 if selection.start.row == selection.end.row {
5722 delta_for_start_row + delta_for_end_row
5723 } else {
5724 delta_for_end_row
5725 }
5726 }
5727
5728 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5729 if self.read_only(cx) {
5730 return;
5731 }
5732 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5733 let selections = self.selections.all::<Point>(cx);
5734 let mut deletion_ranges = Vec::new();
5735 let mut last_outdent = None;
5736 {
5737 let buffer = self.buffer.read(cx);
5738 let snapshot = buffer.snapshot(cx);
5739 for selection in &selections {
5740 let settings = buffer.settings_at(selection.start, cx);
5741 let tab_size = settings.tab_size.get();
5742 let mut rows = selection.spanned_rows(false, &display_map);
5743
5744 // Avoid re-outdenting a row that has already been outdented by a
5745 // previous selection.
5746 if let Some(last_row) = last_outdent {
5747 if last_row == rows.start {
5748 rows.start = rows.start.next_row();
5749 }
5750 }
5751 let has_multiple_rows = rows.len() > 1;
5752 for row in rows.iter_rows() {
5753 let indent_size = snapshot.indent_size_for_line(row);
5754 if indent_size.len > 0 {
5755 let deletion_len = match indent_size.kind {
5756 IndentKind::Space => {
5757 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5758 if columns_to_prev_tab_stop == 0 {
5759 tab_size
5760 } else {
5761 columns_to_prev_tab_stop
5762 }
5763 }
5764 IndentKind::Tab => 1,
5765 };
5766 let start = if has_multiple_rows
5767 || deletion_len > selection.start.column
5768 || indent_size.len < selection.start.column
5769 {
5770 0
5771 } else {
5772 selection.start.column - deletion_len
5773 };
5774 deletion_ranges.push(
5775 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5776 );
5777 last_outdent = Some(row);
5778 }
5779 }
5780 }
5781 }
5782
5783 self.transact(cx, |this, cx| {
5784 this.buffer.update(cx, |buffer, cx| {
5785 let empty_str: Arc<str> = Arc::default();
5786 buffer.edit(
5787 deletion_ranges
5788 .into_iter()
5789 .map(|range| (range, empty_str.clone())),
5790 None,
5791 cx,
5792 );
5793 });
5794 let selections = this.selections.all::<usize>(cx);
5795 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5796 });
5797 }
5798
5799 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5800 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5801 let selections = self.selections.all::<Point>(cx);
5802
5803 let mut new_cursors = Vec::new();
5804 let mut edit_ranges = Vec::new();
5805 let mut selections = selections.iter().peekable();
5806 while let Some(selection) = selections.next() {
5807 let mut rows = selection.spanned_rows(false, &display_map);
5808 let goal_display_column = selection.head().to_display_point(&display_map).column();
5809
5810 // Accumulate contiguous regions of rows that we want to delete.
5811 while let Some(next_selection) = selections.peek() {
5812 let next_rows = next_selection.spanned_rows(false, &display_map);
5813 if next_rows.start <= rows.end {
5814 rows.end = next_rows.end;
5815 selections.next().unwrap();
5816 } else {
5817 break;
5818 }
5819 }
5820
5821 let buffer = &display_map.buffer_snapshot;
5822 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5823 let edit_end;
5824 let cursor_buffer_row;
5825 if buffer.max_point().row >= rows.end.0 {
5826 // If there's a line after the range, delete the \n from the end of the row range
5827 // and position the cursor on the next line.
5828 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5829 cursor_buffer_row = rows.end;
5830 } else {
5831 // If there isn't a line after the range, delete the \n from the line before the
5832 // start of the row range and position the cursor there.
5833 edit_start = edit_start.saturating_sub(1);
5834 edit_end = buffer.len();
5835 cursor_buffer_row = rows.start.previous_row();
5836 }
5837
5838 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5839 *cursor.column_mut() =
5840 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5841
5842 new_cursors.push((
5843 selection.id,
5844 buffer.anchor_after(cursor.to_point(&display_map)),
5845 ));
5846 edit_ranges.push(edit_start..edit_end);
5847 }
5848
5849 self.transact(cx, |this, cx| {
5850 let buffer = this.buffer.update(cx, |buffer, cx| {
5851 let empty_str: Arc<str> = Arc::default();
5852 buffer.edit(
5853 edit_ranges
5854 .into_iter()
5855 .map(|range| (range, empty_str.clone())),
5856 None,
5857 cx,
5858 );
5859 buffer.snapshot(cx)
5860 });
5861 let new_selections = new_cursors
5862 .into_iter()
5863 .map(|(id, cursor)| {
5864 let cursor = cursor.to_point(&buffer);
5865 Selection {
5866 id,
5867 start: cursor,
5868 end: cursor,
5869 reversed: false,
5870 goal: SelectionGoal::None,
5871 }
5872 })
5873 .collect();
5874
5875 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5876 s.select(new_selections);
5877 });
5878 });
5879 }
5880
5881 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
5882 if self.read_only(cx) {
5883 return;
5884 }
5885 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
5886 for selection in self.selections.all::<Point>(cx) {
5887 let start = MultiBufferRow(selection.start.row);
5888 let end = if selection.start.row == selection.end.row {
5889 MultiBufferRow(selection.start.row + 1)
5890 } else {
5891 MultiBufferRow(selection.end.row)
5892 };
5893
5894 if let Some(last_row_range) = row_ranges.last_mut() {
5895 if start <= last_row_range.end {
5896 last_row_range.end = end;
5897 continue;
5898 }
5899 }
5900 row_ranges.push(start..end);
5901 }
5902
5903 let snapshot = self.buffer.read(cx).snapshot(cx);
5904 let mut cursor_positions = Vec::new();
5905 for row_range in &row_ranges {
5906 let anchor = snapshot.anchor_before(Point::new(
5907 row_range.end.previous_row().0,
5908 snapshot.line_len(row_range.end.previous_row()),
5909 ));
5910 cursor_positions.push(anchor..anchor);
5911 }
5912
5913 self.transact(cx, |this, cx| {
5914 for row_range in row_ranges.into_iter().rev() {
5915 for row in row_range.iter_rows().rev() {
5916 let end_of_line = Point::new(row.0, snapshot.line_len(row));
5917 let next_line_row = row.next_row();
5918 let indent = snapshot.indent_size_for_line(next_line_row);
5919 let start_of_next_line = Point::new(next_line_row.0, indent.len);
5920
5921 let replace = if snapshot.line_len(next_line_row) > indent.len {
5922 " "
5923 } else {
5924 ""
5925 };
5926
5927 this.buffer.update(cx, |buffer, cx| {
5928 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
5929 });
5930 }
5931 }
5932
5933 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5934 s.select_anchor_ranges(cursor_positions)
5935 });
5936 });
5937 }
5938
5939 pub fn sort_lines_case_sensitive(
5940 &mut self,
5941 _: &SortLinesCaseSensitive,
5942 cx: &mut ViewContext<Self>,
5943 ) {
5944 self.manipulate_lines(cx, |lines| lines.sort())
5945 }
5946
5947 pub fn sort_lines_case_insensitive(
5948 &mut self,
5949 _: &SortLinesCaseInsensitive,
5950 cx: &mut ViewContext<Self>,
5951 ) {
5952 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
5953 }
5954
5955 pub fn unique_lines_case_insensitive(
5956 &mut self,
5957 _: &UniqueLinesCaseInsensitive,
5958 cx: &mut ViewContext<Self>,
5959 ) {
5960 self.manipulate_lines(cx, |lines| {
5961 let mut seen = HashSet::default();
5962 lines.retain(|line| seen.insert(line.to_lowercase()));
5963 })
5964 }
5965
5966 pub fn unique_lines_case_sensitive(
5967 &mut self,
5968 _: &UniqueLinesCaseSensitive,
5969 cx: &mut ViewContext<Self>,
5970 ) {
5971 self.manipulate_lines(cx, |lines| {
5972 let mut seen = HashSet::default();
5973 lines.retain(|line| seen.insert(*line));
5974 })
5975 }
5976
5977 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
5978 let mut revert_changes = HashMap::default();
5979 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
5980 for hunk in hunks_for_rows(
5981 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
5982 &multi_buffer_snapshot,
5983 ) {
5984 Self::prepare_revert_change(&mut revert_changes, &self.buffer(), &hunk, cx);
5985 }
5986 if !revert_changes.is_empty() {
5987 self.transact(cx, |editor, cx| {
5988 editor.revert(revert_changes, cx);
5989 });
5990 }
5991 }
5992
5993 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
5994 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
5995 if !revert_changes.is_empty() {
5996 self.transact(cx, |editor, cx| {
5997 editor.revert(revert_changes, cx);
5998 });
5999 }
6000 }
6001
6002 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6003 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6004 let project_path = buffer.read(cx).project_path(cx)?;
6005 let project = self.project.as_ref()?.read(cx);
6006 let entry = project.entry_for_path(&project_path, cx)?;
6007 let abs_path = project.absolute_path(&project_path, cx)?;
6008 let parent = if entry.is_symlink {
6009 abs_path.canonicalize().ok()?
6010 } else {
6011 abs_path
6012 }
6013 .parent()?
6014 .to_path_buf();
6015 Some(parent)
6016 }) {
6017 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6018 }
6019 }
6020
6021 fn gather_revert_changes(
6022 &mut self,
6023 selections: &[Selection<Anchor>],
6024 cx: &mut ViewContext<'_, Editor>,
6025 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6026 let mut revert_changes = HashMap::default();
6027 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6028 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6029 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6030 }
6031 revert_changes
6032 }
6033
6034 pub fn prepare_revert_change(
6035 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6036 multi_buffer: &Model<MultiBuffer>,
6037 hunk: &DiffHunk<MultiBufferRow>,
6038 cx: &AppContext,
6039 ) -> Option<()> {
6040 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6041 let buffer = buffer.read(cx);
6042 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6043 let buffer_snapshot = buffer.snapshot();
6044 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6045 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6046 probe
6047 .0
6048 .start
6049 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6050 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6051 }) {
6052 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6053 Some(())
6054 } else {
6055 None
6056 }
6057 }
6058
6059 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6060 self.manipulate_lines(cx, |lines| lines.reverse())
6061 }
6062
6063 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6064 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6065 }
6066
6067 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6068 where
6069 Fn: FnMut(&mut Vec<&str>),
6070 {
6071 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6072 let buffer = self.buffer.read(cx).snapshot(cx);
6073
6074 let mut edits = Vec::new();
6075
6076 let selections = self.selections.all::<Point>(cx);
6077 let mut selections = selections.iter().peekable();
6078 let mut contiguous_row_selections = Vec::new();
6079 let mut new_selections = Vec::new();
6080 let mut added_lines = 0;
6081 let mut removed_lines = 0;
6082
6083 while let Some(selection) = selections.next() {
6084 let (start_row, end_row) = consume_contiguous_rows(
6085 &mut contiguous_row_selections,
6086 selection,
6087 &display_map,
6088 &mut selections,
6089 );
6090
6091 let start_point = Point::new(start_row.0, 0);
6092 let end_point = Point::new(
6093 end_row.previous_row().0,
6094 buffer.line_len(end_row.previous_row()),
6095 );
6096 let text = buffer
6097 .text_for_range(start_point..end_point)
6098 .collect::<String>();
6099
6100 let mut lines = text.split('\n').collect_vec();
6101
6102 let lines_before = lines.len();
6103 callback(&mut lines);
6104 let lines_after = lines.len();
6105
6106 edits.push((start_point..end_point, lines.join("\n")));
6107
6108 // Selections must change based on added and removed line count
6109 let start_row =
6110 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6111 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6112 new_selections.push(Selection {
6113 id: selection.id,
6114 start: start_row,
6115 end: end_row,
6116 goal: SelectionGoal::None,
6117 reversed: selection.reversed,
6118 });
6119
6120 if lines_after > lines_before {
6121 added_lines += lines_after - lines_before;
6122 } else if lines_before > lines_after {
6123 removed_lines += lines_before - lines_after;
6124 }
6125 }
6126
6127 self.transact(cx, |this, cx| {
6128 let buffer = this.buffer.update(cx, |buffer, cx| {
6129 buffer.edit(edits, None, cx);
6130 buffer.snapshot(cx)
6131 });
6132
6133 // Recalculate offsets on newly edited buffer
6134 let new_selections = new_selections
6135 .iter()
6136 .map(|s| {
6137 let start_point = Point::new(s.start.0, 0);
6138 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6139 Selection {
6140 id: s.id,
6141 start: buffer.point_to_offset(start_point),
6142 end: buffer.point_to_offset(end_point),
6143 goal: s.goal,
6144 reversed: s.reversed,
6145 }
6146 })
6147 .collect();
6148
6149 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6150 s.select(new_selections);
6151 });
6152
6153 this.request_autoscroll(Autoscroll::fit(), cx);
6154 });
6155 }
6156
6157 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6158 self.manipulate_text(cx, |text| text.to_uppercase())
6159 }
6160
6161 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6162 self.manipulate_text(cx, |text| text.to_lowercase())
6163 }
6164
6165 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6166 self.manipulate_text(cx, |text| {
6167 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6168 // https://github.com/rutrum/convert-case/issues/16
6169 text.split('\n')
6170 .map(|line| line.to_case(Case::Title))
6171 .join("\n")
6172 })
6173 }
6174
6175 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6176 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6177 }
6178
6179 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6180 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6181 }
6182
6183 pub fn convert_to_upper_camel_case(
6184 &mut self,
6185 _: &ConvertToUpperCamelCase,
6186 cx: &mut ViewContext<Self>,
6187 ) {
6188 self.manipulate_text(cx, |text| {
6189 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6190 // https://github.com/rutrum/convert-case/issues/16
6191 text.split('\n')
6192 .map(|line| line.to_case(Case::UpperCamel))
6193 .join("\n")
6194 })
6195 }
6196
6197 pub fn convert_to_lower_camel_case(
6198 &mut self,
6199 _: &ConvertToLowerCamelCase,
6200 cx: &mut ViewContext<Self>,
6201 ) {
6202 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6203 }
6204
6205 pub fn convert_to_opposite_case(
6206 &mut self,
6207 _: &ConvertToOppositeCase,
6208 cx: &mut ViewContext<Self>,
6209 ) {
6210 self.manipulate_text(cx, |text| {
6211 text.chars()
6212 .fold(String::with_capacity(text.len()), |mut t, c| {
6213 if c.is_uppercase() {
6214 t.extend(c.to_lowercase());
6215 } else {
6216 t.extend(c.to_uppercase());
6217 }
6218 t
6219 })
6220 })
6221 }
6222
6223 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6224 where
6225 Fn: FnMut(&str) -> String,
6226 {
6227 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6228 let buffer = self.buffer.read(cx).snapshot(cx);
6229
6230 let mut new_selections = Vec::new();
6231 let mut edits = Vec::new();
6232 let mut selection_adjustment = 0i32;
6233
6234 for selection in self.selections.all::<usize>(cx) {
6235 let selection_is_empty = selection.is_empty();
6236
6237 let (start, end) = if selection_is_empty {
6238 let word_range = movement::surrounding_word(
6239 &display_map,
6240 selection.start.to_display_point(&display_map),
6241 );
6242 let start = word_range.start.to_offset(&display_map, Bias::Left);
6243 let end = word_range.end.to_offset(&display_map, Bias::Left);
6244 (start, end)
6245 } else {
6246 (selection.start, selection.end)
6247 };
6248
6249 let text = buffer.text_for_range(start..end).collect::<String>();
6250 let old_length = text.len() as i32;
6251 let text = callback(&text);
6252
6253 new_selections.push(Selection {
6254 start: (start as i32 - selection_adjustment) as usize,
6255 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6256 goal: SelectionGoal::None,
6257 ..selection
6258 });
6259
6260 selection_adjustment += old_length - text.len() as i32;
6261
6262 edits.push((start..end, text));
6263 }
6264
6265 self.transact(cx, |this, cx| {
6266 this.buffer.update(cx, |buffer, cx| {
6267 buffer.edit(edits, None, cx);
6268 });
6269
6270 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6271 s.select(new_selections);
6272 });
6273
6274 this.request_autoscroll(Autoscroll::fit(), cx);
6275 });
6276 }
6277
6278 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6279 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6280 let buffer = &display_map.buffer_snapshot;
6281 let selections = self.selections.all::<Point>(cx);
6282
6283 let mut edits = Vec::new();
6284 let mut selections_iter = selections.iter().peekable();
6285 while let Some(selection) = selections_iter.next() {
6286 // Avoid duplicating the same lines twice.
6287 let mut rows = selection.spanned_rows(false, &display_map);
6288
6289 while let Some(next_selection) = selections_iter.peek() {
6290 let next_rows = next_selection.spanned_rows(false, &display_map);
6291 if next_rows.start < rows.end {
6292 rows.end = next_rows.end;
6293 selections_iter.next().unwrap();
6294 } else {
6295 break;
6296 }
6297 }
6298
6299 // Copy the text from the selected row region and splice it either at the start
6300 // or end of the region.
6301 let start = Point::new(rows.start.0, 0);
6302 let end = Point::new(
6303 rows.end.previous_row().0,
6304 buffer.line_len(rows.end.previous_row()),
6305 );
6306 let text = buffer
6307 .text_for_range(start..end)
6308 .chain(Some("\n"))
6309 .collect::<String>();
6310 let insert_location = if upwards {
6311 Point::new(rows.end.0, 0)
6312 } else {
6313 start
6314 };
6315 edits.push((insert_location..insert_location, text));
6316 }
6317
6318 self.transact(cx, |this, cx| {
6319 this.buffer.update(cx, |buffer, cx| {
6320 buffer.edit(edits, None, cx);
6321 });
6322
6323 this.request_autoscroll(Autoscroll::fit(), cx);
6324 });
6325 }
6326
6327 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6328 self.duplicate_line(true, cx);
6329 }
6330
6331 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6332 self.duplicate_line(false, cx);
6333 }
6334
6335 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6336 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6337 let buffer = self.buffer.read(cx).snapshot(cx);
6338
6339 let mut edits = Vec::new();
6340 let mut unfold_ranges = Vec::new();
6341 let mut refold_ranges = Vec::new();
6342
6343 let selections = self.selections.all::<Point>(cx);
6344 let mut selections = selections.iter().peekable();
6345 let mut contiguous_row_selections = Vec::new();
6346 let mut new_selections = Vec::new();
6347
6348 while let Some(selection) = selections.next() {
6349 // Find all the selections that span a contiguous row range
6350 let (start_row, end_row) = consume_contiguous_rows(
6351 &mut contiguous_row_selections,
6352 selection,
6353 &display_map,
6354 &mut selections,
6355 );
6356
6357 // Move the text spanned by the row range to be before the line preceding the row range
6358 if start_row.0 > 0 {
6359 let range_to_move = Point::new(
6360 start_row.previous_row().0,
6361 buffer.line_len(start_row.previous_row()),
6362 )
6363 ..Point::new(
6364 end_row.previous_row().0,
6365 buffer.line_len(end_row.previous_row()),
6366 );
6367 let insertion_point = display_map
6368 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6369 .0;
6370
6371 // Don't move lines across excerpts
6372 if buffer
6373 .excerpt_boundaries_in_range((
6374 Bound::Excluded(insertion_point),
6375 Bound::Included(range_to_move.end),
6376 ))
6377 .next()
6378 .is_none()
6379 {
6380 let text = buffer
6381 .text_for_range(range_to_move.clone())
6382 .flat_map(|s| s.chars())
6383 .skip(1)
6384 .chain(['\n'])
6385 .collect::<String>();
6386
6387 edits.push((
6388 buffer.anchor_after(range_to_move.start)
6389 ..buffer.anchor_before(range_to_move.end),
6390 String::new(),
6391 ));
6392 let insertion_anchor = buffer.anchor_after(insertion_point);
6393 edits.push((insertion_anchor..insertion_anchor, text));
6394
6395 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6396
6397 // Move selections up
6398 new_selections.extend(contiguous_row_selections.drain(..).map(
6399 |mut selection| {
6400 selection.start.row -= row_delta;
6401 selection.end.row -= row_delta;
6402 selection
6403 },
6404 ));
6405
6406 // Move folds up
6407 unfold_ranges.push(range_to_move.clone());
6408 for fold in display_map.folds_in_range(
6409 buffer.anchor_before(range_to_move.start)
6410 ..buffer.anchor_after(range_to_move.end),
6411 ) {
6412 let mut start = fold.range.start.to_point(&buffer);
6413 let mut end = fold.range.end.to_point(&buffer);
6414 start.row -= row_delta;
6415 end.row -= row_delta;
6416 refold_ranges.push((start..end, fold.placeholder.clone()));
6417 }
6418 }
6419 }
6420
6421 // If we didn't move line(s), preserve the existing selections
6422 new_selections.append(&mut contiguous_row_selections);
6423 }
6424
6425 self.transact(cx, |this, cx| {
6426 this.unfold_ranges(unfold_ranges, true, true, cx);
6427 this.buffer.update(cx, |buffer, cx| {
6428 for (range, text) in edits {
6429 buffer.edit([(range, text)], None, cx);
6430 }
6431 });
6432 this.fold_ranges(refold_ranges, true, cx);
6433 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6434 s.select(new_selections);
6435 })
6436 });
6437 }
6438
6439 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6440 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6441 let buffer = self.buffer.read(cx).snapshot(cx);
6442
6443 let mut edits = Vec::new();
6444 let mut unfold_ranges = Vec::new();
6445 let mut refold_ranges = Vec::new();
6446
6447 let selections = self.selections.all::<Point>(cx);
6448 let mut selections = selections.iter().peekable();
6449 let mut contiguous_row_selections = Vec::new();
6450 let mut new_selections = Vec::new();
6451
6452 while let Some(selection) = selections.next() {
6453 // Find all the selections that span a contiguous row range
6454 let (start_row, end_row) = consume_contiguous_rows(
6455 &mut contiguous_row_selections,
6456 selection,
6457 &display_map,
6458 &mut selections,
6459 );
6460
6461 // Move the text spanned by the row range to be after the last line of the row range
6462 if end_row.0 <= buffer.max_point().row {
6463 let range_to_move =
6464 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6465 let insertion_point = display_map
6466 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6467 .0;
6468
6469 // Don't move lines across excerpt boundaries
6470 if buffer
6471 .excerpt_boundaries_in_range((
6472 Bound::Excluded(range_to_move.start),
6473 Bound::Included(insertion_point),
6474 ))
6475 .next()
6476 .is_none()
6477 {
6478 let mut text = String::from("\n");
6479 text.extend(buffer.text_for_range(range_to_move.clone()));
6480 text.pop(); // Drop trailing newline
6481 edits.push((
6482 buffer.anchor_after(range_to_move.start)
6483 ..buffer.anchor_before(range_to_move.end),
6484 String::new(),
6485 ));
6486 let insertion_anchor = buffer.anchor_after(insertion_point);
6487 edits.push((insertion_anchor..insertion_anchor, text));
6488
6489 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6490
6491 // Move selections down
6492 new_selections.extend(contiguous_row_selections.drain(..).map(
6493 |mut selection| {
6494 selection.start.row += row_delta;
6495 selection.end.row += row_delta;
6496 selection
6497 },
6498 ));
6499
6500 // Move folds down
6501 unfold_ranges.push(range_to_move.clone());
6502 for fold in display_map.folds_in_range(
6503 buffer.anchor_before(range_to_move.start)
6504 ..buffer.anchor_after(range_to_move.end),
6505 ) {
6506 let mut start = fold.range.start.to_point(&buffer);
6507 let mut end = fold.range.end.to_point(&buffer);
6508 start.row += row_delta;
6509 end.row += row_delta;
6510 refold_ranges.push((start..end, fold.placeholder.clone()));
6511 }
6512 }
6513 }
6514
6515 // If we didn't move line(s), preserve the existing selections
6516 new_selections.append(&mut contiguous_row_selections);
6517 }
6518
6519 self.transact(cx, |this, cx| {
6520 this.unfold_ranges(unfold_ranges, true, true, cx);
6521 this.buffer.update(cx, |buffer, cx| {
6522 for (range, text) in edits {
6523 buffer.edit([(range, text)], None, cx);
6524 }
6525 });
6526 this.fold_ranges(refold_ranges, true, cx);
6527 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6528 });
6529 }
6530
6531 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6532 let text_layout_details = &self.text_layout_details(cx);
6533 self.transact(cx, |this, cx| {
6534 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6535 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6536 let line_mode = s.line_mode;
6537 s.move_with(|display_map, selection| {
6538 if !selection.is_empty() || line_mode {
6539 return;
6540 }
6541
6542 let mut head = selection.head();
6543 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6544 if head.column() == display_map.line_len(head.row()) {
6545 transpose_offset = display_map
6546 .buffer_snapshot
6547 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6548 }
6549
6550 if transpose_offset == 0 {
6551 return;
6552 }
6553
6554 *head.column_mut() += 1;
6555 head = display_map.clip_point(head, Bias::Right);
6556 let goal = SelectionGoal::HorizontalPosition(
6557 display_map
6558 .x_for_display_point(head, &text_layout_details)
6559 .into(),
6560 );
6561 selection.collapse_to(head, goal);
6562
6563 let transpose_start = display_map
6564 .buffer_snapshot
6565 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6566 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6567 let transpose_end = display_map
6568 .buffer_snapshot
6569 .clip_offset(transpose_offset + 1, Bias::Right);
6570 if let Some(ch) =
6571 display_map.buffer_snapshot.chars_at(transpose_start).next()
6572 {
6573 edits.push((transpose_start..transpose_offset, String::new()));
6574 edits.push((transpose_end..transpose_end, ch.to_string()));
6575 }
6576 }
6577 });
6578 edits
6579 });
6580 this.buffer
6581 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6582 let selections = this.selections.all::<usize>(cx);
6583 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6584 s.select(selections);
6585 });
6586 });
6587 }
6588
6589 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6590 let mut text = String::new();
6591 let buffer = self.buffer.read(cx).snapshot(cx);
6592 let mut selections = self.selections.all::<Point>(cx);
6593 let mut clipboard_selections = Vec::with_capacity(selections.len());
6594 {
6595 let max_point = buffer.max_point();
6596 let mut is_first = true;
6597 for selection in &mut selections {
6598 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6599 if is_entire_line {
6600 selection.start = Point::new(selection.start.row, 0);
6601 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6602 selection.goal = SelectionGoal::None;
6603 }
6604 if is_first {
6605 is_first = false;
6606 } else {
6607 text += "\n";
6608 }
6609 let mut len = 0;
6610 for chunk in buffer.text_for_range(selection.start..selection.end) {
6611 text.push_str(chunk);
6612 len += chunk.len();
6613 }
6614 clipboard_selections.push(ClipboardSelection {
6615 len,
6616 is_entire_line,
6617 first_line_indent: buffer
6618 .indent_size_for_line(MultiBufferRow(selection.start.row))
6619 .len,
6620 });
6621 }
6622 }
6623
6624 self.transact(cx, |this, cx| {
6625 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6626 s.select(selections);
6627 });
6628 this.insert("", cx);
6629 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6630 text,
6631 clipboard_selections,
6632 ));
6633 });
6634 }
6635
6636 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6637 let selections = self.selections.all::<Point>(cx);
6638 let buffer = self.buffer.read(cx).read(cx);
6639 let mut text = String::new();
6640
6641 let mut clipboard_selections = Vec::with_capacity(selections.len());
6642 {
6643 let max_point = buffer.max_point();
6644 let mut is_first = true;
6645 for selection in selections.iter() {
6646 let mut start = selection.start;
6647 let mut end = selection.end;
6648 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6649 if is_entire_line {
6650 start = Point::new(start.row, 0);
6651 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6652 }
6653 if is_first {
6654 is_first = false;
6655 } else {
6656 text += "\n";
6657 }
6658 let mut len = 0;
6659 for chunk in buffer.text_for_range(start..end) {
6660 text.push_str(chunk);
6661 len += chunk.len();
6662 }
6663 clipboard_selections.push(ClipboardSelection {
6664 len,
6665 is_entire_line,
6666 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6667 });
6668 }
6669 }
6670
6671 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6672 text,
6673 clipboard_selections,
6674 ));
6675 }
6676
6677 pub fn do_paste(
6678 &mut self,
6679 text: &String,
6680 clipboard_selections: Option<Vec<ClipboardSelection>>,
6681 handle_entire_lines: bool,
6682 cx: &mut ViewContext<Self>,
6683 ) {
6684 if self.read_only(cx) {
6685 return;
6686 }
6687
6688 let clipboard_text = Cow::Borrowed(text);
6689
6690 self.transact(cx, |this, cx| {
6691 if let Some(mut clipboard_selections) = clipboard_selections {
6692 let old_selections = this.selections.all::<usize>(cx);
6693 let all_selections_were_entire_line =
6694 clipboard_selections.iter().all(|s| s.is_entire_line);
6695 let first_selection_indent_column =
6696 clipboard_selections.first().map(|s| s.first_line_indent);
6697 if clipboard_selections.len() != old_selections.len() {
6698 clipboard_selections.drain(..);
6699 }
6700
6701 this.buffer.update(cx, |buffer, cx| {
6702 let snapshot = buffer.read(cx);
6703 let mut start_offset = 0;
6704 let mut edits = Vec::new();
6705 let mut original_indent_columns = Vec::new();
6706 for (ix, selection) in old_selections.iter().enumerate() {
6707 let to_insert;
6708 let entire_line;
6709 let original_indent_column;
6710 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6711 let end_offset = start_offset + clipboard_selection.len;
6712 to_insert = &clipboard_text[start_offset..end_offset];
6713 entire_line = clipboard_selection.is_entire_line;
6714 start_offset = end_offset + 1;
6715 original_indent_column = Some(clipboard_selection.first_line_indent);
6716 } else {
6717 to_insert = clipboard_text.as_str();
6718 entire_line = all_selections_were_entire_line;
6719 original_indent_column = first_selection_indent_column
6720 }
6721
6722 // If the corresponding selection was empty when this slice of the
6723 // clipboard text was written, then the entire line containing the
6724 // selection was copied. If this selection is also currently empty,
6725 // then paste the line before the current line of the buffer.
6726 let range = if selection.is_empty() && handle_entire_lines && entire_line {
6727 let column = selection.start.to_point(&snapshot).column as usize;
6728 let line_start = selection.start - column;
6729 line_start..line_start
6730 } else {
6731 selection.range()
6732 };
6733
6734 edits.push((range, to_insert));
6735 original_indent_columns.extend(original_indent_column);
6736 }
6737 drop(snapshot);
6738
6739 buffer.edit(
6740 edits,
6741 Some(AutoindentMode::Block {
6742 original_indent_columns,
6743 }),
6744 cx,
6745 );
6746 });
6747
6748 let selections = this.selections.all::<usize>(cx);
6749 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6750 } else {
6751 this.insert(&clipboard_text, cx);
6752 }
6753 });
6754 }
6755
6756 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
6757 if let Some(item) = cx.read_from_clipboard() {
6758 let entries = item.entries();
6759
6760 match entries.first() {
6761 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
6762 // of all the pasted entries.
6763 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
6764 .do_paste(
6765 clipboard_string.text(),
6766 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
6767 true,
6768 cx,
6769 ),
6770 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
6771 }
6772 }
6773 }
6774
6775 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
6776 if self.read_only(cx) {
6777 return;
6778 }
6779
6780 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
6781 if let Some((selections, _)) =
6782 self.selection_history.transaction(transaction_id).cloned()
6783 {
6784 self.change_selections(None, cx, |s| {
6785 s.select_anchors(selections.to_vec());
6786 });
6787 }
6788 self.request_autoscroll(Autoscroll::fit(), cx);
6789 self.unmark_text(cx);
6790 self.refresh_inline_completion(true, cx);
6791 cx.emit(EditorEvent::Edited { transaction_id });
6792 cx.emit(EditorEvent::TransactionUndone { transaction_id });
6793 }
6794 }
6795
6796 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
6797 if self.read_only(cx) {
6798 return;
6799 }
6800
6801 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
6802 if let Some((_, Some(selections))) =
6803 self.selection_history.transaction(transaction_id).cloned()
6804 {
6805 self.change_selections(None, cx, |s| {
6806 s.select_anchors(selections.to_vec());
6807 });
6808 }
6809 self.request_autoscroll(Autoscroll::fit(), cx);
6810 self.unmark_text(cx);
6811 self.refresh_inline_completion(true, cx);
6812 cx.emit(EditorEvent::Edited { transaction_id });
6813 }
6814 }
6815
6816 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
6817 self.buffer
6818 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
6819 }
6820
6821 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
6822 self.buffer
6823 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
6824 }
6825
6826 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
6827 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6828 let line_mode = s.line_mode;
6829 s.move_with(|map, selection| {
6830 let cursor = if selection.is_empty() && !line_mode {
6831 movement::left(map, selection.start)
6832 } else {
6833 selection.start
6834 };
6835 selection.collapse_to(cursor, SelectionGoal::None);
6836 });
6837 })
6838 }
6839
6840 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
6841 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6842 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
6843 })
6844 }
6845
6846 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
6847 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6848 let line_mode = s.line_mode;
6849 s.move_with(|map, selection| {
6850 let cursor = if selection.is_empty() && !line_mode {
6851 movement::right(map, selection.end)
6852 } else {
6853 selection.end
6854 };
6855 selection.collapse_to(cursor, SelectionGoal::None)
6856 });
6857 })
6858 }
6859
6860 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
6861 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6862 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
6863 })
6864 }
6865
6866 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
6867 if self.take_rename(true, cx).is_some() {
6868 return;
6869 }
6870
6871 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6872 cx.propagate();
6873 return;
6874 }
6875
6876 let text_layout_details = &self.text_layout_details(cx);
6877 let selection_count = self.selections.count();
6878 let first_selection = self.selections.first_anchor();
6879
6880 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6881 let line_mode = s.line_mode;
6882 s.move_with(|map, selection| {
6883 if !selection.is_empty() && !line_mode {
6884 selection.goal = SelectionGoal::None;
6885 }
6886 let (cursor, goal) = movement::up(
6887 map,
6888 selection.start,
6889 selection.goal,
6890 false,
6891 &text_layout_details,
6892 );
6893 selection.collapse_to(cursor, goal);
6894 });
6895 });
6896
6897 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
6898 {
6899 cx.propagate();
6900 }
6901 }
6902
6903 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
6904 if self.take_rename(true, cx).is_some() {
6905 return;
6906 }
6907
6908 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6909 cx.propagate();
6910 return;
6911 }
6912
6913 let text_layout_details = &self.text_layout_details(cx);
6914
6915 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6916 let line_mode = s.line_mode;
6917 s.move_with(|map, selection| {
6918 if !selection.is_empty() && !line_mode {
6919 selection.goal = SelectionGoal::None;
6920 }
6921 let (cursor, goal) = movement::up_by_rows(
6922 map,
6923 selection.start,
6924 action.lines,
6925 selection.goal,
6926 false,
6927 &text_layout_details,
6928 );
6929 selection.collapse_to(cursor, goal);
6930 });
6931 })
6932 }
6933
6934 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
6935 if self.take_rename(true, cx).is_some() {
6936 return;
6937 }
6938
6939 if matches!(self.mode, EditorMode::SingleLine { .. }) {
6940 cx.propagate();
6941 return;
6942 }
6943
6944 let text_layout_details = &self.text_layout_details(cx);
6945
6946 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6947 let line_mode = s.line_mode;
6948 s.move_with(|map, selection| {
6949 if !selection.is_empty() && !line_mode {
6950 selection.goal = SelectionGoal::None;
6951 }
6952 let (cursor, goal) = movement::down_by_rows(
6953 map,
6954 selection.start,
6955 action.lines,
6956 selection.goal,
6957 false,
6958 &text_layout_details,
6959 );
6960 selection.collapse_to(cursor, goal);
6961 });
6962 })
6963 }
6964
6965 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
6966 let text_layout_details = &self.text_layout_details(cx);
6967 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6968 s.move_heads_with(|map, head, goal| {
6969 movement::down_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6970 })
6971 })
6972 }
6973
6974 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
6975 let text_layout_details = &self.text_layout_details(cx);
6976 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6977 s.move_heads_with(|map, head, goal| {
6978 movement::up_by_rows(map, head, action.lines, goal, false, &text_layout_details)
6979 })
6980 })
6981 }
6982
6983 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
6984 let Some(row_count) = self.visible_row_count() else {
6985 return;
6986 };
6987
6988 let text_layout_details = &self.text_layout_details(cx);
6989
6990 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
6991 s.move_heads_with(|map, head, goal| {
6992 movement::up_by_rows(map, head, row_count, goal, false, &text_layout_details)
6993 })
6994 })
6995 }
6996
6997 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
6998 if self.take_rename(true, cx).is_some() {
6999 return;
7000 }
7001
7002 if self
7003 .context_menu
7004 .write()
7005 .as_mut()
7006 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7007 .unwrap_or(false)
7008 {
7009 return;
7010 }
7011
7012 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7013 cx.propagate();
7014 return;
7015 }
7016
7017 let Some(row_count) = self.visible_row_count() else {
7018 return;
7019 };
7020
7021 let autoscroll = if action.center_cursor {
7022 Autoscroll::center()
7023 } else {
7024 Autoscroll::fit()
7025 };
7026
7027 let text_layout_details = &self.text_layout_details(cx);
7028
7029 self.change_selections(Some(autoscroll), cx, |s| {
7030 let line_mode = s.line_mode;
7031 s.move_with(|map, selection| {
7032 if !selection.is_empty() && !line_mode {
7033 selection.goal = SelectionGoal::None;
7034 }
7035 let (cursor, goal) = movement::up_by_rows(
7036 map,
7037 selection.end,
7038 row_count,
7039 selection.goal,
7040 false,
7041 &text_layout_details,
7042 );
7043 selection.collapse_to(cursor, goal);
7044 });
7045 });
7046 }
7047
7048 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7049 let text_layout_details = &self.text_layout_details(cx);
7050 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7051 s.move_heads_with(|map, head, goal| {
7052 movement::up(map, head, goal, false, &text_layout_details)
7053 })
7054 })
7055 }
7056
7057 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7058 self.take_rename(true, cx);
7059
7060 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7061 cx.propagate();
7062 return;
7063 }
7064
7065 let text_layout_details = &self.text_layout_details(cx);
7066 let selection_count = self.selections.count();
7067 let first_selection = self.selections.first_anchor();
7068
7069 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7070 let line_mode = s.line_mode;
7071 s.move_with(|map, selection| {
7072 if !selection.is_empty() && !line_mode {
7073 selection.goal = SelectionGoal::None;
7074 }
7075 let (cursor, goal) = movement::down(
7076 map,
7077 selection.end,
7078 selection.goal,
7079 false,
7080 &text_layout_details,
7081 );
7082 selection.collapse_to(cursor, goal);
7083 });
7084 });
7085
7086 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7087 {
7088 cx.propagate();
7089 }
7090 }
7091
7092 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7093 let Some(row_count) = self.visible_row_count() else {
7094 return;
7095 };
7096
7097 let text_layout_details = &self.text_layout_details(cx);
7098
7099 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7100 s.move_heads_with(|map, head, goal| {
7101 movement::down_by_rows(map, head, row_count, goal, false, &text_layout_details)
7102 })
7103 })
7104 }
7105
7106 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7107 if self.take_rename(true, cx).is_some() {
7108 return;
7109 }
7110
7111 if self
7112 .context_menu
7113 .write()
7114 .as_mut()
7115 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7116 .unwrap_or(false)
7117 {
7118 return;
7119 }
7120
7121 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7122 cx.propagate();
7123 return;
7124 }
7125
7126 let Some(row_count) = self.visible_row_count() else {
7127 return;
7128 };
7129
7130 let autoscroll = if action.center_cursor {
7131 Autoscroll::center()
7132 } else {
7133 Autoscroll::fit()
7134 };
7135
7136 let text_layout_details = &self.text_layout_details(cx);
7137 self.change_selections(Some(autoscroll), cx, |s| {
7138 let line_mode = s.line_mode;
7139 s.move_with(|map, selection| {
7140 if !selection.is_empty() && !line_mode {
7141 selection.goal = SelectionGoal::None;
7142 }
7143 let (cursor, goal) = movement::down_by_rows(
7144 map,
7145 selection.end,
7146 row_count,
7147 selection.goal,
7148 false,
7149 &text_layout_details,
7150 );
7151 selection.collapse_to(cursor, goal);
7152 });
7153 });
7154 }
7155
7156 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7157 let text_layout_details = &self.text_layout_details(cx);
7158 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7159 s.move_heads_with(|map, head, goal| {
7160 movement::down(map, head, goal, false, &text_layout_details)
7161 })
7162 });
7163 }
7164
7165 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7166 if let Some(context_menu) = self.context_menu.write().as_mut() {
7167 context_menu.select_first(self.project.as_ref(), cx);
7168 }
7169 }
7170
7171 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7172 if let Some(context_menu) = self.context_menu.write().as_mut() {
7173 context_menu.select_prev(self.project.as_ref(), cx);
7174 }
7175 }
7176
7177 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7178 if let Some(context_menu) = self.context_menu.write().as_mut() {
7179 context_menu.select_next(self.project.as_ref(), cx);
7180 }
7181 }
7182
7183 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7184 if let Some(context_menu) = self.context_menu.write().as_mut() {
7185 context_menu.select_last(self.project.as_ref(), cx);
7186 }
7187 }
7188
7189 pub fn move_to_previous_word_start(
7190 &mut self,
7191 _: &MoveToPreviousWordStart,
7192 cx: &mut ViewContext<Self>,
7193 ) {
7194 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7195 s.move_cursors_with(|map, head, _| {
7196 (
7197 movement::previous_word_start(map, head),
7198 SelectionGoal::None,
7199 )
7200 });
7201 })
7202 }
7203
7204 pub fn move_to_previous_subword_start(
7205 &mut self,
7206 _: &MoveToPreviousSubwordStart,
7207 cx: &mut ViewContext<Self>,
7208 ) {
7209 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7210 s.move_cursors_with(|map, head, _| {
7211 (
7212 movement::previous_subword_start(map, head),
7213 SelectionGoal::None,
7214 )
7215 });
7216 })
7217 }
7218
7219 pub fn select_to_previous_word_start(
7220 &mut self,
7221 _: &SelectToPreviousWordStart,
7222 cx: &mut ViewContext<Self>,
7223 ) {
7224 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7225 s.move_heads_with(|map, head, _| {
7226 (
7227 movement::previous_word_start(map, head),
7228 SelectionGoal::None,
7229 )
7230 });
7231 })
7232 }
7233
7234 pub fn select_to_previous_subword_start(
7235 &mut self,
7236 _: &SelectToPreviousSubwordStart,
7237 cx: &mut ViewContext<Self>,
7238 ) {
7239 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7240 s.move_heads_with(|map, head, _| {
7241 (
7242 movement::previous_subword_start(map, head),
7243 SelectionGoal::None,
7244 )
7245 });
7246 })
7247 }
7248
7249 pub fn delete_to_previous_word_start(
7250 &mut self,
7251 _: &DeleteToPreviousWordStart,
7252 cx: &mut ViewContext<Self>,
7253 ) {
7254 self.transact(cx, |this, cx| {
7255 this.select_autoclose_pair(cx);
7256 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7257 let line_mode = s.line_mode;
7258 s.move_with(|map, selection| {
7259 if selection.is_empty() && !line_mode {
7260 let cursor = movement::previous_word_start(map, selection.head());
7261 selection.set_head(cursor, SelectionGoal::None);
7262 }
7263 });
7264 });
7265 this.insert("", cx);
7266 });
7267 }
7268
7269 pub fn delete_to_previous_subword_start(
7270 &mut self,
7271 _: &DeleteToPreviousSubwordStart,
7272 cx: &mut ViewContext<Self>,
7273 ) {
7274 self.transact(cx, |this, cx| {
7275 this.select_autoclose_pair(cx);
7276 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7277 let line_mode = s.line_mode;
7278 s.move_with(|map, selection| {
7279 if selection.is_empty() && !line_mode {
7280 let cursor = movement::previous_subword_start(map, selection.head());
7281 selection.set_head(cursor, SelectionGoal::None);
7282 }
7283 });
7284 });
7285 this.insert("", cx);
7286 });
7287 }
7288
7289 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7290 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7291 s.move_cursors_with(|map, head, _| {
7292 (movement::next_word_end(map, head), SelectionGoal::None)
7293 });
7294 })
7295 }
7296
7297 pub fn move_to_next_subword_end(
7298 &mut self,
7299 _: &MoveToNextSubwordEnd,
7300 cx: &mut ViewContext<Self>,
7301 ) {
7302 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7303 s.move_cursors_with(|map, head, _| {
7304 (movement::next_subword_end(map, head), SelectionGoal::None)
7305 });
7306 })
7307 }
7308
7309 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7310 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7311 s.move_heads_with(|map, head, _| {
7312 (movement::next_word_end(map, head), SelectionGoal::None)
7313 });
7314 })
7315 }
7316
7317 pub fn select_to_next_subword_end(
7318 &mut self,
7319 _: &SelectToNextSubwordEnd,
7320 cx: &mut ViewContext<Self>,
7321 ) {
7322 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7323 s.move_heads_with(|map, head, _| {
7324 (movement::next_subword_end(map, head), SelectionGoal::None)
7325 });
7326 })
7327 }
7328
7329 pub fn delete_to_next_word_end(&mut self, _: &DeleteToNextWordEnd, cx: &mut ViewContext<Self>) {
7330 self.transact(cx, |this, cx| {
7331 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7332 let line_mode = s.line_mode;
7333 s.move_with(|map, selection| {
7334 if selection.is_empty() && !line_mode {
7335 let cursor = movement::next_word_end(map, selection.head());
7336 selection.set_head(cursor, SelectionGoal::None);
7337 }
7338 });
7339 });
7340 this.insert("", cx);
7341 });
7342 }
7343
7344 pub fn delete_to_next_subword_end(
7345 &mut self,
7346 _: &DeleteToNextSubwordEnd,
7347 cx: &mut ViewContext<Self>,
7348 ) {
7349 self.transact(cx, |this, cx| {
7350 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7351 s.move_with(|map, selection| {
7352 if selection.is_empty() {
7353 let cursor = movement::next_subword_end(map, selection.head());
7354 selection.set_head(cursor, SelectionGoal::None);
7355 }
7356 });
7357 });
7358 this.insert("", cx);
7359 });
7360 }
7361
7362 pub fn move_to_beginning_of_line(
7363 &mut self,
7364 action: &MoveToBeginningOfLine,
7365 cx: &mut ViewContext<Self>,
7366 ) {
7367 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7368 s.move_cursors_with(|map, head, _| {
7369 (
7370 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7371 SelectionGoal::None,
7372 )
7373 });
7374 })
7375 }
7376
7377 pub fn select_to_beginning_of_line(
7378 &mut self,
7379 action: &SelectToBeginningOfLine,
7380 cx: &mut ViewContext<Self>,
7381 ) {
7382 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7383 s.move_heads_with(|map, head, _| {
7384 (
7385 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7386 SelectionGoal::None,
7387 )
7388 });
7389 });
7390 }
7391
7392 pub fn delete_to_beginning_of_line(
7393 &mut self,
7394 _: &DeleteToBeginningOfLine,
7395 cx: &mut ViewContext<Self>,
7396 ) {
7397 self.transact(cx, |this, cx| {
7398 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7399 s.move_with(|_, selection| {
7400 selection.reversed = true;
7401 });
7402 });
7403
7404 this.select_to_beginning_of_line(
7405 &SelectToBeginningOfLine {
7406 stop_at_soft_wraps: false,
7407 },
7408 cx,
7409 );
7410 this.backspace(&Backspace, cx);
7411 });
7412 }
7413
7414 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7415 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7416 s.move_cursors_with(|map, head, _| {
7417 (
7418 movement::line_end(map, head, action.stop_at_soft_wraps),
7419 SelectionGoal::None,
7420 )
7421 });
7422 })
7423 }
7424
7425 pub fn select_to_end_of_line(
7426 &mut self,
7427 action: &SelectToEndOfLine,
7428 cx: &mut ViewContext<Self>,
7429 ) {
7430 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7431 s.move_heads_with(|map, head, _| {
7432 (
7433 movement::line_end(map, head, action.stop_at_soft_wraps),
7434 SelectionGoal::None,
7435 )
7436 });
7437 })
7438 }
7439
7440 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7441 self.transact(cx, |this, cx| {
7442 this.select_to_end_of_line(
7443 &SelectToEndOfLine {
7444 stop_at_soft_wraps: false,
7445 },
7446 cx,
7447 );
7448 this.delete(&Delete, cx);
7449 });
7450 }
7451
7452 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7453 self.transact(cx, |this, cx| {
7454 this.select_to_end_of_line(
7455 &SelectToEndOfLine {
7456 stop_at_soft_wraps: false,
7457 },
7458 cx,
7459 );
7460 this.cut(&Cut, cx);
7461 });
7462 }
7463
7464 pub fn move_to_start_of_paragraph(
7465 &mut self,
7466 _: &MoveToStartOfParagraph,
7467 cx: &mut ViewContext<Self>,
7468 ) {
7469 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7470 cx.propagate();
7471 return;
7472 }
7473
7474 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7475 s.move_with(|map, selection| {
7476 selection.collapse_to(
7477 movement::start_of_paragraph(map, selection.head(), 1),
7478 SelectionGoal::None,
7479 )
7480 });
7481 })
7482 }
7483
7484 pub fn move_to_end_of_paragraph(
7485 &mut self,
7486 _: &MoveToEndOfParagraph,
7487 cx: &mut ViewContext<Self>,
7488 ) {
7489 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7490 cx.propagate();
7491 return;
7492 }
7493
7494 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7495 s.move_with(|map, selection| {
7496 selection.collapse_to(
7497 movement::end_of_paragraph(map, selection.head(), 1),
7498 SelectionGoal::None,
7499 )
7500 });
7501 })
7502 }
7503
7504 pub fn select_to_start_of_paragraph(
7505 &mut self,
7506 _: &SelectToStartOfParagraph,
7507 cx: &mut ViewContext<Self>,
7508 ) {
7509 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7510 cx.propagate();
7511 return;
7512 }
7513
7514 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7515 s.move_heads_with(|map, head, _| {
7516 (
7517 movement::start_of_paragraph(map, head, 1),
7518 SelectionGoal::None,
7519 )
7520 });
7521 })
7522 }
7523
7524 pub fn select_to_end_of_paragraph(
7525 &mut self,
7526 _: &SelectToEndOfParagraph,
7527 cx: &mut ViewContext<Self>,
7528 ) {
7529 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7530 cx.propagate();
7531 return;
7532 }
7533
7534 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7535 s.move_heads_with(|map, head, _| {
7536 (
7537 movement::end_of_paragraph(map, head, 1),
7538 SelectionGoal::None,
7539 )
7540 });
7541 })
7542 }
7543
7544 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7545 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7546 cx.propagate();
7547 return;
7548 }
7549
7550 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7551 s.select_ranges(vec![0..0]);
7552 });
7553 }
7554
7555 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7556 let mut selection = self.selections.last::<Point>(cx);
7557 selection.set_head(Point::zero(), SelectionGoal::None);
7558
7559 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7560 s.select(vec![selection]);
7561 });
7562 }
7563
7564 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7565 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7566 cx.propagate();
7567 return;
7568 }
7569
7570 let cursor = self.buffer.read(cx).read(cx).len();
7571 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7572 s.select_ranges(vec![cursor..cursor])
7573 });
7574 }
7575
7576 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7577 self.nav_history = nav_history;
7578 }
7579
7580 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7581 self.nav_history.as_ref()
7582 }
7583
7584 fn push_to_nav_history(
7585 &mut self,
7586 cursor_anchor: Anchor,
7587 new_position: Option<Point>,
7588 cx: &mut ViewContext<Self>,
7589 ) {
7590 if let Some(nav_history) = self.nav_history.as_mut() {
7591 let buffer = self.buffer.read(cx).read(cx);
7592 let cursor_position = cursor_anchor.to_point(&buffer);
7593 let scroll_state = self.scroll_manager.anchor();
7594 let scroll_top_row = scroll_state.top_row(&buffer);
7595 drop(buffer);
7596
7597 if let Some(new_position) = new_position {
7598 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7599 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7600 return;
7601 }
7602 }
7603
7604 nav_history.push(
7605 Some(NavigationData {
7606 cursor_anchor,
7607 cursor_position,
7608 scroll_anchor: scroll_state,
7609 scroll_top_row,
7610 }),
7611 cx,
7612 );
7613 }
7614 }
7615
7616 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7617 let buffer = self.buffer.read(cx).snapshot(cx);
7618 let mut selection = self.selections.first::<usize>(cx);
7619 selection.set_head(buffer.len(), SelectionGoal::None);
7620 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7621 s.select(vec![selection]);
7622 });
7623 }
7624
7625 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7626 let end = self.buffer.read(cx).read(cx).len();
7627 self.change_selections(None, cx, |s| {
7628 s.select_ranges(vec![0..end]);
7629 });
7630 }
7631
7632 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7633 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7634 let mut selections = self.selections.all::<Point>(cx);
7635 let max_point = display_map.buffer_snapshot.max_point();
7636 for selection in &mut selections {
7637 let rows = selection.spanned_rows(true, &display_map);
7638 selection.start = Point::new(rows.start.0, 0);
7639 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7640 selection.reversed = false;
7641 }
7642 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7643 s.select(selections);
7644 });
7645 }
7646
7647 pub fn split_selection_into_lines(
7648 &mut self,
7649 _: &SplitSelectionIntoLines,
7650 cx: &mut ViewContext<Self>,
7651 ) {
7652 let mut to_unfold = Vec::new();
7653 let mut new_selection_ranges = Vec::new();
7654 {
7655 let selections = self.selections.all::<Point>(cx);
7656 let buffer = self.buffer.read(cx).read(cx);
7657 for selection in selections {
7658 for row in selection.start.row..selection.end.row {
7659 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7660 new_selection_ranges.push(cursor..cursor);
7661 }
7662 new_selection_ranges.push(selection.end..selection.end);
7663 to_unfold.push(selection.start..selection.end);
7664 }
7665 }
7666 self.unfold_ranges(to_unfold, true, true, cx);
7667 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7668 s.select_ranges(new_selection_ranges);
7669 });
7670 }
7671
7672 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7673 self.add_selection(true, cx);
7674 }
7675
7676 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7677 self.add_selection(false, cx);
7678 }
7679
7680 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7681 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7682 let mut selections = self.selections.all::<Point>(cx);
7683 let text_layout_details = self.text_layout_details(cx);
7684 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7685 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7686 let range = oldest_selection.display_range(&display_map).sorted();
7687
7688 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7689 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7690 let positions = start_x.min(end_x)..start_x.max(end_x);
7691
7692 selections.clear();
7693 let mut stack = Vec::new();
7694 for row in range.start.row().0..=range.end.row().0 {
7695 if let Some(selection) = self.selections.build_columnar_selection(
7696 &display_map,
7697 DisplayRow(row),
7698 &positions,
7699 oldest_selection.reversed,
7700 &text_layout_details,
7701 ) {
7702 stack.push(selection.id);
7703 selections.push(selection);
7704 }
7705 }
7706
7707 if above {
7708 stack.reverse();
7709 }
7710
7711 AddSelectionsState { above, stack }
7712 });
7713
7714 let last_added_selection = *state.stack.last().unwrap();
7715 let mut new_selections = Vec::new();
7716 if above == state.above {
7717 let end_row = if above {
7718 DisplayRow(0)
7719 } else {
7720 display_map.max_point().row()
7721 };
7722
7723 'outer: for selection in selections {
7724 if selection.id == last_added_selection {
7725 let range = selection.display_range(&display_map).sorted();
7726 debug_assert_eq!(range.start.row(), range.end.row());
7727 let mut row = range.start.row();
7728 let positions =
7729 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
7730 px(start)..px(end)
7731 } else {
7732 let start_x =
7733 display_map.x_for_display_point(range.start, &text_layout_details);
7734 let end_x =
7735 display_map.x_for_display_point(range.end, &text_layout_details);
7736 start_x.min(end_x)..start_x.max(end_x)
7737 };
7738
7739 while row != end_row {
7740 if above {
7741 row.0 -= 1;
7742 } else {
7743 row.0 += 1;
7744 }
7745
7746 if let Some(new_selection) = self.selections.build_columnar_selection(
7747 &display_map,
7748 row,
7749 &positions,
7750 selection.reversed,
7751 &text_layout_details,
7752 ) {
7753 state.stack.push(new_selection.id);
7754 if above {
7755 new_selections.push(new_selection);
7756 new_selections.push(selection);
7757 } else {
7758 new_selections.push(selection);
7759 new_selections.push(new_selection);
7760 }
7761
7762 continue 'outer;
7763 }
7764 }
7765 }
7766
7767 new_selections.push(selection);
7768 }
7769 } else {
7770 new_selections = selections;
7771 new_selections.retain(|s| s.id != last_added_selection);
7772 state.stack.pop();
7773 }
7774
7775 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7776 s.select(new_selections);
7777 });
7778 if state.stack.len() > 1 {
7779 self.add_selections_state = Some(state);
7780 }
7781 }
7782
7783 pub fn select_next_match_internal(
7784 &mut self,
7785 display_map: &DisplaySnapshot,
7786 replace_newest: bool,
7787 autoscroll: Option<Autoscroll>,
7788 cx: &mut ViewContext<Self>,
7789 ) -> Result<()> {
7790 fn select_next_match_ranges(
7791 this: &mut Editor,
7792 range: Range<usize>,
7793 replace_newest: bool,
7794 auto_scroll: Option<Autoscroll>,
7795 cx: &mut ViewContext<Editor>,
7796 ) {
7797 this.unfold_ranges([range.clone()], false, true, cx);
7798 this.change_selections(auto_scroll, cx, |s| {
7799 if replace_newest {
7800 s.delete(s.newest_anchor().id);
7801 }
7802 s.insert_range(range.clone());
7803 });
7804 }
7805
7806 let buffer = &display_map.buffer_snapshot;
7807 let mut selections = self.selections.all::<usize>(cx);
7808 if let Some(mut select_next_state) = self.select_next_state.take() {
7809 let query = &select_next_state.query;
7810 if !select_next_state.done {
7811 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
7812 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
7813 let mut next_selected_range = None;
7814
7815 let bytes_after_last_selection =
7816 buffer.bytes_in_range(last_selection.end..buffer.len());
7817 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
7818 let query_matches = query
7819 .stream_find_iter(bytes_after_last_selection)
7820 .map(|result| (last_selection.end, result))
7821 .chain(
7822 query
7823 .stream_find_iter(bytes_before_first_selection)
7824 .map(|result| (0, result)),
7825 );
7826
7827 for (start_offset, query_match) in query_matches {
7828 let query_match = query_match.unwrap(); // can only fail due to I/O
7829 let offset_range =
7830 start_offset + query_match.start()..start_offset + query_match.end();
7831 let display_range = offset_range.start.to_display_point(&display_map)
7832 ..offset_range.end.to_display_point(&display_map);
7833
7834 if !select_next_state.wordwise
7835 || (!movement::is_inside_word(&display_map, display_range.start)
7836 && !movement::is_inside_word(&display_map, display_range.end))
7837 {
7838 // TODO: This is n^2, because we might check all the selections
7839 if !selections
7840 .iter()
7841 .any(|selection| selection.range().overlaps(&offset_range))
7842 {
7843 next_selected_range = Some(offset_range);
7844 break;
7845 }
7846 }
7847 }
7848
7849 if let Some(next_selected_range) = next_selected_range {
7850 select_next_match_ranges(
7851 self,
7852 next_selected_range,
7853 replace_newest,
7854 autoscroll,
7855 cx,
7856 );
7857 } else {
7858 select_next_state.done = true;
7859 }
7860 }
7861
7862 self.select_next_state = Some(select_next_state);
7863 } else {
7864 let mut only_carets = true;
7865 let mut same_text_selected = true;
7866 let mut selected_text = None;
7867
7868 let mut selections_iter = selections.iter().peekable();
7869 while let Some(selection) = selections_iter.next() {
7870 if selection.start != selection.end {
7871 only_carets = false;
7872 }
7873
7874 if same_text_selected {
7875 if selected_text.is_none() {
7876 selected_text =
7877 Some(buffer.text_for_range(selection.range()).collect::<String>());
7878 }
7879
7880 if let Some(next_selection) = selections_iter.peek() {
7881 if next_selection.range().len() == selection.range().len() {
7882 let next_selected_text = buffer
7883 .text_for_range(next_selection.range())
7884 .collect::<String>();
7885 if Some(next_selected_text) != selected_text {
7886 same_text_selected = false;
7887 selected_text = None;
7888 }
7889 } else {
7890 same_text_selected = false;
7891 selected_text = None;
7892 }
7893 }
7894 }
7895 }
7896
7897 if only_carets {
7898 for selection in &mut selections {
7899 let word_range = movement::surrounding_word(
7900 &display_map,
7901 selection.start.to_display_point(&display_map),
7902 );
7903 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
7904 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
7905 selection.goal = SelectionGoal::None;
7906 selection.reversed = false;
7907 select_next_match_ranges(
7908 self,
7909 selection.start..selection.end,
7910 replace_newest,
7911 autoscroll,
7912 cx,
7913 );
7914 }
7915
7916 if selections.len() == 1 {
7917 let selection = selections
7918 .last()
7919 .expect("ensured that there's only one selection");
7920 let query = buffer
7921 .text_for_range(selection.start..selection.end)
7922 .collect::<String>();
7923 let is_empty = query.is_empty();
7924 let select_state = SelectNextState {
7925 query: AhoCorasick::new(&[query])?,
7926 wordwise: true,
7927 done: is_empty,
7928 };
7929 self.select_next_state = Some(select_state);
7930 } else {
7931 self.select_next_state = None;
7932 }
7933 } else if let Some(selected_text) = selected_text {
7934 self.select_next_state = Some(SelectNextState {
7935 query: AhoCorasick::new(&[selected_text])?,
7936 wordwise: false,
7937 done: false,
7938 });
7939 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
7940 }
7941 }
7942 Ok(())
7943 }
7944
7945 pub fn select_all_matches(
7946 &mut self,
7947 _action: &SelectAllMatches,
7948 cx: &mut ViewContext<Self>,
7949 ) -> Result<()> {
7950 self.push_to_selection_history();
7951 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7952
7953 self.select_next_match_internal(&display_map, false, None, cx)?;
7954 let Some(select_next_state) = self.select_next_state.as_mut() else {
7955 return Ok(());
7956 };
7957 if select_next_state.done {
7958 return Ok(());
7959 }
7960
7961 let mut new_selections = self.selections.all::<usize>(cx);
7962
7963 let buffer = &display_map.buffer_snapshot;
7964 let query_matches = select_next_state
7965 .query
7966 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
7967
7968 for query_match in query_matches {
7969 let query_match = query_match.unwrap(); // can only fail due to I/O
7970 let offset_range = query_match.start()..query_match.end();
7971 let display_range = offset_range.start.to_display_point(&display_map)
7972 ..offset_range.end.to_display_point(&display_map);
7973
7974 if !select_next_state.wordwise
7975 || (!movement::is_inside_word(&display_map, display_range.start)
7976 && !movement::is_inside_word(&display_map, display_range.end))
7977 {
7978 self.selections.change_with(cx, |selections| {
7979 new_selections.push(Selection {
7980 id: selections.new_selection_id(),
7981 start: offset_range.start,
7982 end: offset_range.end,
7983 reversed: false,
7984 goal: SelectionGoal::None,
7985 });
7986 });
7987 }
7988 }
7989
7990 new_selections.sort_by_key(|selection| selection.start);
7991 let mut ix = 0;
7992 while ix + 1 < new_selections.len() {
7993 let current_selection = &new_selections[ix];
7994 let next_selection = &new_selections[ix + 1];
7995 if current_selection.range().overlaps(&next_selection.range()) {
7996 if current_selection.id < next_selection.id {
7997 new_selections.remove(ix + 1);
7998 } else {
7999 new_selections.remove(ix);
8000 }
8001 } else {
8002 ix += 1;
8003 }
8004 }
8005
8006 select_next_state.done = true;
8007 self.unfold_ranges(
8008 new_selections.iter().map(|selection| selection.range()),
8009 false,
8010 false,
8011 cx,
8012 );
8013 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8014 selections.select(new_selections)
8015 });
8016
8017 Ok(())
8018 }
8019
8020 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8021 self.push_to_selection_history();
8022 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8023 self.select_next_match_internal(
8024 &display_map,
8025 action.replace_newest,
8026 Some(Autoscroll::newest()),
8027 cx,
8028 )?;
8029 Ok(())
8030 }
8031
8032 pub fn select_previous(
8033 &mut self,
8034 action: &SelectPrevious,
8035 cx: &mut ViewContext<Self>,
8036 ) -> Result<()> {
8037 self.push_to_selection_history();
8038 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8039 let buffer = &display_map.buffer_snapshot;
8040 let mut selections = self.selections.all::<usize>(cx);
8041 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8042 let query = &select_prev_state.query;
8043 if !select_prev_state.done {
8044 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8045 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8046 let mut next_selected_range = None;
8047 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8048 let bytes_before_last_selection =
8049 buffer.reversed_bytes_in_range(0..last_selection.start);
8050 let bytes_after_first_selection =
8051 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8052 let query_matches = query
8053 .stream_find_iter(bytes_before_last_selection)
8054 .map(|result| (last_selection.start, result))
8055 .chain(
8056 query
8057 .stream_find_iter(bytes_after_first_selection)
8058 .map(|result| (buffer.len(), result)),
8059 );
8060 for (end_offset, query_match) in query_matches {
8061 let query_match = query_match.unwrap(); // can only fail due to I/O
8062 let offset_range =
8063 end_offset - query_match.end()..end_offset - query_match.start();
8064 let display_range = offset_range.start.to_display_point(&display_map)
8065 ..offset_range.end.to_display_point(&display_map);
8066
8067 if !select_prev_state.wordwise
8068 || (!movement::is_inside_word(&display_map, display_range.start)
8069 && !movement::is_inside_word(&display_map, display_range.end))
8070 {
8071 next_selected_range = Some(offset_range);
8072 break;
8073 }
8074 }
8075
8076 if let Some(next_selected_range) = next_selected_range {
8077 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8078 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8079 if action.replace_newest {
8080 s.delete(s.newest_anchor().id);
8081 }
8082 s.insert_range(next_selected_range);
8083 });
8084 } else {
8085 select_prev_state.done = true;
8086 }
8087 }
8088
8089 self.select_prev_state = Some(select_prev_state);
8090 } else {
8091 let mut only_carets = true;
8092 let mut same_text_selected = true;
8093 let mut selected_text = None;
8094
8095 let mut selections_iter = selections.iter().peekable();
8096 while let Some(selection) = selections_iter.next() {
8097 if selection.start != selection.end {
8098 only_carets = false;
8099 }
8100
8101 if same_text_selected {
8102 if selected_text.is_none() {
8103 selected_text =
8104 Some(buffer.text_for_range(selection.range()).collect::<String>());
8105 }
8106
8107 if let Some(next_selection) = selections_iter.peek() {
8108 if next_selection.range().len() == selection.range().len() {
8109 let next_selected_text = buffer
8110 .text_for_range(next_selection.range())
8111 .collect::<String>();
8112 if Some(next_selected_text) != selected_text {
8113 same_text_selected = false;
8114 selected_text = None;
8115 }
8116 } else {
8117 same_text_selected = false;
8118 selected_text = None;
8119 }
8120 }
8121 }
8122 }
8123
8124 if only_carets {
8125 for selection in &mut selections {
8126 let word_range = movement::surrounding_word(
8127 &display_map,
8128 selection.start.to_display_point(&display_map),
8129 );
8130 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8131 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8132 selection.goal = SelectionGoal::None;
8133 selection.reversed = false;
8134 }
8135 if selections.len() == 1 {
8136 let selection = selections
8137 .last()
8138 .expect("ensured that there's only one selection");
8139 let query = buffer
8140 .text_for_range(selection.start..selection.end)
8141 .collect::<String>();
8142 let is_empty = query.is_empty();
8143 let select_state = SelectNextState {
8144 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8145 wordwise: true,
8146 done: is_empty,
8147 };
8148 self.select_prev_state = Some(select_state);
8149 } else {
8150 self.select_prev_state = None;
8151 }
8152
8153 self.unfold_ranges(
8154 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8155 false,
8156 true,
8157 cx,
8158 );
8159 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8160 s.select(selections);
8161 });
8162 } else if let Some(selected_text) = selected_text {
8163 self.select_prev_state = Some(SelectNextState {
8164 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8165 wordwise: false,
8166 done: false,
8167 });
8168 self.select_previous(action, cx)?;
8169 }
8170 }
8171 Ok(())
8172 }
8173
8174 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8175 let text_layout_details = &self.text_layout_details(cx);
8176 self.transact(cx, |this, cx| {
8177 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8178 let mut edits = Vec::new();
8179 let mut selection_edit_ranges = Vec::new();
8180 let mut last_toggled_row = None;
8181 let snapshot = this.buffer.read(cx).read(cx);
8182 let empty_str: Arc<str> = Arc::default();
8183 let mut suffixes_inserted = Vec::new();
8184
8185 fn comment_prefix_range(
8186 snapshot: &MultiBufferSnapshot,
8187 row: MultiBufferRow,
8188 comment_prefix: &str,
8189 comment_prefix_whitespace: &str,
8190 ) -> Range<Point> {
8191 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8192
8193 let mut line_bytes = snapshot
8194 .bytes_in_range(start..snapshot.max_point())
8195 .flatten()
8196 .copied();
8197
8198 // If this line currently begins with the line comment prefix, then record
8199 // the range containing the prefix.
8200 if line_bytes
8201 .by_ref()
8202 .take(comment_prefix.len())
8203 .eq(comment_prefix.bytes())
8204 {
8205 // Include any whitespace that matches the comment prefix.
8206 let matching_whitespace_len = line_bytes
8207 .zip(comment_prefix_whitespace.bytes())
8208 .take_while(|(a, b)| a == b)
8209 .count() as u32;
8210 let end = Point::new(
8211 start.row,
8212 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8213 );
8214 start..end
8215 } else {
8216 start..start
8217 }
8218 }
8219
8220 fn comment_suffix_range(
8221 snapshot: &MultiBufferSnapshot,
8222 row: MultiBufferRow,
8223 comment_suffix: &str,
8224 comment_suffix_has_leading_space: bool,
8225 ) -> Range<Point> {
8226 let end = Point::new(row.0, snapshot.line_len(row));
8227 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8228
8229 let mut line_end_bytes = snapshot
8230 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8231 .flatten()
8232 .copied();
8233
8234 let leading_space_len = if suffix_start_column > 0
8235 && line_end_bytes.next() == Some(b' ')
8236 && comment_suffix_has_leading_space
8237 {
8238 1
8239 } else {
8240 0
8241 };
8242
8243 // If this line currently begins with the line comment prefix, then record
8244 // the range containing the prefix.
8245 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8246 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8247 start..end
8248 } else {
8249 end..end
8250 }
8251 }
8252
8253 // TODO: Handle selections that cross excerpts
8254 for selection in &mut selections {
8255 let start_column = snapshot
8256 .indent_size_for_line(MultiBufferRow(selection.start.row))
8257 .len;
8258 let language = if let Some(language) =
8259 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8260 {
8261 language
8262 } else {
8263 continue;
8264 };
8265
8266 selection_edit_ranges.clear();
8267
8268 // If multiple selections contain a given row, avoid processing that
8269 // row more than once.
8270 let mut start_row = MultiBufferRow(selection.start.row);
8271 if last_toggled_row == Some(start_row) {
8272 start_row = start_row.next_row();
8273 }
8274 let end_row =
8275 if selection.end.row > selection.start.row && selection.end.column == 0 {
8276 MultiBufferRow(selection.end.row - 1)
8277 } else {
8278 MultiBufferRow(selection.end.row)
8279 };
8280 last_toggled_row = Some(end_row);
8281
8282 if start_row > end_row {
8283 continue;
8284 }
8285
8286 // If the language has line comments, toggle those.
8287 let full_comment_prefixes = language.line_comment_prefixes();
8288 if !full_comment_prefixes.is_empty() {
8289 let first_prefix = full_comment_prefixes
8290 .first()
8291 .expect("prefixes is non-empty");
8292 let prefix_trimmed_lengths = full_comment_prefixes
8293 .iter()
8294 .map(|p| p.trim_end_matches(' ').len())
8295 .collect::<SmallVec<[usize; 4]>>();
8296
8297 let mut all_selection_lines_are_comments = true;
8298
8299 for row in start_row.0..=end_row.0 {
8300 let row = MultiBufferRow(row);
8301 if start_row < end_row && snapshot.is_line_blank(row) {
8302 continue;
8303 }
8304
8305 let prefix_range = full_comment_prefixes
8306 .iter()
8307 .zip(prefix_trimmed_lengths.iter().copied())
8308 .map(|(prefix, trimmed_prefix_len)| {
8309 comment_prefix_range(
8310 snapshot.deref(),
8311 row,
8312 &prefix[..trimmed_prefix_len],
8313 &prefix[trimmed_prefix_len..],
8314 )
8315 })
8316 .max_by_key(|range| range.end.column - range.start.column)
8317 .expect("prefixes is non-empty");
8318
8319 if prefix_range.is_empty() {
8320 all_selection_lines_are_comments = false;
8321 }
8322
8323 selection_edit_ranges.push(prefix_range);
8324 }
8325
8326 if all_selection_lines_are_comments {
8327 edits.extend(
8328 selection_edit_ranges
8329 .iter()
8330 .cloned()
8331 .map(|range| (range, empty_str.clone())),
8332 );
8333 } else {
8334 let min_column = selection_edit_ranges
8335 .iter()
8336 .map(|range| range.start.column)
8337 .min()
8338 .unwrap_or(0);
8339 edits.extend(selection_edit_ranges.iter().map(|range| {
8340 let position = Point::new(range.start.row, min_column);
8341 (position..position, first_prefix.clone())
8342 }));
8343 }
8344 } else if let Some((full_comment_prefix, comment_suffix)) =
8345 language.block_comment_delimiters()
8346 {
8347 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8348 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8349 let prefix_range = comment_prefix_range(
8350 snapshot.deref(),
8351 start_row,
8352 comment_prefix,
8353 comment_prefix_whitespace,
8354 );
8355 let suffix_range = comment_suffix_range(
8356 snapshot.deref(),
8357 end_row,
8358 comment_suffix.trim_start_matches(' '),
8359 comment_suffix.starts_with(' '),
8360 );
8361
8362 if prefix_range.is_empty() || suffix_range.is_empty() {
8363 edits.push((
8364 prefix_range.start..prefix_range.start,
8365 full_comment_prefix.clone(),
8366 ));
8367 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8368 suffixes_inserted.push((end_row, comment_suffix.len()));
8369 } else {
8370 edits.push((prefix_range, empty_str.clone()));
8371 edits.push((suffix_range, empty_str.clone()));
8372 }
8373 } else {
8374 continue;
8375 }
8376 }
8377
8378 drop(snapshot);
8379 this.buffer.update(cx, |buffer, cx| {
8380 buffer.edit(edits, None, cx);
8381 });
8382
8383 // Adjust selections so that they end before any comment suffixes that
8384 // were inserted.
8385 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8386 let mut selections = this.selections.all::<Point>(cx);
8387 let snapshot = this.buffer.read(cx).read(cx);
8388 for selection in &mut selections {
8389 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8390 match row.cmp(&MultiBufferRow(selection.end.row)) {
8391 Ordering::Less => {
8392 suffixes_inserted.next();
8393 continue;
8394 }
8395 Ordering::Greater => break,
8396 Ordering::Equal => {
8397 if selection.end.column == snapshot.line_len(row) {
8398 if selection.is_empty() {
8399 selection.start.column -= suffix_len as u32;
8400 }
8401 selection.end.column -= suffix_len as u32;
8402 }
8403 break;
8404 }
8405 }
8406 }
8407 }
8408
8409 drop(snapshot);
8410 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8411
8412 let selections = this.selections.all::<Point>(cx);
8413 let selections_on_single_row = selections.windows(2).all(|selections| {
8414 selections[0].start.row == selections[1].start.row
8415 && selections[0].end.row == selections[1].end.row
8416 && selections[0].start.row == selections[0].end.row
8417 });
8418 let selections_selecting = selections
8419 .iter()
8420 .any(|selection| selection.start != selection.end);
8421 let advance_downwards = action.advance_downwards
8422 && selections_on_single_row
8423 && !selections_selecting
8424 && !matches!(this.mode, EditorMode::SingleLine { .. });
8425
8426 if advance_downwards {
8427 let snapshot = this.buffer.read(cx).snapshot(cx);
8428
8429 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8430 s.move_cursors_with(|display_snapshot, display_point, _| {
8431 let mut point = display_point.to_point(display_snapshot);
8432 point.row += 1;
8433 point = snapshot.clip_point(point, Bias::Left);
8434 let display_point = point.to_display_point(display_snapshot);
8435 let goal = SelectionGoal::HorizontalPosition(
8436 display_snapshot
8437 .x_for_display_point(display_point, &text_layout_details)
8438 .into(),
8439 );
8440 (display_point, goal)
8441 })
8442 });
8443 }
8444 });
8445 }
8446
8447 pub fn select_enclosing_symbol(
8448 &mut self,
8449 _: &SelectEnclosingSymbol,
8450 cx: &mut ViewContext<Self>,
8451 ) {
8452 let buffer = self.buffer.read(cx).snapshot(cx);
8453 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8454
8455 fn update_selection(
8456 selection: &Selection<usize>,
8457 buffer_snap: &MultiBufferSnapshot,
8458 ) -> Option<Selection<usize>> {
8459 let cursor = selection.head();
8460 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8461 for symbol in symbols.iter().rev() {
8462 let start = symbol.range.start.to_offset(&buffer_snap);
8463 let end = symbol.range.end.to_offset(&buffer_snap);
8464 let new_range = start..end;
8465 if start < selection.start || end > selection.end {
8466 return Some(Selection {
8467 id: selection.id,
8468 start: new_range.start,
8469 end: new_range.end,
8470 goal: SelectionGoal::None,
8471 reversed: selection.reversed,
8472 });
8473 }
8474 }
8475 None
8476 }
8477
8478 let mut selected_larger_symbol = false;
8479 let new_selections = old_selections
8480 .iter()
8481 .map(|selection| match update_selection(selection, &buffer) {
8482 Some(new_selection) => {
8483 if new_selection.range() != selection.range() {
8484 selected_larger_symbol = true;
8485 }
8486 new_selection
8487 }
8488 None => selection.clone(),
8489 })
8490 .collect::<Vec<_>>();
8491
8492 if selected_larger_symbol {
8493 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8494 s.select(new_selections);
8495 });
8496 }
8497 }
8498
8499 pub fn select_larger_syntax_node(
8500 &mut self,
8501 _: &SelectLargerSyntaxNode,
8502 cx: &mut ViewContext<Self>,
8503 ) {
8504 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8505 let buffer = self.buffer.read(cx).snapshot(cx);
8506 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8507
8508 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8509 let mut selected_larger_node = false;
8510 let new_selections = old_selections
8511 .iter()
8512 .map(|selection| {
8513 let old_range = selection.start..selection.end;
8514 let mut new_range = old_range.clone();
8515 while let Some(containing_range) =
8516 buffer.range_for_syntax_ancestor(new_range.clone())
8517 {
8518 new_range = containing_range;
8519 if !display_map.intersects_fold(new_range.start)
8520 && !display_map.intersects_fold(new_range.end)
8521 {
8522 break;
8523 }
8524 }
8525
8526 selected_larger_node |= new_range != old_range;
8527 Selection {
8528 id: selection.id,
8529 start: new_range.start,
8530 end: new_range.end,
8531 goal: SelectionGoal::None,
8532 reversed: selection.reversed,
8533 }
8534 })
8535 .collect::<Vec<_>>();
8536
8537 if selected_larger_node {
8538 stack.push(old_selections);
8539 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8540 s.select(new_selections);
8541 });
8542 }
8543 self.select_larger_syntax_node_stack = stack;
8544 }
8545
8546 pub fn select_smaller_syntax_node(
8547 &mut self,
8548 _: &SelectSmallerSyntaxNode,
8549 cx: &mut ViewContext<Self>,
8550 ) {
8551 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8552 if let Some(selections) = stack.pop() {
8553 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8554 s.select(selections.to_vec());
8555 });
8556 }
8557 self.select_larger_syntax_node_stack = stack;
8558 }
8559
8560 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8561 if !EditorSettings::get_global(cx).gutter.runnables {
8562 self.clear_tasks();
8563 return Task::ready(());
8564 }
8565 let project = self.project.clone();
8566 cx.spawn(|this, mut cx| async move {
8567 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8568 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8569 }) else {
8570 return;
8571 };
8572
8573 let Some(project) = project else {
8574 return;
8575 };
8576
8577 let hide_runnables = project
8578 .update(&mut cx, |project, cx| {
8579 // Do not display any test indicators in non-dev server remote projects.
8580 project.is_remote() && project.ssh_connection_string(cx).is_none()
8581 })
8582 .unwrap_or(true);
8583 if hide_runnables {
8584 return;
8585 }
8586 let new_rows =
8587 cx.background_executor()
8588 .spawn({
8589 let snapshot = display_snapshot.clone();
8590 async move {
8591 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8592 }
8593 })
8594 .await;
8595 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8596
8597 this.update(&mut cx, |this, _| {
8598 this.clear_tasks();
8599 for (key, value) in rows {
8600 this.insert_tasks(key, value);
8601 }
8602 })
8603 .ok();
8604 })
8605 }
8606 fn fetch_runnable_ranges(
8607 snapshot: &DisplaySnapshot,
8608 range: Range<Anchor>,
8609 ) -> Vec<language::RunnableRange> {
8610 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8611 }
8612
8613 fn runnable_rows(
8614 project: Model<Project>,
8615 snapshot: DisplaySnapshot,
8616 runnable_ranges: Vec<RunnableRange>,
8617 mut cx: AsyncWindowContext,
8618 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8619 runnable_ranges
8620 .into_iter()
8621 .filter_map(|mut runnable| {
8622 let tasks = cx
8623 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8624 .ok()?;
8625 if tasks.is_empty() {
8626 return None;
8627 }
8628
8629 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8630
8631 let row = snapshot
8632 .buffer_snapshot
8633 .buffer_line_for_row(MultiBufferRow(point.row))?
8634 .1
8635 .start
8636 .row;
8637
8638 let context_range =
8639 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8640 Some((
8641 (runnable.buffer_id, row),
8642 RunnableTasks {
8643 templates: tasks,
8644 offset: MultiBufferOffset(runnable.run_range.start),
8645 context_range,
8646 column: point.column,
8647 extra_variables: runnable.extra_captures,
8648 },
8649 ))
8650 })
8651 .collect()
8652 }
8653
8654 fn templates_with_tags(
8655 project: &Model<Project>,
8656 runnable: &mut Runnable,
8657 cx: &WindowContext<'_>,
8658 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8659 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8660 let (worktree_id, file) = project
8661 .buffer_for_id(runnable.buffer, cx)
8662 .and_then(|buffer| buffer.read(cx).file())
8663 .map(|file| (WorktreeId::from_usize(file.worktree_id()), file.clone()))
8664 .unzip();
8665
8666 (project.task_inventory().clone(), worktree_id, file)
8667 });
8668
8669 let inventory = inventory.read(cx);
8670 let tags = mem::take(&mut runnable.tags);
8671 let mut tags: Vec<_> = tags
8672 .into_iter()
8673 .flat_map(|tag| {
8674 let tag = tag.0.clone();
8675 inventory
8676 .list_tasks(
8677 file.clone(),
8678 Some(runnable.language.clone()),
8679 worktree_id,
8680 cx,
8681 )
8682 .into_iter()
8683 .filter(move |(_, template)| {
8684 template.tags.iter().any(|source_tag| source_tag == &tag)
8685 })
8686 })
8687 .sorted_by_key(|(kind, _)| kind.to_owned())
8688 .collect();
8689 if let Some((leading_tag_source, _)) = tags.first() {
8690 // Strongest source wins; if we have worktree tag binding, prefer that to
8691 // global and language bindings;
8692 // if we have a global binding, prefer that to language binding.
8693 let first_mismatch = tags
8694 .iter()
8695 .position(|(tag_source, _)| tag_source != leading_tag_source);
8696 if let Some(index) = first_mismatch {
8697 tags.truncate(index);
8698 }
8699 }
8700
8701 tags
8702 }
8703
8704 pub fn move_to_enclosing_bracket(
8705 &mut self,
8706 _: &MoveToEnclosingBracket,
8707 cx: &mut ViewContext<Self>,
8708 ) {
8709 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8710 s.move_offsets_with(|snapshot, selection| {
8711 let Some(enclosing_bracket_ranges) =
8712 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
8713 else {
8714 return;
8715 };
8716
8717 let mut best_length = usize::MAX;
8718 let mut best_inside = false;
8719 let mut best_in_bracket_range = false;
8720 let mut best_destination = None;
8721 for (open, close) in enclosing_bracket_ranges {
8722 let close = close.to_inclusive();
8723 let length = close.end() - open.start;
8724 let inside = selection.start >= open.end && selection.end <= *close.start();
8725 let in_bracket_range = open.to_inclusive().contains(&selection.head())
8726 || close.contains(&selection.head());
8727
8728 // If best is next to a bracket and current isn't, skip
8729 if !in_bracket_range && best_in_bracket_range {
8730 continue;
8731 }
8732
8733 // Prefer smaller lengths unless best is inside and current isn't
8734 if length > best_length && (best_inside || !inside) {
8735 continue;
8736 }
8737
8738 best_length = length;
8739 best_inside = inside;
8740 best_in_bracket_range = in_bracket_range;
8741 best_destination = Some(
8742 if close.contains(&selection.start) && close.contains(&selection.end) {
8743 if inside {
8744 open.end
8745 } else {
8746 open.start
8747 }
8748 } else {
8749 if inside {
8750 *close.start()
8751 } else {
8752 *close.end()
8753 }
8754 },
8755 );
8756 }
8757
8758 if let Some(destination) = best_destination {
8759 selection.collapse_to(destination, SelectionGoal::None);
8760 }
8761 })
8762 });
8763 }
8764
8765 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
8766 self.end_selection(cx);
8767 self.selection_history.mode = SelectionHistoryMode::Undoing;
8768 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
8769 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8770 self.select_next_state = entry.select_next_state;
8771 self.select_prev_state = entry.select_prev_state;
8772 self.add_selections_state = entry.add_selections_state;
8773 self.request_autoscroll(Autoscroll::newest(), cx);
8774 }
8775 self.selection_history.mode = SelectionHistoryMode::Normal;
8776 }
8777
8778 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
8779 self.end_selection(cx);
8780 self.selection_history.mode = SelectionHistoryMode::Redoing;
8781 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
8782 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
8783 self.select_next_state = entry.select_next_state;
8784 self.select_prev_state = entry.select_prev_state;
8785 self.add_selections_state = entry.add_selections_state;
8786 self.request_autoscroll(Autoscroll::newest(), cx);
8787 }
8788 self.selection_history.mode = SelectionHistoryMode::Normal;
8789 }
8790
8791 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
8792 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
8793 }
8794
8795 pub fn expand_excerpts_down(
8796 &mut self,
8797 action: &ExpandExcerptsDown,
8798 cx: &mut ViewContext<Self>,
8799 ) {
8800 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
8801 }
8802
8803 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
8804 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
8805 }
8806
8807 pub fn expand_excerpts_for_direction(
8808 &mut self,
8809 lines: u32,
8810 direction: ExpandExcerptDirection,
8811 cx: &mut ViewContext<Self>,
8812 ) {
8813 let selections = self.selections.disjoint_anchors();
8814
8815 let lines = if lines == 0 {
8816 EditorSettings::get_global(cx).expand_excerpt_lines
8817 } else {
8818 lines
8819 };
8820
8821 self.buffer.update(cx, |buffer, cx| {
8822 buffer.expand_excerpts(
8823 selections
8824 .into_iter()
8825 .map(|selection| selection.head().excerpt_id)
8826 .dedup(),
8827 lines,
8828 direction,
8829 cx,
8830 )
8831 })
8832 }
8833
8834 pub fn expand_excerpt(
8835 &mut self,
8836 excerpt: ExcerptId,
8837 direction: ExpandExcerptDirection,
8838 cx: &mut ViewContext<Self>,
8839 ) {
8840 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
8841 self.buffer.update(cx, |buffer, cx| {
8842 buffer.expand_excerpts([excerpt], lines, direction, cx)
8843 })
8844 }
8845
8846 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
8847 self.go_to_diagnostic_impl(Direction::Next, cx)
8848 }
8849
8850 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
8851 self.go_to_diagnostic_impl(Direction::Prev, cx)
8852 }
8853
8854 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
8855 let buffer = self.buffer.read(cx).snapshot(cx);
8856 let selection = self.selections.newest::<usize>(cx);
8857
8858 // If there is an active Diagnostic Popover jump to its diagnostic instead.
8859 if direction == Direction::Next {
8860 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
8861 let (group_id, jump_to) = popover.activation_info();
8862 if self.activate_diagnostics(group_id, cx) {
8863 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8864 let mut new_selection = s.newest_anchor().clone();
8865 new_selection.collapse_to(jump_to, SelectionGoal::None);
8866 s.select_anchors(vec![new_selection.clone()]);
8867 });
8868 }
8869 return;
8870 }
8871 }
8872
8873 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
8874 active_diagnostics
8875 .primary_range
8876 .to_offset(&buffer)
8877 .to_inclusive()
8878 });
8879 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
8880 if active_primary_range.contains(&selection.head()) {
8881 *active_primary_range.start()
8882 } else {
8883 selection.head()
8884 }
8885 } else {
8886 selection.head()
8887 };
8888 let snapshot = self.snapshot(cx);
8889 loop {
8890 let diagnostics = if direction == Direction::Prev {
8891 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
8892 } else {
8893 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
8894 }
8895 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
8896 let group = diagnostics
8897 // relies on diagnostics_in_range to return diagnostics with the same starting range to
8898 // be sorted in a stable way
8899 // skip until we are at current active diagnostic, if it exists
8900 .skip_while(|entry| {
8901 (match direction {
8902 Direction::Prev => entry.range.start >= search_start,
8903 Direction::Next => entry.range.start <= search_start,
8904 }) && self
8905 .active_diagnostics
8906 .as_ref()
8907 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
8908 })
8909 .find_map(|entry| {
8910 if entry.diagnostic.is_primary
8911 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
8912 && !entry.range.is_empty()
8913 // if we match with the active diagnostic, skip it
8914 && Some(entry.diagnostic.group_id)
8915 != self.active_diagnostics.as_ref().map(|d| d.group_id)
8916 {
8917 Some((entry.range, entry.diagnostic.group_id))
8918 } else {
8919 None
8920 }
8921 });
8922
8923 if let Some((primary_range, group_id)) = group {
8924 if self.activate_diagnostics(group_id, cx) {
8925 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8926 s.select(vec![Selection {
8927 id: selection.id,
8928 start: primary_range.start,
8929 end: primary_range.start,
8930 reversed: false,
8931 goal: SelectionGoal::None,
8932 }]);
8933 });
8934 }
8935 break;
8936 } else {
8937 // Cycle around to the start of the buffer, potentially moving back to the start of
8938 // the currently active diagnostic.
8939 active_primary_range.take();
8940 if direction == Direction::Prev {
8941 if search_start == buffer.len() {
8942 break;
8943 } else {
8944 search_start = buffer.len();
8945 }
8946 } else if search_start == 0 {
8947 break;
8948 } else {
8949 search_start = 0;
8950 }
8951 }
8952 }
8953 }
8954
8955 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
8956 let snapshot = self
8957 .display_map
8958 .update(cx, |display_map, cx| display_map.snapshot(cx));
8959 let selection = self.selections.newest::<Point>(cx);
8960
8961 if !self.seek_in_direction(
8962 &snapshot,
8963 selection.head(),
8964 false,
8965 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8966 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
8967 ),
8968 cx,
8969 ) {
8970 let wrapped_point = Point::zero();
8971 self.seek_in_direction(
8972 &snapshot,
8973 wrapped_point,
8974 true,
8975 snapshot.buffer_snapshot.git_diff_hunks_in_range(
8976 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
8977 ),
8978 cx,
8979 );
8980 }
8981 }
8982
8983 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
8984 let snapshot = self
8985 .display_map
8986 .update(cx, |display_map, cx| display_map.snapshot(cx));
8987 let selection = self.selections.newest::<Point>(cx);
8988
8989 if !self.seek_in_direction(
8990 &snapshot,
8991 selection.head(),
8992 false,
8993 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
8994 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
8995 ),
8996 cx,
8997 ) {
8998 let wrapped_point = snapshot.buffer_snapshot.max_point();
8999 self.seek_in_direction(
9000 &snapshot,
9001 wrapped_point,
9002 true,
9003 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9004 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9005 ),
9006 cx,
9007 );
9008 }
9009 }
9010
9011 fn seek_in_direction(
9012 &mut self,
9013 snapshot: &DisplaySnapshot,
9014 initial_point: Point,
9015 is_wrapped: bool,
9016 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
9017 cx: &mut ViewContext<Editor>,
9018 ) -> bool {
9019 let display_point = initial_point.to_display_point(snapshot);
9020 let mut hunks = hunks
9021 .map(|hunk| diff_hunk_to_display(&hunk, &snapshot))
9022 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9023 .dedup();
9024
9025 if let Some(hunk) = hunks.next() {
9026 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9027 let row = hunk.start_display_row();
9028 let point = DisplayPoint::new(row, 0);
9029 s.select_display_ranges([point..point]);
9030 });
9031
9032 true
9033 } else {
9034 false
9035 }
9036 }
9037
9038 pub fn go_to_definition(
9039 &mut self,
9040 _: &GoToDefinition,
9041 cx: &mut ViewContext<Self>,
9042 ) -> Task<Result<Navigated>> {
9043 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9044 let references = self.find_all_references(&FindAllReferences, cx);
9045 cx.background_executor().spawn(async move {
9046 if definition.await? == Navigated::Yes {
9047 return Ok(Navigated::Yes);
9048 }
9049 if let Some(references) = references {
9050 if references.await? == Navigated::Yes {
9051 return Ok(Navigated::Yes);
9052 }
9053 }
9054
9055 Ok(Navigated::No)
9056 })
9057 }
9058
9059 pub fn go_to_declaration(
9060 &mut self,
9061 _: &GoToDeclaration,
9062 cx: &mut ViewContext<Self>,
9063 ) -> Task<Result<Navigated>> {
9064 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9065 }
9066
9067 pub fn go_to_declaration_split(
9068 &mut self,
9069 _: &GoToDeclaration,
9070 cx: &mut ViewContext<Self>,
9071 ) -> Task<Result<Navigated>> {
9072 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9073 }
9074
9075 pub fn go_to_implementation(
9076 &mut self,
9077 _: &GoToImplementation,
9078 cx: &mut ViewContext<Self>,
9079 ) -> Task<Result<Navigated>> {
9080 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9081 }
9082
9083 pub fn go_to_implementation_split(
9084 &mut self,
9085 _: &GoToImplementationSplit,
9086 cx: &mut ViewContext<Self>,
9087 ) -> Task<Result<Navigated>> {
9088 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9089 }
9090
9091 pub fn go_to_type_definition(
9092 &mut self,
9093 _: &GoToTypeDefinition,
9094 cx: &mut ViewContext<Self>,
9095 ) -> Task<Result<Navigated>> {
9096 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9097 }
9098
9099 pub fn go_to_definition_split(
9100 &mut self,
9101 _: &GoToDefinitionSplit,
9102 cx: &mut ViewContext<Self>,
9103 ) -> Task<Result<Navigated>> {
9104 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9105 }
9106
9107 pub fn go_to_type_definition_split(
9108 &mut self,
9109 _: &GoToTypeDefinitionSplit,
9110 cx: &mut ViewContext<Self>,
9111 ) -> Task<Result<Navigated>> {
9112 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9113 }
9114
9115 fn go_to_definition_of_kind(
9116 &mut self,
9117 kind: GotoDefinitionKind,
9118 split: bool,
9119 cx: &mut ViewContext<Self>,
9120 ) -> Task<Result<Navigated>> {
9121 let Some(workspace) = self.workspace() else {
9122 return Task::ready(Ok(Navigated::No));
9123 };
9124 let buffer = self.buffer.read(cx);
9125 let head = self.selections.newest::<usize>(cx).head();
9126 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9127 text_anchor
9128 } else {
9129 return Task::ready(Ok(Navigated::No));
9130 };
9131
9132 let project = workspace.read(cx).project().clone();
9133 let definitions = project.update(cx, |project, cx| match kind {
9134 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9135 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9136 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9137 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9138 });
9139
9140 cx.spawn(|editor, mut cx| async move {
9141 let definitions = definitions.await?;
9142 let navigated = editor
9143 .update(&mut cx, |editor, cx| {
9144 editor.navigate_to_hover_links(
9145 Some(kind),
9146 definitions
9147 .into_iter()
9148 .filter(|location| {
9149 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9150 })
9151 .map(HoverLink::Text)
9152 .collect::<Vec<_>>(),
9153 split,
9154 cx,
9155 )
9156 })?
9157 .await?;
9158 anyhow::Ok(navigated)
9159 })
9160 }
9161
9162 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9163 let position = self.selections.newest_anchor().head();
9164 let Some((buffer, buffer_position)) =
9165 self.buffer.read(cx).text_anchor_for_position(position, cx)
9166 else {
9167 return;
9168 };
9169
9170 cx.spawn(|editor, mut cx| async move {
9171 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9172 editor.update(&mut cx, |_, cx| {
9173 cx.open_url(&url);
9174 })
9175 } else {
9176 Ok(())
9177 }
9178 })
9179 .detach();
9180 }
9181
9182 pub(crate) fn navigate_to_hover_links(
9183 &mut self,
9184 kind: Option<GotoDefinitionKind>,
9185 mut definitions: Vec<HoverLink>,
9186 split: bool,
9187 cx: &mut ViewContext<Editor>,
9188 ) -> Task<Result<Navigated>> {
9189 // If there is one definition, just open it directly
9190 if definitions.len() == 1 {
9191 let definition = definitions.pop().unwrap();
9192 let target_task = match definition {
9193 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9194 HoverLink::InlayHint(lsp_location, server_id) => {
9195 self.compute_target_location(lsp_location, server_id, cx)
9196 }
9197 HoverLink::Url(url) => {
9198 cx.open_url(&url);
9199 Task::ready(Ok(None))
9200 }
9201 };
9202 cx.spawn(|editor, mut cx| async move {
9203 let target = target_task.await.context("target resolution task")?;
9204 let Some(target) = target else {
9205 return Ok(Navigated::No);
9206 };
9207 editor.update(&mut cx, |editor, cx| {
9208 let Some(workspace) = editor.workspace() else {
9209 return Navigated::No;
9210 };
9211 let pane = workspace.read(cx).active_pane().clone();
9212
9213 let range = target.range.to_offset(target.buffer.read(cx));
9214 let range = editor.range_for_match(&range);
9215
9216 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9217 let buffer = target.buffer.read(cx);
9218 let range = check_multiline_range(buffer, range);
9219 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9220 s.select_ranges([range]);
9221 });
9222 } else {
9223 cx.window_context().defer(move |cx| {
9224 let target_editor: View<Self> =
9225 workspace.update(cx, |workspace, cx| {
9226 let pane = if split {
9227 workspace.adjacent_pane(cx)
9228 } else {
9229 workspace.active_pane().clone()
9230 };
9231
9232 workspace.open_project_item(
9233 pane,
9234 target.buffer.clone(),
9235 true,
9236 true,
9237 cx,
9238 )
9239 });
9240 target_editor.update(cx, |target_editor, cx| {
9241 // When selecting a definition in a different buffer, disable the nav history
9242 // to avoid creating a history entry at the previous cursor location.
9243 pane.update(cx, |pane, _| pane.disable_history());
9244 let buffer = target.buffer.read(cx);
9245 let range = check_multiline_range(buffer, range);
9246 target_editor.change_selections(
9247 Some(Autoscroll::focused()),
9248 cx,
9249 |s| {
9250 s.select_ranges([range]);
9251 },
9252 );
9253 pane.update(cx, |pane, _| pane.enable_history());
9254 });
9255 });
9256 }
9257 Navigated::Yes
9258 })
9259 })
9260 } else if !definitions.is_empty() {
9261 let replica_id = self.replica_id(cx);
9262 cx.spawn(|editor, mut cx| async move {
9263 let (title, location_tasks, workspace) = editor
9264 .update(&mut cx, |editor, cx| {
9265 let tab_kind = match kind {
9266 Some(GotoDefinitionKind::Implementation) => "Implementations",
9267 _ => "Definitions",
9268 };
9269 let title = definitions
9270 .iter()
9271 .find_map(|definition| match definition {
9272 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9273 let buffer = origin.buffer.read(cx);
9274 format!(
9275 "{} for {}",
9276 tab_kind,
9277 buffer
9278 .text_for_range(origin.range.clone())
9279 .collect::<String>()
9280 )
9281 }),
9282 HoverLink::InlayHint(_, _) => None,
9283 HoverLink::Url(_) => None,
9284 })
9285 .unwrap_or(tab_kind.to_string());
9286 let location_tasks = definitions
9287 .into_iter()
9288 .map(|definition| match definition {
9289 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9290 HoverLink::InlayHint(lsp_location, server_id) => {
9291 editor.compute_target_location(lsp_location, server_id, cx)
9292 }
9293 HoverLink::Url(_) => Task::ready(Ok(None)),
9294 })
9295 .collect::<Vec<_>>();
9296 (title, location_tasks, editor.workspace().clone())
9297 })
9298 .context("location tasks preparation")?;
9299
9300 let locations = futures::future::join_all(location_tasks)
9301 .await
9302 .into_iter()
9303 .filter_map(|location| location.transpose())
9304 .collect::<Result<_>>()
9305 .context("location tasks")?;
9306
9307 let Some(workspace) = workspace else {
9308 return Ok(Navigated::No);
9309 };
9310 let opened = workspace
9311 .update(&mut cx, |workspace, cx| {
9312 Self::open_locations_in_multibuffer(
9313 workspace, locations, replica_id, title, split, cx,
9314 )
9315 })
9316 .ok();
9317
9318 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9319 })
9320 } else {
9321 Task::ready(Ok(Navigated::No))
9322 }
9323 }
9324
9325 fn compute_target_location(
9326 &self,
9327 lsp_location: lsp::Location,
9328 server_id: LanguageServerId,
9329 cx: &mut ViewContext<Editor>,
9330 ) -> Task<anyhow::Result<Option<Location>>> {
9331 let Some(project) = self.project.clone() else {
9332 return Task::Ready(Some(Ok(None)));
9333 };
9334
9335 cx.spawn(move |editor, mut cx| async move {
9336 let location_task = editor.update(&mut cx, |editor, cx| {
9337 project.update(cx, |project, cx| {
9338 let language_server_name =
9339 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9340 project
9341 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9342 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9343 });
9344 language_server_name.map(|language_server_name| {
9345 project.open_local_buffer_via_lsp(
9346 lsp_location.uri.clone(),
9347 server_id,
9348 language_server_name,
9349 cx,
9350 )
9351 })
9352 })
9353 })?;
9354 let location = match location_task {
9355 Some(task) => Some({
9356 let target_buffer_handle = task.await.context("open local buffer")?;
9357 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9358 let target_start = target_buffer
9359 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9360 let target_end = target_buffer
9361 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9362 target_buffer.anchor_after(target_start)
9363 ..target_buffer.anchor_before(target_end)
9364 })?;
9365 Location {
9366 buffer: target_buffer_handle,
9367 range,
9368 }
9369 }),
9370 None => None,
9371 };
9372 Ok(location)
9373 })
9374 }
9375
9376 pub fn find_all_references(
9377 &mut self,
9378 _: &FindAllReferences,
9379 cx: &mut ViewContext<Self>,
9380 ) -> Option<Task<Result<Navigated>>> {
9381 let multi_buffer = self.buffer.read(cx);
9382 let selection = self.selections.newest::<usize>(cx);
9383 let head = selection.head();
9384
9385 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9386 let head_anchor = multi_buffer_snapshot.anchor_at(
9387 head,
9388 if head < selection.tail() {
9389 Bias::Right
9390 } else {
9391 Bias::Left
9392 },
9393 );
9394
9395 match self
9396 .find_all_references_task_sources
9397 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9398 {
9399 Ok(_) => {
9400 log::info!(
9401 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9402 );
9403 return None;
9404 }
9405 Err(i) => {
9406 self.find_all_references_task_sources.insert(i, head_anchor);
9407 }
9408 }
9409
9410 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9411 let replica_id = self.replica_id(cx);
9412 let workspace = self.workspace()?;
9413 let project = workspace.read(cx).project().clone();
9414 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9415 Some(cx.spawn(|editor, mut cx| async move {
9416 let _cleanup = defer({
9417 let mut cx = cx.clone();
9418 move || {
9419 let _ = editor.update(&mut cx, |editor, _| {
9420 if let Ok(i) =
9421 editor
9422 .find_all_references_task_sources
9423 .binary_search_by(|anchor| {
9424 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9425 })
9426 {
9427 editor.find_all_references_task_sources.remove(i);
9428 }
9429 });
9430 }
9431 });
9432
9433 let locations = references.await?;
9434 if locations.is_empty() {
9435 return anyhow::Ok(Navigated::No);
9436 }
9437
9438 workspace.update(&mut cx, |workspace, cx| {
9439 let title = locations
9440 .first()
9441 .as_ref()
9442 .map(|location| {
9443 let buffer = location.buffer.read(cx);
9444 format!(
9445 "References to `{}`",
9446 buffer
9447 .text_for_range(location.range.clone())
9448 .collect::<String>()
9449 )
9450 })
9451 .unwrap();
9452 Self::open_locations_in_multibuffer(
9453 workspace, locations, replica_id, title, false, cx,
9454 );
9455 Navigated::Yes
9456 })
9457 }))
9458 }
9459
9460 /// Opens a multibuffer with the given project locations in it
9461 pub fn open_locations_in_multibuffer(
9462 workspace: &mut Workspace,
9463 mut locations: Vec<Location>,
9464 replica_id: ReplicaId,
9465 title: String,
9466 split: bool,
9467 cx: &mut ViewContext<Workspace>,
9468 ) {
9469 // If there are multiple definitions, open them in a multibuffer
9470 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9471 let mut locations = locations.into_iter().peekable();
9472 let mut ranges_to_highlight = Vec::new();
9473 let capability = workspace.project().read(cx).capability();
9474
9475 let excerpt_buffer = cx.new_model(|cx| {
9476 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9477 while let Some(location) = locations.next() {
9478 let buffer = location.buffer.read(cx);
9479 let mut ranges_for_buffer = Vec::new();
9480 let range = location.range.to_offset(buffer);
9481 ranges_for_buffer.push(range.clone());
9482
9483 while let Some(next_location) = locations.peek() {
9484 if next_location.buffer == location.buffer {
9485 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9486 locations.next();
9487 } else {
9488 break;
9489 }
9490 }
9491
9492 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9493 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9494 location.buffer.clone(),
9495 ranges_for_buffer,
9496 DEFAULT_MULTIBUFFER_CONTEXT,
9497 cx,
9498 ))
9499 }
9500
9501 multibuffer.with_title(title)
9502 });
9503
9504 let editor = cx.new_view(|cx| {
9505 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9506 });
9507 editor.update(cx, |editor, cx| {
9508 if let Some(first_range) = ranges_to_highlight.first() {
9509 editor.change_selections(None, cx, |selections| {
9510 selections.clear_disjoint();
9511 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9512 });
9513 }
9514 editor.highlight_background::<Self>(
9515 &ranges_to_highlight,
9516 |theme| theme.editor_highlighted_line_background,
9517 cx,
9518 );
9519 });
9520
9521 let item = Box::new(editor);
9522 let item_id = item.item_id();
9523
9524 if split {
9525 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9526 } else {
9527 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9528 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9529 pane.close_current_preview_item(cx)
9530 } else {
9531 None
9532 }
9533 });
9534 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9535 }
9536 workspace.active_pane().update(cx, |pane, cx| {
9537 pane.set_preview_item_id(Some(item_id), cx);
9538 });
9539 }
9540
9541 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9542 use language::ToOffset as _;
9543
9544 let project = self.project.clone()?;
9545 let selection = self.selections.newest_anchor().clone();
9546 let (cursor_buffer, cursor_buffer_position) = self
9547 .buffer
9548 .read(cx)
9549 .text_anchor_for_position(selection.head(), cx)?;
9550 let (tail_buffer, cursor_buffer_position_end) = self
9551 .buffer
9552 .read(cx)
9553 .text_anchor_for_position(selection.tail(), cx)?;
9554 if tail_buffer != cursor_buffer {
9555 return None;
9556 }
9557
9558 let snapshot = cursor_buffer.read(cx).snapshot();
9559 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9560 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9561 let prepare_rename = project.update(cx, |project, cx| {
9562 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9563 });
9564 drop(snapshot);
9565
9566 Some(cx.spawn(|this, mut cx| async move {
9567 let rename_range = if let Some(range) = prepare_rename.await? {
9568 Some(range)
9569 } else {
9570 this.update(&mut cx, |this, cx| {
9571 let buffer = this.buffer.read(cx).snapshot(cx);
9572 let mut buffer_highlights = this
9573 .document_highlights_for_position(selection.head(), &buffer)
9574 .filter(|highlight| {
9575 highlight.start.excerpt_id == selection.head().excerpt_id
9576 && highlight.end.excerpt_id == selection.head().excerpt_id
9577 });
9578 buffer_highlights
9579 .next()
9580 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9581 })?
9582 };
9583 if let Some(rename_range) = rename_range {
9584 this.update(&mut cx, |this, cx| {
9585 let snapshot = cursor_buffer.read(cx).snapshot();
9586 let rename_buffer_range = rename_range.to_offset(&snapshot);
9587 let cursor_offset_in_rename_range =
9588 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9589 let cursor_offset_in_rename_range_end =
9590 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9591
9592 this.take_rename(false, cx);
9593 let buffer = this.buffer.read(cx).read(cx);
9594 let cursor_offset = selection.head().to_offset(&buffer);
9595 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9596 let rename_end = rename_start + rename_buffer_range.len();
9597 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9598 let mut old_highlight_id = None;
9599 let old_name: Arc<str> = buffer
9600 .chunks(rename_start..rename_end, true)
9601 .map(|chunk| {
9602 if old_highlight_id.is_none() {
9603 old_highlight_id = chunk.syntax_highlight_id;
9604 }
9605 chunk.text
9606 })
9607 .collect::<String>()
9608 .into();
9609
9610 drop(buffer);
9611
9612 // Position the selection in the rename editor so that it matches the current selection.
9613 this.show_local_selections = false;
9614 let rename_editor = cx.new_view(|cx| {
9615 let mut editor = Editor::single_line(cx);
9616 editor.buffer.update(cx, |buffer, cx| {
9617 buffer.edit([(0..0, old_name.clone())], None, cx)
9618 });
9619 let rename_selection_range = match cursor_offset_in_rename_range
9620 .cmp(&cursor_offset_in_rename_range_end)
9621 {
9622 Ordering::Equal => {
9623 editor.select_all(&SelectAll, cx);
9624 return editor;
9625 }
9626 Ordering::Less => {
9627 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9628 }
9629 Ordering::Greater => {
9630 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9631 }
9632 };
9633 if rename_selection_range.end > old_name.len() {
9634 editor.select_all(&SelectAll, cx);
9635 } else {
9636 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9637 s.select_ranges([rename_selection_range]);
9638 });
9639 }
9640 editor
9641 });
9642 cx.subscribe(&rename_editor, |_, _, e, cx| match e {
9643 EditorEvent::Focused => cx.emit(EditorEvent::FocusedIn),
9644 _ => {}
9645 })
9646 .detach();
9647
9648 let write_highlights =
9649 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
9650 let read_highlights =
9651 this.clear_background_highlights::<DocumentHighlightRead>(cx);
9652 let ranges = write_highlights
9653 .iter()
9654 .flat_map(|(_, ranges)| ranges.iter())
9655 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
9656 .cloned()
9657 .collect();
9658
9659 this.highlight_text::<Rename>(
9660 ranges,
9661 HighlightStyle {
9662 fade_out: Some(0.6),
9663 ..Default::default()
9664 },
9665 cx,
9666 );
9667 let rename_focus_handle = rename_editor.focus_handle(cx);
9668 cx.focus(&rename_focus_handle);
9669 let block_id = this.insert_blocks(
9670 [BlockProperties {
9671 style: BlockStyle::Flex,
9672 position: range.start,
9673 height: 1,
9674 render: Box::new({
9675 let rename_editor = rename_editor.clone();
9676 move |cx: &mut BlockContext| {
9677 let mut text_style = cx.editor_style.text.clone();
9678 if let Some(highlight_style) = old_highlight_id
9679 .and_then(|h| h.style(&cx.editor_style.syntax))
9680 {
9681 text_style = text_style.highlight(highlight_style);
9682 }
9683 div()
9684 .pl(cx.anchor_x)
9685 .child(EditorElement::new(
9686 &rename_editor,
9687 EditorStyle {
9688 background: cx.theme().system().transparent,
9689 local_player: cx.editor_style.local_player,
9690 text: text_style,
9691 scrollbar_width: cx.editor_style.scrollbar_width,
9692 syntax: cx.editor_style.syntax.clone(),
9693 status: cx.editor_style.status.clone(),
9694 inlay_hints_style: HighlightStyle {
9695 color: Some(cx.theme().status().hint),
9696 font_weight: Some(FontWeight::BOLD),
9697 ..HighlightStyle::default()
9698 },
9699 suggestions_style: HighlightStyle {
9700 color: Some(cx.theme().status().predictive),
9701 ..HighlightStyle::default()
9702 },
9703 ..EditorStyle::default()
9704 },
9705 ))
9706 .into_any_element()
9707 }
9708 }),
9709 disposition: BlockDisposition::Below,
9710 priority: 0,
9711 }],
9712 Some(Autoscroll::fit()),
9713 cx,
9714 )[0];
9715 this.pending_rename = Some(RenameState {
9716 range,
9717 old_name,
9718 editor: rename_editor,
9719 block_id,
9720 });
9721 })?;
9722 }
9723
9724 Ok(())
9725 }))
9726 }
9727
9728 pub fn confirm_rename(
9729 &mut self,
9730 _: &ConfirmRename,
9731 cx: &mut ViewContext<Self>,
9732 ) -> Option<Task<Result<()>>> {
9733 let rename = self.take_rename(false, cx)?;
9734 let workspace = self.workspace()?;
9735 let (start_buffer, start) = self
9736 .buffer
9737 .read(cx)
9738 .text_anchor_for_position(rename.range.start, cx)?;
9739 let (end_buffer, end) = self
9740 .buffer
9741 .read(cx)
9742 .text_anchor_for_position(rename.range.end, cx)?;
9743 if start_buffer != end_buffer {
9744 return None;
9745 }
9746
9747 let buffer = start_buffer;
9748 let range = start..end;
9749 let old_name = rename.old_name;
9750 let new_name = rename.editor.read(cx).text(cx);
9751
9752 let rename = workspace
9753 .read(cx)
9754 .project()
9755 .clone()
9756 .update(cx, |project, cx| {
9757 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
9758 });
9759 let workspace = workspace.downgrade();
9760
9761 Some(cx.spawn(|editor, mut cx| async move {
9762 let project_transaction = rename.await?;
9763 Self::open_project_transaction(
9764 &editor,
9765 workspace,
9766 project_transaction,
9767 format!("Rename: {} → {}", old_name, new_name),
9768 cx.clone(),
9769 )
9770 .await?;
9771
9772 editor.update(&mut cx, |editor, cx| {
9773 editor.refresh_document_highlights(cx);
9774 })?;
9775 Ok(())
9776 }))
9777 }
9778
9779 fn take_rename(
9780 &mut self,
9781 moving_cursor: bool,
9782 cx: &mut ViewContext<Self>,
9783 ) -> Option<RenameState> {
9784 let rename = self.pending_rename.take()?;
9785 if rename.editor.focus_handle(cx).is_focused(cx) {
9786 cx.focus(&self.focus_handle);
9787 }
9788
9789 self.remove_blocks(
9790 [rename.block_id].into_iter().collect(),
9791 Some(Autoscroll::fit()),
9792 cx,
9793 );
9794 self.clear_highlights::<Rename>(cx);
9795 self.show_local_selections = true;
9796
9797 if moving_cursor {
9798 let rename_editor = rename.editor.read(cx);
9799 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
9800
9801 // Update the selection to match the position of the selection inside
9802 // the rename editor.
9803 let snapshot = self.buffer.read(cx).read(cx);
9804 let rename_range = rename.range.to_offset(&snapshot);
9805 let cursor_in_editor = snapshot
9806 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
9807 .min(rename_range.end);
9808 drop(snapshot);
9809
9810 self.change_selections(None, cx, |s| {
9811 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
9812 });
9813 } else {
9814 self.refresh_document_highlights(cx);
9815 }
9816
9817 Some(rename)
9818 }
9819
9820 pub fn pending_rename(&self) -> Option<&RenameState> {
9821 self.pending_rename.as_ref()
9822 }
9823
9824 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9825 let project = match &self.project {
9826 Some(project) => project.clone(),
9827 None => return None,
9828 };
9829
9830 Some(self.perform_format(project, FormatTrigger::Manual, cx))
9831 }
9832
9833 fn perform_format(
9834 &mut self,
9835 project: Model<Project>,
9836 trigger: FormatTrigger,
9837 cx: &mut ViewContext<Self>,
9838 ) -> Task<Result<()>> {
9839 let buffer = self.buffer().clone();
9840 let mut buffers = buffer.read(cx).all_buffers();
9841 if trigger == FormatTrigger::Save {
9842 buffers.retain(|buffer| buffer.read(cx).is_dirty());
9843 }
9844
9845 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
9846 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
9847
9848 cx.spawn(|_, mut cx| async move {
9849 let transaction = futures::select_biased! {
9850 () = timeout => {
9851 log::warn!("timed out waiting for formatting");
9852 None
9853 }
9854 transaction = format.log_err().fuse() => transaction,
9855 };
9856
9857 buffer
9858 .update(&mut cx, |buffer, cx| {
9859 if let Some(transaction) = transaction {
9860 if !buffer.is_singleton() {
9861 buffer.push_transaction(&transaction.0, cx);
9862 }
9863 }
9864
9865 cx.notify();
9866 })
9867 .ok();
9868
9869 Ok(())
9870 })
9871 }
9872
9873 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
9874 if let Some(project) = self.project.clone() {
9875 self.buffer.update(cx, |multi_buffer, cx| {
9876 project.update(cx, |project, cx| {
9877 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
9878 });
9879 })
9880 }
9881 }
9882
9883 fn cancel_language_server_work(
9884 &mut self,
9885 _: &CancelLanguageServerWork,
9886 cx: &mut ViewContext<Self>,
9887 ) {
9888 if let Some(project) = self.project.clone() {
9889 self.buffer.update(cx, |multi_buffer, cx| {
9890 project.update(cx, |project, cx| {
9891 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
9892 });
9893 })
9894 }
9895 }
9896
9897 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
9898 cx.show_character_palette();
9899 }
9900
9901 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
9902 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
9903 let buffer = self.buffer.read(cx).snapshot(cx);
9904 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
9905 let is_valid = buffer
9906 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
9907 .any(|entry| {
9908 entry.diagnostic.is_primary
9909 && !entry.range.is_empty()
9910 && entry.range.start == primary_range_start
9911 && entry.diagnostic.message == active_diagnostics.primary_message
9912 });
9913
9914 if is_valid != active_diagnostics.is_valid {
9915 active_diagnostics.is_valid = is_valid;
9916 let mut new_styles = HashMap::default();
9917 for (block_id, diagnostic) in &active_diagnostics.blocks {
9918 new_styles.insert(
9919 *block_id,
9920 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
9921 );
9922 }
9923 self.display_map.update(cx, |display_map, _cx| {
9924 display_map.replace_blocks(new_styles)
9925 });
9926 }
9927 }
9928 }
9929
9930 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
9931 self.dismiss_diagnostics(cx);
9932 let snapshot = self.snapshot(cx);
9933 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
9934 let buffer = self.buffer.read(cx).snapshot(cx);
9935
9936 let mut primary_range = None;
9937 let mut primary_message = None;
9938 let mut group_end = Point::zero();
9939 let diagnostic_group = buffer
9940 .diagnostic_group::<MultiBufferPoint>(group_id)
9941 .filter_map(|entry| {
9942 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
9943 && (entry.range.start.row == entry.range.end.row
9944 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
9945 {
9946 return None;
9947 }
9948 if entry.range.end > group_end {
9949 group_end = entry.range.end;
9950 }
9951 if entry.diagnostic.is_primary {
9952 primary_range = Some(entry.range.clone());
9953 primary_message = Some(entry.diagnostic.message.clone());
9954 }
9955 Some(entry)
9956 })
9957 .collect::<Vec<_>>();
9958 let primary_range = primary_range?;
9959 let primary_message = primary_message?;
9960 let primary_range =
9961 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
9962
9963 let blocks = display_map
9964 .insert_blocks(
9965 diagnostic_group.iter().map(|entry| {
9966 let diagnostic = entry.diagnostic.clone();
9967 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
9968 BlockProperties {
9969 style: BlockStyle::Fixed,
9970 position: buffer.anchor_after(entry.range.start),
9971 height: message_height,
9972 render: diagnostic_block_renderer(diagnostic, None, true, true),
9973 disposition: BlockDisposition::Below,
9974 priority: 0,
9975 }
9976 }),
9977 cx,
9978 )
9979 .into_iter()
9980 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
9981 .collect();
9982
9983 Some(ActiveDiagnosticGroup {
9984 primary_range,
9985 primary_message,
9986 group_id,
9987 blocks,
9988 is_valid: true,
9989 })
9990 });
9991 self.active_diagnostics.is_some()
9992 }
9993
9994 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
9995 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
9996 self.display_map.update(cx, |display_map, cx| {
9997 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
9998 });
9999 cx.notify();
10000 }
10001 }
10002
10003 pub fn set_selections_from_remote(
10004 &mut self,
10005 selections: Vec<Selection<Anchor>>,
10006 pending_selection: Option<Selection<Anchor>>,
10007 cx: &mut ViewContext<Self>,
10008 ) {
10009 let old_cursor_position = self.selections.newest_anchor().head();
10010 self.selections.change_with(cx, |s| {
10011 s.select_anchors(selections);
10012 if let Some(pending_selection) = pending_selection {
10013 s.set_pending(pending_selection, SelectMode::Character);
10014 } else {
10015 s.clear_pending();
10016 }
10017 });
10018 self.selections_did_change(false, &old_cursor_position, true, cx);
10019 }
10020
10021 fn push_to_selection_history(&mut self) {
10022 self.selection_history.push(SelectionHistoryEntry {
10023 selections: self.selections.disjoint_anchors(),
10024 select_next_state: self.select_next_state.clone(),
10025 select_prev_state: self.select_prev_state.clone(),
10026 add_selections_state: self.add_selections_state.clone(),
10027 });
10028 }
10029
10030 pub fn transact(
10031 &mut self,
10032 cx: &mut ViewContext<Self>,
10033 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10034 ) -> Option<TransactionId> {
10035 self.start_transaction_at(Instant::now(), cx);
10036 update(self, cx);
10037 self.end_transaction_at(Instant::now(), cx)
10038 }
10039
10040 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10041 self.end_selection(cx);
10042 if let Some(tx_id) = self
10043 .buffer
10044 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10045 {
10046 self.selection_history
10047 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10048 cx.emit(EditorEvent::TransactionBegun {
10049 transaction_id: tx_id,
10050 })
10051 }
10052 }
10053
10054 fn end_transaction_at(
10055 &mut self,
10056 now: Instant,
10057 cx: &mut ViewContext<Self>,
10058 ) -> Option<TransactionId> {
10059 if let Some(transaction_id) = self
10060 .buffer
10061 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10062 {
10063 if let Some((_, end_selections)) =
10064 self.selection_history.transaction_mut(transaction_id)
10065 {
10066 *end_selections = Some(self.selections.disjoint_anchors());
10067 } else {
10068 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10069 }
10070
10071 cx.emit(EditorEvent::Edited { transaction_id });
10072 Some(transaction_id)
10073 } else {
10074 None
10075 }
10076 }
10077
10078 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10079 let mut fold_ranges = Vec::new();
10080
10081 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10082
10083 let selections = self.selections.all_adjusted(cx);
10084 for selection in selections {
10085 let range = selection.range().sorted();
10086 let buffer_start_row = range.start.row;
10087
10088 for row in (0..=range.end.row).rev() {
10089 if let Some((foldable_range, fold_text)) =
10090 display_map.foldable_range(MultiBufferRow(row))
10091 {
10092 if foldable_range.end.row >= buffer_start_row {
10093 fold_ranges.push((foldable_range, fold_text));
10094 if row <= range.start.row {
10095 break;
10096 }
10097 }
10098 }
10099 }
10100 }
10101
10102 self.fold_ranges(fold_ranges, true, cx);
10103 }
10104
10105 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10106 let buffer_row = fold_at.buffer_row;
10107 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10108
10109 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10110 let autoscroll = self
10111 .selections
10112 .all::<Point>(cx)
10113 .iter()
10114 .any(|selection| fold_range.overlaps(&selection.range()));
10115
10116 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10117 }
10118 }
10119
10120 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10121 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10122 let buffer = &display_map.buffer_snapshot;
10123 let selections = self.selections.all::<Point>(cx);
10124 let ranges = selections
10125 .iter()
10126 .map(|s| {
10127 let range = s.display_range(&display_map).sorted();
10128 let mut start = range.start.to_point(&display_map);
10129 let mut end = range.end.to_point(&display_map);
10130 start.column = 0;
10131 end.column = buffer.line_len(MultiBufferRow(end.row));
10132 start..end
10133 })
10134 .collect::<Vec<_>>();
10135
10136 self.unfold_ranges(ranges, true, true, cx);
10137 }
10138
10139 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10140 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10141
10142 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10143 ..Point::new(
10144 unfold_at.buffer_row.0,
10145 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10146 );
10147
10148 let autoscroll = self
10149 .selections
10150 .all::<Point>(cx)
10151 .iter()
10152 .any(|selection| selection.range().overlaps(&intersection_range));
10153
10154 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10155 }
10156
10157 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10158 let selections = self.selections.all::<Point>(cx);
10159 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10160 let line_mode = self.selections.line_mode;
10161 let ranges = selections.into_iter().map(|s| {
10162 if line_mode {
10163 let start = Point::new(s.start.row, 0);
10164 let end = Point::new(
10165 s.end.row,
10166 display_map
10167 .buffer_snapshot
10168 .line_len(MultiBufferRow(s.end.row)),
10169 );
10170 (start..end, display_map.fold_placeholder.clone())
10171 } else {
10172 (s.start..s.end, display_map.fold_placeholder.clone())
10173 }
10174 });
10175 self.fold_ranges(ranges, true, cx);
10176 }
10177
10178 pub fn fold_ranges<T: ToOffset + Clone>(
10179 &mut self,
10180 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10181 auto_scroll: bool,
10182 cx: &mut ViewContext<Self>,
10183 ) {
10184 let mut fold_ranges = Vec::new();
10185 let mut buffers_affected = HashMap::default();
10186 let multi_buffer = self.buffer().read(cx);
10187 for (fold_range, fold_text) in ranges {
10188 if let Some((_, buffer, _)) =
10189 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10190 {
10191 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10192 };
10193 fold_ranges.push((fold_range, fold_text));
10194 }
10195
10196 let mut ranges = fold_ranges.into_iter().peekable();
10197 if ranges.peek().is_some() {
10198 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10199
10200 if auto_scroll {
10201 self.request_autoscroll(Autoscroll::fit(), cx);
10202 }
10203
10204 for buffer in buffers_affected.into_values() {
10205 self.sync_expanded_diff_hunks(buffer, cx);
10206 }
10207
10208 cx.notify();
10209
10210 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10211 // Clear diagnostics block when folding a range that contains it.
10212 let snapshot = self.snapshot(cx);
10213 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10214 drop(snapshot);
10215 self.active_diagnostics = Some(active_diagnostics);
10216 self.dismiss_diagnostics(cx);
10217 } else {
10218 self.active_diagnostics = Some(active_diagnostics);
10219 }
10220 }
10221
10222 self.scrollbar_marker_state.dirty = true;
10223 }
10224 }
10225
10226 pub fn unfold_ranges<T: ToOffset + Clone>(
10227 &mut self,
10228 ranges: impl IntoIterator<Item = Range<T>>,
10229 inclusive: bool,
10230 auto_scroll: bool,
10231 cx: &mut ViewContext<Self>,
10232 ) {
10233 let mut unfold_ranges = Vec::new();
10234 let mut buffers_affected = HashMap::default();
10235 let multi_buffer = self.buffer().read(cx);
10236 for range in ranges {
10237 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10238 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10239 };
10240 unfold_ranges.push(range);
10241 }
10242
10243 let mut ranges = unfold_ranges.into_iter().peekable();
10244 if ranges.peek().is_some() {
10245 self.display_map
10246 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10247 if auto_scroll {
10248 self.request_autoscroll(Autoscroll::fit(), cx);
10249 }
10250
10251 for buffer in buffers_affected.into_values() {
10252 self.sync_expanded_diff_hunks(buffer, cx);
10253 }
10254
10255 cx.notify();
10256 self.scrollbar_marker_state.dirty = true;
10257 self.active_indent_guides_state.dirty = true;
10258 }
10259 }
10260
10261 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10262 if hovered != self.gutter_hovered {
10263 self.gutter_hovered = hovered;
10264 cx.notify();
10265 }
10266 }
10267
10268 pub fn insert_blocks(
10269 &mut self,
10270 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10271 autoscroll: Option<Autoscroll>,
10272 cx: &mut ViewContext<Self>,
10273 ) -> Vec<CustomBlockId> {
10274 let blocks = self
10275 .display_map
10276 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10277 if let Some(autoscroll) = autoscroll {
10278 self.request_autoscroll(autoscroll, cx);
10279 }
10280 cx.notify();
10281 blocks
10282 }
10283
10284 pub fn resize_blocks(
10285 &mut self,
10286 heights: HashMap<CustomBlockId, u32>,
10287 autoscroll: Option<Autoscroll>,
10288 cx: &mut ViewContext<Self>,
10289 ) {
10290 self.display_map
10291 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10292 if let Some(autoscroll) = autoscroll {
10293 self.request_autoscroll(autoscroll, cx);
10294 }
10295 cx.notify();
10296 }
10297
10298 pub fn replace_blocks(
10299 &mut self,
10300 renderers: HashMap<CustomBlockId, RenderBlock>,
10301 autoscroll: Option<Autoscroll>,
10302 cx: &mut ViewContext<Self>,
10303 ) {
10304 self.display_map
10305 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10306 if let Some(autoscroll) = autoscroll {
10307 self.request_autoscroll(autoscroll, cx);
10308 }
10309 cx.notify();
10310 }
10311
10312 pub fn remove_blocks(
10313 &mut self,
10314 block_ids: HashSet<CustomBlockId>,
10315 autoscroll: Option<Autoscroll>,
10316 cx: &mut ViewContext<Self>,
10317 ) {
10318 self.display_map.update(cx, |display_map, cx| {
10319 display_map.remove_blocks(block_ids, cx)
10320 });
10321 if let Some(autoscroll) = autoscroll {
10322 self.request_autoscroll(autoscroll, cx);
10323 }
10324 cx.notify();
10325 }
10326
10327 pub fn row_for_block(
10328 &self,
10329 block_id: CustomBlockId,
10330 cx: &mut ViewContext<Self>,
10331 ) -> Option<DisplayRow> {
10332 self.display_map
10333 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10334 }
10335
10336 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10337 self.focused_block = Some(focused_block);
10338 }
10339
10340 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10341 self.focused_block.take()
10342 }
10343
10344 pub fn insert_creases(
10345 &mut self,
10346 creases: impl IntoIterator<Item = Crease>,
10347 cx: &mut ViewContext<Self>,
10348 ) -> Vec<CreaseId> {
10349 self.display_map
10350 .update(cx, |map, cx| map.insert_creases(creases, cx))
10351 }
10352
10353 pub fn remove_creases(
10354 &mut self,
10355 ids: impl IntoIterator<Item = CreaseId>,
10356 cx: &mut ViewContext<Self>,
10357 ) {
10358 self.display_map
10359 .update(cx, |map, cx| map.remove_creases(ids, cx));
10360 }
10361
10362 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10363 self.display_map
10364 .update(cx, |map, cx| map.snapshot(cx))
10365 .longest_row()
10366 }
10367
10368 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10369 self.display_map
10370 .update(cx, |map, cx| map.snapshot(cx))
10371 .max_point()
10372 }
10373
10374 pub fn text(&self, cx: &AppContext) -> String {
10375 self.buffer.read(cx).read(cx).text()
10376 }
10377
10378 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10379 let text = self.text(cx);
10380 let text = text.trim();
10381
10382 if text.is_empty() {
10383 return None;
10384 }
10385
10386 Some(text.to_string())
10387 }
10388
10389 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10390 self.transact(cx, |this, cx| {
10391 this.buffer
10392 .read(cx)
10393 .as_singleton()
10394 .expect("you can only call set_text on editors for singleton buffers")
10395 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10396 });
10397 }
10398
10399 pub fn display_text(&self, cx: &mut AppContext) -> String {
10400 self.display_map
10401 .update(cx, |map, cx| map.snapshot(cx))
10402 .text()
10403 }
10404
10405 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10406 let mut wrap_guides = smallvec::smallvec![];
10407
10408 if self.show_wrap_guides == Some(false) {
10409 return wrap_guides;
10410 }
10411
10412 let settings = self.buffer.read(cx).settings_at(0, cx);
10413 if settings.show_wrap_guides {
10414 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10415 wrap_guides.push((soft_wrap as usize, true));
10416 }
10417 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10418 }
10419
10420 wrap_guides
10421 }
10422
10423 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10424 let settings = self.buffer.read(cx).settings_at(0, cx);
10425 let mode = self
10426 .soft_wrap_mode_override
10427 .unwrap_or_else(|| settings.soft_wrap);
10428 match mode {
10429 language_settings::SoftWrap::None => SoftWrap::None,
10430 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10431 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10432 language_settings::SoftWrap::PreferredLineLength => {
10433 SoftWrap::Column(settings.preferred_line_length)
10434 }
10435 }
10436 }
10437
10438 pub fn set_soft_wrap_mode(
10439 &mut self,
10440 mode: language_settings::SoftWrap,
10441 cx: &mut ViewContext<Self>,
10442 ) {
10443 self.soft_wrap_mode_override = Some(mode);
10444 cx.notify();
10445 }
10446
10447 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10448 let rem_size = cx.rem_size();
10449 self.display_map.update(cx, |map, cx| {
10450 map.set_font(
10451 style.text.font(),
10452 style.text.font_size.to_pixels(rem_size),
10453 cx,
10454 )
10455 });
10456 self.style = Some(style);
10457 }
10458
10459 pub fn style(&self) -> Option<&EditorStyle> {
10460 self.style.as_ref()
10461 }
10462
10463 // Called by the element. This method is not designed to be called outside of the editor
10464 // element's layout code because it does not notify when rewrapping is computed synchronously.
10465 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10466 self.display_map
10467 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10468 }
10469
10470 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10471 if self.soft_wrap_mode_override.is_some() {
10472 self.soft_wrap_mode_override.take();
10473 } else {
10474 let soft_wrap = match self.soft_wrap_mode(cx) {
10475 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10476 SoftWrap::EditorWidth | SoftWrap::Column(_) => {
10477 language_settings::SoftWrap::PreferLine
10478 }
10479 };
10480 self.soft_wrap_mode_override = Some(soft_wrap);
10481 }
10482 cx.notify();
10483 }
10484
10485 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10486 let Some(workspace) = self.workspace() else {
10487 return;
10488 };
10489 let fs = workspace.read(cx).app_state().fs.clone();
10490 let current_show = TabBarSettings::get_global(cx).show;
10491 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10492 setting.show = Some(!current_show);
10493 });
10494 }
10495
10496 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10497 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10498 self.buffer
10499 .read(cx)
10500 .settings_at(0, cx)
10501 .indent_guides
10502 .enabled
10503 });
10504 self.show_indent_guides = Some(!currently_enabled);
10505 cx.notify();
10506 }
10507
10508 fn should_show_indent_guides(&self) -> Option<bool> {
10509 self.show_indent_guides
10510 }
10511
10512 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10513 let mut editor_settings = EditorSettings::get_global(cx).clone();
10514 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10515 EditorSettings::override_global(editor_settings, cx);
10516 }
10517
10518 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10519 self.show_gutter = show_gutter;
10520 cx.notify();
10521 }
10522
10523 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10524 self.show_line_numbers = Some(show_line_numbers);
10525 cx.notify();
10526 }
10527
10528 pub fn set_show_git_diff_gutter(
10529 &mut self,
10530 show_git_diff_gutter: bool,
10531 cx: &mut ViewContext<Self>,
10532 ) {
10533 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10534 cx.notify();
10535 }
10536
10537 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10538 self.show_code_actions = Some(show_code_actions);
10539 cx.notify();
10540 }
10541
10542 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10543 self.show_runnables = Some(show_runnables);
10544 cx.notify();
10545 }
10546
10547 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10548 if self.display_map.read(cx).masked != masked {
10549 self.display_map.update(cx, |map, _| map.masked = masked);
10550 }
10551 cx.notify()
10552 }
10553
10554 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10555 self.show_wrap_guides = Some(show_wrap_guides);
10556 cx.notify();
10557 }
10558
10559 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10560 self.show_indent_guides = Some(show_indent_guides);
10561 cx.notify();
10562 }
10563
10564 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10565 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10566 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10567 if let Some(dir) = file.abs_path(cx).parent() {
10568 return Some(dir.to_owned());
10569 }
10570 }
10571
10572 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10573 return Some(project_path.path.to_path_buf());
10574 }
10575 }
10576
10577 None
10578 }
10579
10580 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10581 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10582 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10583 cx.reveal_path(&file.abs_path(cx));
10584 }
10585 }
10586 }
10587
10588 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10589 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10590 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10591 if let Some(path) = file.abs_path(cx).to_str() {
10592 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10593 }
10594 }
10595 }
10596 }
10597
10598 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10599 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10600 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10601 if let Some(path) = file.path().to_str() {
10602 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10603 }
10604 }
10605 }
10606 }
10607
10608 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10609 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10610
10611 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10612 self.start_git_blame(true, cx);
10613 }
10614
10615 cx.notify();
10616 }
10617
10618 pub fn toggle_git_blame_inline(
10619 &mut self,
10620 _: &ToggleGitBlameInline,
10621 cx: &mut ViewContext<Self>,
10622 ) {
10623 self.toggle_git_blame_inline_internal(true, cx);
10624 cx.notify();
10625 }
10626
10627 pub fn git_blame_inline_enabled(&self) -> bool {
10628 self.git_blame_inline_enabled
10629 }
10630
10631 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
10632 self.show_selection_menu = self
10633 .show_selection_menu
10634 .map(|show_selections_menu| !show_selections_menu)
10635 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
10636
10637 cx.notify();
10638 }
10639
10640 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
10641 self.show_selection_menu
10642 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
10643 }
10644
10645 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10646 if let Some(project) = self.project.as_ref() {
10647 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
10648 return;
10649 };
10650
10651 if buffer.read(cx).file().is_none() {
10652 return;
10653 }
10654
10655 let focused = self.focus_handle(cx).contains_focused(cx);
10656
10657 let project = project.clone();
10658 let blame =
10659 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
10660 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
10661 self.blame = Some(blame);
10662 }
10663 }
10664
10665 fn toggle_git_blame_inline_internal(
10666 &mut self,
10667 user_triggered: bool,
10668 cx: &mut ViewContext<Self>,
10669 ) {
10670 if self.git_blame_inline_enabled {
10671 self.git_blame_inline_enabled = false;
10672 self.show_git_blame_inline = false;
10673 self.show_git_blame_inline_delay_task.take();
10674 } else {
10675 self.git_blame_inline_enabled = true;
10676 self.start_git_blame_inline(user_triggered, cx);
10677 }
10678
10679 cx.notify();
10680 }
10681
10682 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
10683 self.start_git_blame(user_triggered, cx);
10684
10685 if ProjectSettings::get_global(cx)
10686 .git
10687 .inline_blame_delay()
10688 .is_some()
10689 {
10690 self.start_inline_blame_timer(cx);
10691 } else {
10692 self.show_git_blame_inline = true
10693 }
10694 }
10695
10696 pub fn blame(&self) -> Option<&Model<GitBlame>> {
10697 self.blame.as_ref()
10698 }
10699
10700 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
10701 self.show_git_blame_gutter && self.has_blame_entries(cx)
10702 }
10703
10704 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
10705 self.show_git_blame_inline
10706 && self.focus_handle.is_focused(cx)
10707 && !self.newest_selection_head_on_empty_line(cx)
10708 && self.has_blame_entries(cx)
10709 }
10710
10711 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
10712 self.blame()
10713 .map_or(false, |blame| blame.read(cx).has_generated_entries())
10714 }
10715
10716 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
10717 let cursor_anchor = self.selections.newest_anchor().head();
10718
10719 let snapshot = self.buffer.read(cx).snapshot(cx);
10720 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
10721
10722 snapshot.line_len(buffer_row) == 0
10723 }
10724
10725 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
10726 let (path, selection, repo) = maybe!({
10727 let project_handle = self.project.as_ref()?.clone();
10728 let project = project_handle.read(cx);
10729
10730 let selection = self.selections.newest::<Point>(cx);
10731 let selection_range = selection.range();
10732
10733 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10734 (buffer, selection_range.start.row..selection_range.end.row)
10735 } else {
10736 let buffer_ranges = self
10737 .buffer()
10738 .read(cx)
10739 .range_to_buffer_ranges(selection_range, cx);
10740
10741 let (buffer, range, _) = if selection.reversed {
10742 buffer_ranges.first()
10743 } else {
10744 buffer_ranges.last()
10745 }?;
10746
10747 let snapshot = buffer.read(cx).snapshot();
10748 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
10749 ..text::ToPoint::to_point(&range.end, &snapshot).row;
10750 (buffer.clone(), selection)
10751 };
10752
10753 let path = buffer
10754 .read(cx)
10755 .file()?
10756 .as_local()?
10757 .path()
10758 .to_str()?
10759 .to_string();
10760 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
10761 Some((path, selection, repo))
10762 })
10763 .ok_or_else(|| anyhow!("unable to open git repository"))?;
10764
10765 const REMOTE_NAME: &str = "origin";
10766 let origin_url = repo
10767 .remote_url(REMOTE_NAME)
10768 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
10769 let sha = repo
10770 .head_sha()
10771 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
10772
10773 let (provider, remote) =
10774 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
10775 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
10776
10777 Ok(provider.build_permalink(
10778 remote,
10779 BuildPermalinkParams {
10780 sha: &sha,
10781 path: &path,
10782 selection: Some(selection),
10783 },
10784 ))
10785 }
10786
10787 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
10788 let permalink = self.get_permalink_to_line(cx);
10789
10790 match permalink {
10791 Ok(permalink) => {
10792 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
10793 }
10794 Err(err) => {
10795 let message = format!("Failed to copy permalink: {err}");
10796
10797 Err::<(), anyhow::Error>(err).log_err();
10798
10799 if let Some(workspace) = self.workspace() {
10800 workspace.update(cx, |workspace, cx| {
10801 struct CopyPermalinkToLine;
10802
10803 workspace.show_toast(
10804 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
10805 cx,
10806 )
10807 })
10808 }
10809 }
10810 }
10811 }
10812
10813 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
10814 let permalink = self.get_permalink_to_line(cx);
10815
10816 match permalink {
10817 Ok(permalink) => {
10818 cx.open_url(permalink.as_ref());
10819 }
10820 Err(err) => {
10821 let message = format!("Failed to open permalink: {err}");
10822
10823 Err::<(), anyhow::Error>(err).log_err();
10824
10825 if let Some(workspace) = self.workspace() {
10826 workspace.update(cx, |workspace, cx| {
10827 struct OpenPermalinkToLine;
10828
10829 workspace.show_toast(
10830 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
10831 cx,
10832 )
10833 })
10834 }
10835 }
10836 }
10837 }
10838
10839 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
10840 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
10841 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
10842 pub fn highlight_rows<T: 'static>(
10843 &mut self,
10844 rows: RangeInclusive<Anchor>,
10845 color: Option<Hsla>,
10846 should_autoscroll: bool,
10847 cx: &mut ViewContext<Self>,
10848 ) {
10849 let snapshot = self.buffer().read(cx).snapshot(cx);
10850 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
10851 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
10852 highlight
10853 .range
10854 .start()
10855 .cmp(&rows.start(), &snapshot)
10856 .then(highlight.range.end().cmp(&rows.end(), &snapshot))
10857 });
10858 match (color, existing_highlight_index) {
10859 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
10860 ix,
10861 RowHighlight {
10862 index: post_inc(&mut self.highlight_order),
10863 range: rows,
10864 should_autoscroll,
10865 color,
10866 },
10867 ),
10868 (None, Ok(i)) => {
10869 row_highlights.remove(i);
10870 }
10871 }
10872 }
10873
10874 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
10875 pub fn clear_row_highlights<T: 'static>(&mut self) {
10876 self.highlighted_rows.remove(&TypeId::of::<T>());
10877 }
10878
10879 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
10880 pub fn highlighted_rows<T: 'static>(
10881 &self,
10882 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
10883 Some(
10884 self.highlighted_rows
10885 .get(&TypeId::of::<T>())?
10886 .iter()
10887 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
10888 )
10889 }
10890
10891 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
10892 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
10893 /// Allows to ignore certain kinds of highlights.
10894 pub fn highlighted_display_rows(
10895 &mut self,
10896 cx: &mut WindowContext,
10897 ) -> BTreeMap<DisplayRow, Hsla> {
10898 let snapshot = self.snapshot(cx);
10899 let mut used_highlight_orders = HashMap::default();
10900 self.highlighted_rows
10901 .iter()
10902 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
10903 .fold(
10904 BTreeMap::<DisplayRow, Hsla>::new(),
10905 |mut unique_rows, highlight| {
10906 let start_row = highlight.range.start().to_display_point(&snapshot).row();
10907 let end_row = highlight.range.end().to_display_point(&snapshot).row();
10908 for row in start_row.0..=end_row.0 {
10909 let used_index =
10910 used_highlight_orders.entry(row).or_insert(highlight.index);
10911 if highlight.index >= *used_index {
10912 *used_index = highlight.index;
10913 match highlight.color {
10914 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
10915 None => unique_rows.remove(&DisplayRow(row)),
10916 };
10917 }
10918 }
10919 unique_rows
10920 },
10921 )
10922 }
10923
10924 pub fn highlighted_display_row_for_autoscroll(
10925 &self,
10926 snapshot: &DisplaySnapshot,
10927 ) -> Option<DisplayRow> {
10928 self.highlighted_rows
10929 .values()
10930 .flat_map(|highlighted_rows| highlighted_rows.iter())
10931 .filter_map(|highlight| {
10932 if highlight.color.is_none() || !highlight.should_autoscroll {
10933 return None;
10934 }
10935 Some(highlight.range.start().to_display_point(&snapshot).row())
10936 })
10937 .min()
10938 }
10939
10940 pub fn set_search_within_ranges(
10941 &mut self,
10942 ranges: &[Range<Anchor>],
10943 cx: &mut ViewContext<Self>,
10944 ) {
10945 self.highlight_background::<SearchWithinRange>(
10946 ranges,
10947 |colors| colors.editor_document_highlight_read_background,
10948 cx,
10949 )
10950 }
10951
10952 pub fn set_breadcrumb_header(&mut self, new_header: String) {
10953 self.breadcrumb_header = Some(new_header);
10954 }
10955
10956 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
10957 self.clear_background_highlights::<SearchWithinRange>(cx);
10958 }
10959
10960 pub fn highlight_background<T: 'static>(
10961 &mut self,
10962 ranges: &[Range<Anchor>],
10963 color_fetcher: fn(&ThemeColors) -> Hsla,
10964 cx: &mut ViewContext<Self>,
10965 ) {
10966 self.background_highlights
10967 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10968 self.scrollbar_marker_state.dirty = true;
10969 cx.notify();
10970 }
10971
10972 pub fn clear_background_highlights<T: 'static>(
10973 &mut self,
10974 cx: &mut ViewContext<Self>,
10975 ) -> Option<BackgroundHighlight> {
10976 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
10977 if !text_highlights.1.is_empty() {
10978 self.scrollbar_marker_state.dirty = true;
10979 cx.notify();
10980 }
10981 Some(text_highlights)
10982 }
10983
10984 pub fn highlight_gutter<T: 'static>(
10985 &mut self,
10986 ranges: &[Range<Anchor>],
10987 color_fetcher: fn(&AppContext) -> Hsla,
10988 cx: &mut ViewContext<Self>,
10989 ) {
10990 self.gutter_highlights
10991 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
10992 cx.notify();
10993 }
10994
10995 pub fn clear_gutter_highlights<T: 'static>(
10996 &mut self,
10997 cx: &mut ViewContext<Self>,
10998 ) -> Option<GutterHighlight> {
10999 cx.notify();
11000 self.gutter_highlights.remove(&TypeId::of::<T>())
11001 }
11002
11003 #[cfg(feature = "test-support")]
11004 pub fn all_text_background_highlights(
11005 &mut self,
11006 cx: &mut ViewContext<Self>,
11007 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11008 let snapshot = self.snapshot(cx);
11009 let buffer = &snapshot.buffer_snapshot;
11010 let start = buffer.anchor_before(0);
11011 let end = buffer.anchor_after(buffer.len());
11012 let theme = cx.theme().colors();
11013 self.background_highlights_in_range(start..end, &snapshot, theme)
11014 }
11015
11016 #[cfg(feature = "test-support")]
11017 pub fn search_background_highlights(
11018 &mut self,
11019 cx: &mut ViewContext<Self>,
11020 ) -> Vec<Range<Point>> {
11021 let snapshot = self.buffer().read(cx).snapshot(cx);
11022
11023 let highlights = self
11024 .background_highlights
11025 .get(&TypeId::of::<items::BufferSearchHighlights>());
11026
11027 if let Some((_color, ranges)) = highlights {
11028 ranges
11029 .iter()
11030 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11031 .collect_vec()
11032 } else {
11033 vec![]
11034 }
11035 }
11036
11037 fn document_highlights_for_position<'a>(
11038 &'a self,
11039 position: Anchor,
11040 buffer: &'a MultiBufferSnapshot,
11041 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11042 let read_highlights = self
11043 .background_highlights
11044 .get(&TypeId::of::<DocumentHighlightRead>())
11045 .map(|h| &h.1);
11046 let write_highlights = self
11047 .background_highlights
11048 .get(&TypeId::of::<DocumentHighlightWrite>())
11049 .map(|h| &h.1);
11050 let left_position = position.bias_left(buffer);
11051 let right_position = position.bias_right(buffer);
11052 read_highlights
11053 .into_iter()
11054 .chain(write_highlights)
11055 .flat_map(move |ranges| {
11056 let start_ix = match ranges.binary_search_by(|probe| {
11057 let cmp = probe.end.cmp(&left_position, buffer);
11058 if cmp.is_ge() {
11059 Ordering::Greater
11060 } else {
11061 Ordering::Less
11062 }
11063 }) {
11064 Ok(i) | Err(i) => i,
11065 };
11066
11067 ranges[start_ix..]
11068 .iter()
11069 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11070 })
11071 }
11072
11073 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11074 self.background_highlights
11075 .get(&TypeId::of::<T>())
11076 .map_or(false, |(_, highlights)| !highlights.is_empty())
11077 }
11078
11079 pub fn background_highlights_in_range(
11080 &self,
11081 search_range: Range<Anchor>,
11082 display_snapshot: &DisplaySnapshot,
11083 theme: &ThemeColors,
11084 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11085 let mut results = Vec::new();
11086 for (color_fetcher, ranges) in self.background_highlights.values() {
11087 let color = color_fetcher(theme);
11088 let start_ix = match ranges.binary_search_by(|probe| {
11089 let cmp = probe
11090 .end
11091 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11092 if cmp.is_gt() {
11093 Ordering::Greater
11094 } else {
11095 Ordering::Less
11096 }
11097 }) {
11098 Ok(i) | Err(i) => i,
11099 };
11100 for range in &ranges[start_ix..] {
11101 if range
11102 .start
11103 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11104 .is_ge()
11105 {
11106 break;
11107 }
11108
11109 let start = range.start.to_display_point(&display_snapshot);
11110 let end = range.end.to_display_point(&display_snapshot);
11111 results.push((start..end, color))
11112 }
11113 }
11114 results
11115 }
11116
11117 pub fn background_highlight_row_ranges<T: 'static>(
11118 &self,
11119 search_range: Range<Anchor>,
11120 display_snapshot: &DisplaySnapshot,
11121 count: usize,
11122 ) -> Vec<RangeInclusive<DisplayPoint>> {
11123 let mut results = Vec::new();
11124 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11125 return vec![];
11126 };
11127
11128 let start_ix = match ranges.binary_search_by(|probe| {
11129 let cmp = probe
11130 .end
11131 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11132 if cmp.is_gt() {
11133 Ordering::Greater
11134 } else {
11135 Ordering::Less
11136 }
11137 }) {
11138 Ok(i) | Err(i) => i,
11139 };
11140 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11141 if let (Some(start_display), Some(end_display)) = (start, end) {
11142 results.push(
11143 start_display.to_display_point(display_snapshot)
11144 ..=end_display.to_display_point(display_snapshot),
11145 );
11146 }
11147 };
11148 let mut start_row: Option<Point> = None;
11149 let mut end_row: Option<Point> = None;
11150 if ranges.len() > count {
11151 return Vec::new();
11152 }
11153 for range in &ranges[start_ix..] {
11154 if range
11155 .start
11156 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11157 .is_ge()
11158 {
11159 break;
11160 }
11161 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11162 if let Some(current_row) = &end_row {
11163 if end.row == current_row.row {
11164 continue;
11165 }
11166 }
11167 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11168 if start_row.is_none() {
11169 assert_eq!(end_row, None);
11170 start_row = Some(start);
11171 end_row = Some(end);
11172 continue;
11173 }
11174 if let Some(current_end) = end_row.as_mut() {
11175 if start.row > current_end.row + 1 {
11176 push_region(start_row, end_row);
11177 start_row = Some(start);
11178 end_row = Some(end);
11179 } else {
11180 // Merge two hunks.
11181 *current_end = end;
11182 }
11183 } else {
11184 unreachable!();
11185 }
11186 }
11187 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11188 push_region(start_row, end_row);
11189 results
11190 }
11191
11192 pub fn gutter_highlights_in_range(
11193 &self,
11194 search_range: Range<Anchor>,
11195 display_snapshot: &DisplaySnapshot,
11196 cx: &AppContext,
11197 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11198 let mut results = Vec::new();
11199 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11200 let color = color_fetcher(cx);
11201 let start_ix = match ranges.binary_search_by(|probe| {
11202 let cmp = probe
11203 .end
11204 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11205 if cmp.is_gt() {
11206 Ordering::Greater
11207 } else {
11208 Ordering::Less
11209 }
11210 }) {
11211 Ok(i) | Err(i) => i,
11212 };
11213 for range in &ranges[start_ix..] {
11214 if range
11215 .start
11216 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11217 .is_ge()
11218 {
11219 break;
11220 }
11221
11222 let start = range.start.to_display_point(&display_snapshot);
11223 let end = range.end.to_display_point(&display_snapshot);
11224 results.push((start..end, color))
11225 }
11226 }
11227 results
11228 }
11229
11230 /// Get the text ranges corresponding to the redaction query
11231 pub fn redacted_ranges(
11232 &self,
11233 search_range: Range<Anchor>,
11234 display_snapshot: &DisplaySnapshot,
11235 cx: &WindowContext,
11236 ) -> Vec<Range<DisplayPoint>> {
11237 display_snapshot
11238 .buffer_snapshot
11239 .redacted_ranges(search_range, |file| {
11240 if let Some(file) = file {
11241 file.is_private()
11242 && EditorSettings::get(Some(file.as_ref().into()), cx).redact_private_values
11243 } else {
11244 false
11245 }
11246 })
11247 .map(|range| {
11248 range.start.to_display_point(display_snapshot)
11249 ..range.end.to_display_point(display_snapshot)
11250 })
11251 .collect()
11252 }
11253
11254 pub fn highlight_text<T: 'static>(
11255 &mut self,
11256 ranges: Vec<Range<Anchor>>,
11257 style: HighlightStyle,
11258 cx: &mut ViewContext<Self>,
11259 ) {
11260 self.display_map.update(cx, |map, _| {
11261 map.highlight_text(TypeId::of::<T>(), ranges, style)
11262 });
11263 cx.notify();
11264 }
11265
11266 pub(crate) fn highlight_inlays<T: 'static>(
11267 &mut self,
11268 highlights: Vec<InlayHighlight>,
11269 style: HighlightStyle,
11270 cx: &mut ViewContext<Self>,
11271 ) {
11272 self.display_map.update(cx, |map, _| {
11273 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11274 });
11275 cx.notify();
11276 }
11277
11278 pub fn text_highlights<'a, T: 'static>(
11279 &'a self,
11280 cx: &'a AppContext,
11281 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11282 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11283 }
11284
11285 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11286 let cleared = self
11287 .display_map
11288 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11289 if cleared {
11290 cx.notify();
11291 }
11292 }
11293
11294 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11295 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11296 && self.focus_handle.is_focused(cx)
11297 }
11298
11299 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11300 self.show_cursor_when_unfocused = is_enabled;
11301 cx.notify();
11302 }
11303
11304 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11305 cx.notify();
11306 }
11307
11308 fn on_buffer_event(
11309 &mut self,
11310 multibuffer: Model<MultiBuffer>,
11311 event: &multi_buffer::Event,
11312 cx: &mut ViewContext<Self>,
11313 ) {
11314 match event {
11315 multi_buffer::Event::Edited {
11316 singleton_buffer_edited,
11317 } => {
11318 self.scrollbar_marker_state.dirty = true;
11319 self.active_indent_guides_state.dirty = true;
11320 self.refresh_active_diagnostics(cx);
11321 self.refresh_code_actions(cx);
11322 if self.has_active_inline_completion(cx) {
11323 self.update_visible_inline_completion(cx);
11324 }
11325 cx.emit(EditorEvent::BufferEdited);
11326 cx.emit(SearchEvent::MatchesInvalidated);
11327 if *singleton_buffer_edited {
11328 if let Some(project) = &self.project {
11329 let project = project.read(cx);
11330 #[allow(clippy::mutable_key_type)]
11331 let languages_affected = multibuffer
11332 .read(cx)
11333 .all_buffers()
11334 .into_iter()
11335 .filter_map(|buffer| {
11336 let buffer = buffer.read(cx);
11337 let language = buffer.language()?;
11338 if project.is_local()
11339 && project.language_servers_for_buffer(buffer, cx).count() == 0
11340 {
11341 None
11342 } else {
11343 Some(language)
11344 }
11345 })
11346 .cloned()
11347 .collect::<HashSet<_>>();
11348 if !languages_affected.is_empty() {
11349 self.refresh_inlay_hints(
11350 InlayHintRefreshReason::BufferEdited(languages_affected),
11351 cx,
11352 );
11353 }
11354 }
11355 }
11356
11357 let Some(project) = &self.project else { return };
11358 let telemetry = project.read(cx).client().telemetry().clone();
11359 refresh_linked_ranges(self, cx);
11360 telemetry.log_edit_event("editor");
11361 }
11362 multi_buffer::Event::ExcerptsAdded {
11363 buffer,
11364 predecessor,
11365 excerpts,
11366 } => {
11367 self.tasks_update_task = Some(self.refresh_runnables(cx));
11368 cx.emit(EditorEvent::ExcerptsAdded {
11369 buffer: buffer.clone(),
11370 predecessor: *predecessor,
11371 excerpts: excerpts.clone(),
11372 });
11373 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11374 }
11375 multi_buffer::Event::ExcerptsRemoved { ids } => {
11376 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11377 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11378 }
11379 multi_buffer::Event::ExcerptsEdited { ids } => {
11380 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11381 }
11382 multi_buffer::Event::ExcerptsExpanded { ids } => {
11383 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11384 }
11385 multi_buffer::Event::Reparsed(buffer_id) => {
11386 self.tasks_update_task = Some(self.refresh_runnables(cx));
11387
11388 cx.emit(EditorEvent::Reparsed(*buffer_id));
11389 }
11390 multi_buffer::Event::LanguageChanged(buffer_id) => {
11391 linked_editing_ranges::refresh_linked_ranges(self, cx);
11392 cx.emit(EditorEvent::Reparsed(*buffer_id));
11393 cx.notify();
11394 }
11395 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11396 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11397 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11398 cx.emit(EditorEvent::TitleChanged)
11399 }
11400 multi_buffer::Event::DiffBaseChanged => {
11401 self.scrollbar_marker_state.dirty = true;
11402 cx.emit(EditorEvent::DiffBaseChanged);
11403 cx.notify();
11404 }
11405 multi_buffer::Event::DiffUpdated { buffer } => {
11406 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11407 cx.notify();
11408 }
11409 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11410 multi_buffer::Event::DiagnosticsUpdated => {
11411 self.refresh_active_diagnostics(cx);
11412 self.scrollbar_marker_state.dirty = true;
11413 cx.notify();
11414 }
11415 _ => {}
11416 };
11417 }
11418
11419 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11420 cx.notify();
11421 }
11422
11423 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11424 self.tasks_update_task = Some(self.refresh_runnables(cx));
11425 self.refresh_inline_completion(true, cx);
11426 self.refresh_inlay_hints(
11427 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11428 self.selections.newest_anchor().head(),
11429 &self.buffer.read(cx).snapshot(cx),
11430 cx,
11431 )),
11432 cx,
11433 );
11434 let editor_settings = EditorSettings::get_global(cx);
11435 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11436 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11437
11438 let project_settings = ProjectSettings::get_global(cx);
11439 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11440
11441 if self.mode == EditorMode::Full {
11442 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11443 if self.git_blame_inline_enabled != inline_blame_enabled {
11444 self.toggle_git_blame_inline_internal(false, cx);
11445 }
11446 }
11447
11448 cx.notify();
11449 }
11450
11451 pub fn set_searchable(&mut self, searchable: bool) {
11452 self.searchable = searchable;
11453 }
11454
11455 pub fn searchable(&self) -> bool {
11456 self.searchable
11457 }
11458
11459 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11460 self.open_excerpts_common(true, cx)
11461 }
11462
11463 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11464 self.open_excerpts_common(false, cx)
11465 }
11466
11467 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11468 let buffer = self.buffer.read(cx);
11469 if buffer.is_singleton() {
11470 cx.propagate();
11471 return;
11472 }
11473
11474 let Some(workspace) = self.workspace() else {
11475 cx.propagate();
11476 return;
11477 };
11478
11479 let mut new_selections_by_buffer = HashMap::default();
11480 for selection in self.selections.all::<usize>(cx) {
11481 for (buffer, mut range, _) in
11482 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11483 {
11484 if selection.reversed {
11485 mem::swap(&mut range.start, &mut range.end);
11486 }
11487 new_selections_by_buffer
11488 .entry(buffer)
11489 .or_insert(Vec::new())
11490 .push(range)
11491 }
11492 }
11493
11494 // We defer the pane interaction because we ourselves are a workspace item
11495 // and activating a new item causes the pane to call a method on us reentrantly,
11496 // which panics if we're on the stack.
11497 cx.window_context().defer(move |cx| {
11498 workspace.update(cx, |workspace, cx| {
11499 let pane = if split {
11500 workspace.adjacent_pane(cx)
11501 } else {
11502 workspace.active_pane().clone()
11503 };
11504
11505 for (buffer, ranges) in new_selections_by_buffer {
11506 let editor =
11507 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11508 editor.update(cx, |editor, cx| {
11509 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11510 s.select_ranges(ranges);
11511 });
11512 });
11513 }
11514 })
11515 });
11516 }
11517
11518 fn jump(
11519 &mut self,
11520 path: ProjectPath,
11521 position: Point,
11522 anchor: language::Anchor,
11523 offset_from_top: u32,
11524 cx: &mut ViewContext<Self>,
11525 ) {
11526 let workspace = self.workspace();
11527 cx.spawn(|_, mut cx| async move {
11528 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11529 let editor = workspace.update(&mut cx, |workspace, cx| {
11530 // Reset the preview item id before opening the new item
11531 workspace.active_pane().update(cx, |pane, cx| {
11532 pane.set_preview_item_id(None, cx);
11533 });
11534 workspace.open_path_preview(path, None, true, true, cx)
11535 })?;
11536 let editor = editor
11537 .await?
11538 .downcast::<Editor>()
11539 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11540 .downgrade();
11541 editor.update(&mut cx, |editor, cx| {
11542 let buffer = editor
11543 .buffer()
11544 .read(cx)
11545 .as_singleton()
11546 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11547 let buffer = buffer.read(cx);
11548 let cursor = if buffer.can_resolve(&anchor) {
11549 language::ToPoint::to_point(&anchor, buffer)
11550 } else {
11551 buffer.clip_point(position, Bias::Left)
11552 };
11553
11554 let nav_history = editor.nav_history.take();
11555 editor.change_selections(
11556 Some(Autoscroll::top_relative(offset_from_top as usize)),
11557 cx,
11558 |s| {
11559 s.select_ranges([cursor..cursor]);
11560 },
11561 );
11562 editor.nav_history = nav_history;
11563
11564 anyhow::Ok(())
11565 })??;
11566
11567 anyhow::Ok(())
11568 })
11569 .detach_and_log_err(cx);
11570 }
11571
11572 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11573 let snapshot = self.buffer.read(cx).read(cx);
11574 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11575 Some(
11576 ranges
11577 .iter()
11578 .map(move |range| {
11579 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11580 })
11581 .collect(),
11582 )
11583 }
11584
11585 fn selection_replacement_ranges(
11586 &self,
11587 range: Range<OffsetUtf16>,
11588 cx: &AppContext,
11589 ) -> Vec<Range<OffsetUtf16>> {
11590 let selections = self.selections.all::<OffsetUtf16>(cx);
11591 let newest_selection = selections
11592 .iter()
11593 .max_by_key(|selection| selection.id)
11594 .unwrap();
11595 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
11596 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
11597 let snapshot = self.buffer.read(cx).read(cx);
11598 selections
11599 .into_iter()
11600 .map(|mut selection| {
11601 selection.start.0 =
11602 (selection.start.0 as isize).saturating_add(start_delta) as usize;
11603 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
11604 snapshot.clip_offset_utf16(selection.start, Bias::Left)
11605 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
11606 })
11607 .collect()
11608 }
11609
11610 fn report_editor_event(
11611 &self,
11612 operation: &'static str,
11613 file_extension: Option<String>,
11614 cx: &AppContext,
11615 ) {
11616 if cfg!(any(test, feature = "test-support")) {
11617 return;
11618 }
11619
11620 let Some(project) = &self.project else { return };
11621
11622 // If None, we are in a file without an extension
11623 let file = self
11624 .buffer
11625 .read(cx)
11626 .as_singleton()
11627 .and_then(|b| b.read(cx).file());
11628 let file_extension = file_extension.or(file
11629 .as_ref()
11630 .and_then(|file| Path::new(file.file_name(cx)).extension())
11631 .and_then(|e| e.to_str())
11632 .map(|a| a.to_string()));
11633
11634 let vim_mode = cx
11635 .global::<SettingsStore>()
11636 .raw_user_settings()
11637 .get("vim_mode")
11638 == Some(&serde_json::Value::Bool(true));
11639
11640 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
11641 == language::language_settings::InlineCompletionProvider::Copilot;
11642 let copilot_enabled_for_language = self
11643 .buffer
11644 .read(cx)
11645 .settings_at(0, cx)
11646 .show_inline_completions;
11647
11648 let telemetry = project.read(cx).client().telemetry().clone();
11649 telemetry.report_editor_event(
11650 file_extension,
11651 vim_mode,
11652 operation,
11653 copilot_enabled,
11654 copilot_enabled_for_language,
11655 )
11656 }
11657
11658 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
11659 /// with each line being an array of {text, highlight} objects.
11660 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
11661 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
11662 return;
11663 };
11664
11665 #[derive(Serialize)]
11666 struct Chunk<'a> {
11667 text: String,
11668 highlight: Option<&'a str>,
11669 }
11670
11671 let snapshot = buffer.read(cx).snapshot();
11672 let range = self
11673 .selected_text_range(cx)
11674 .and_then(|selected_range| {
11675 if selected_range.is_empty() {
11676 None
11677 } else {
11678 Some(selected_range)
11679 }
11680 })
11681 .unwrap_or_else(|| 0..snapshot.len());
11682
11683 let chunks = snapshot.chunks(range, true);
11684 let mut lines = Vec::new();
11685 let mut line: VecDeque<Chunk> = VecDeque::new();
11686
11687 let Some(style) = self.style.as_ref() else {
11688 return;
11689 };
11690
11691 for chunk in chunks {
11692 let highlight = chunk
11693 .syntax_highlight_id
11694 .and_then(|id| id.name(&style.syntax));
11695 let mut chunk_lines = chunk.text.split('\n').peekable();
11696 while let Some(text) = chunk_lines.next() {
11697 let mut merged_with_last_token = false;
11698 if let Some(last_token) = line.back_mut() {
11699 if last_token.highlight == highlight {
11700 last_token.text.push_str(text);
11701 merged_with_last_token = true;
11702 }
11703 }
11704
11705 if !merged_with_last_token {
11706 line.push_back(Chunk {
11707 text: text.into(),
11708 highlight,
11709 });
11710 }
11711
11712 if chunk_lines.peek().is_some() {
11713 if line.len() > 1 && line.front().unwrap().text.is_empty() {
11714 line.pop_front();
11715 }
11716 if line.len() > 1 && line.back().unwrap().text.is_empty() {
11717 line.pop_back();
11718 }
11719
11720 lines.push(mem::take(&mut line));
11721 }
11722 }
11723 }
11724
11725 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
11726 return;
11727 };
11728 cx.write_to_clipboard(ClipboardItem::new_string(lines));
11729 }
11730
11731 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
11732 &self.inlay_hint_cache
11733 }
11734
11735 pub fn replay_insert_event(
11736 &mut self,
11737 text: &str,
11738 relative_utf16_range: Option<Range<isize>>,
11739 cx: &mut ViewContext<Self>,
11740 ) {
11741 if !self.input_enabled {
11742 cx.emit(EditorEvent::InputIgnored { text: text.into() });
11743 return;
11744 }
11745 if let Some(relative_utf16_range) = relative_utf16_range {
11746 let selections = self.selections.all::<OffsetUtf16>(cx);
11747 self.change_selections(None, cx, |s| {
11748 let new_ranges = selections.into_iter().map(|range| {
11749 let start = OffsetUtf16(
11750 range
11751 .head()
11752 .0
11753 .saturating_add_signed(relative_utf16_range.start),
11754 );
11755 let end = OffsetUtf16(
11756 range
11757 .head()
11758 .0
11759 .saturating_add_signed(relative_utf16_range.end),
11760 );
11761 start..end
11762 });
11763 s.select_ranges(new_ranges);
11764 });
11765 }
11766
11767 self.handle_input(text, cx);
11768 }
11769
11770 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
11771 let Some(project) = self.project.as_ref() else {
11772 return false;
11773 };
11774 let project = project.read(cx);
11775
11776 let mut supports = false;
11777 self.buffer().read(cx).for_each_buffer(|buffer| {
11778 if !supports {
11779 supports = project
11780 .language_servers_for_buffer(buffer.read(cx), cx)
11781 .any(
11782 |(_, server)| match server.capabilities().inlay_hint_provider {
11783 Some(lsp::OneOf::Left(enabled)) => enabled,
11784 Some(lsp::OneOf::Right(_)) => true,
11785 None => false,
11786 },
11787 )
11788 }
11789 });
11790 supports
11791 }
11792
11793 pub fn focus(&self, cx: &mut WindowContext) {
11794 cx.focus(&self.focus_handle)
11795 }
11796
11797 pub fn is_focused(&self, cx: &WindowContext) -> bool {
11798 self.focus_handle.is_focused(cx)
11799 }
11800
11801 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
11802 cx.emit(EditorEvent::Focused);
11803
11804 if let Some(descendant) = self
11805 .last_focused_descendant
11806 .take()
11807 .and_then(|descendant| descendant.upgrade())
11808 {
11809 cx.focus(&descendant);
11810 } else {
11811 if let Some(blame) = self.blame.as_ref() {
11812 blame.update(cx, GitBlame::focus)
11813 }
11814
11815 self.blink_manager.update(cx, BlinkManager::enable);
11816 self.show_cursor_names(cx);
11817 self.buffer.update(cx, |buffer, cx| {
11818 buffer.finalize_last_transaction(cx);
11819 if self.leader_peer_id.is_none() {
11820 buffer.set_active_selections(
11821 &self.selections.disjoint_anchors(),
11822 self.selections.line_mode,
11823 self.cursor_shape,
11824 cx,
11825 );
11826 }
11827 });
11828 }
11829 }
11830
11831 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
11832 cx.emit(EditorEvent::FocusedIn)
11833 }
11834
11835 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
11836 if event.blurred != self.focus_handle {
11837 self.last_focused_descendant = Some(event.blurred);
11838 }
11839 }
11840
11841 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
11842 self.blink_manager.update(cx, BlinkManager::disable);
11843 self.buffer
11844 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
11845
11846 if let Some(blame) = self.blame.as_ref() {
11847 blame.update(cx, GitBlame::blur)
11848 }
11849 if !self.hover_state.focused(cx) {
11850 hide_hover(self, cx);
11851 }
11852
11853 self.hide_context_menu(cx);
11854 cx.emit(EditorEvent::Blurred);
11855 cx.notify();
11856 }
11857
11858 pub fn register_action<A: Action>(
11859 &mut self,
11860 listener: impl Fn(&A, &mut WindowContext) + 'static,
11861 ) -> Subscription {
11862 let id = self.next_editor_action_id.post_inc();
11863 let listener = Arc::new(listener);
11864 self.editor_actions.borrow_mut().insert(
11865 id,
11866 Box::new(move |cx| {
11867 let _view = cx.view().clone();
11868 let cx = cx.window_context();
11869 let listener = listener.clone();
11870 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
11871 let action = action.downcast_ref().unwrap();
11872 if phase == DispatchPhase::Bubble {
11873 listener(action, cx)
11874 }
11875 })
11876 }),
11877 );
11878
11879 let editor_actions = self.editor_actions.clone();
11880 Subscription::new(move || {
11881 editor_actions.borrow_mut().remove(&id);
11882 })
11883 }
11884
11885 pub fn file_header_size(&self) -> u32 {
11886 self.file_header_size
11887 }
11888
11889 pub fn revert(
11890 &mut self,
11891 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
11892 cx: &mut ViewContext<Self>,
11893 ) {
11894 self.buffer().update(cx, |multi_buffer, cx| {
11895 for (buffer_id, changes) in revert_changes {
11896 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
11897 buffer.update(cx, |buffer, cx| {
11898 buffer.edit(
11899 changes.into_iter().map(|(range, text)| {
11900 (range, text.to_string().map(Arc::<str>::from))
11901 }),
11902 None,
11903 cx,
11904 );
11905 });
11906 }
11907 }
11908 });
11909 self.change_selections(None, cx, |selections| selections.refresh());
11910 }
11911
11912 pub fn to_pixel_point(
11913 &mut self,
11914 source: multi_buffer::Anchor,
11915 editor_snapshot: &EditorSnapshot,
11916 cx: &mut ViewContext<Self>,
11917 ) -> Option<gpui::Point<Pixels>> {
11918 let source_point = source.to_display_point(editor_snapshot);
11919 self.display_to_pixel_point(source_point, editor_snapshot, cx)
11920 }
11921
11922 pub fn display_to_pixel_point(
11923 &mut self,
11924 source: DisplayPoint,
11925 editor_snapshot: &EditorSnapshot,
11926 cx: &mut ViewContext<Self>,
11927 ) -> Option<gpui::Point<Pixels>> {
11928 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
11929 let text_layout_details = self.text_layout_details(cx);
11930 let scroll_top = text_layout_details
11931 .scroll_anchor
11932 .scroll_position(editor_snapshot)
11933 .y;
11934
11935 if source.row().as_f32() < scroll_top.floor() {
11936 return None;
11937 }
11938 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
11939 let source_y = line_height * (source.row().as_f32() - scroll_top);
11940 Some(gpui::Point::new(source_x, source_y))
11941 }
11942
11943 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
11944 let bounds = self.last_bounds?;
11945 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
11946 }
11947
11948 pub fn has_active_completions_menu(&self) -> bool {
11949 self.context_menu.read().as_ref().map_or(false, |menu| {
11950 menu.visible() && matches!(menu, ContextMenu::Completions(_))
11951 })
11952 }
11953}
11954
11955fn hunks_for_selections(
11956 multi_buffer_snapshot: &MultiBufferSnapshot,
11957 selections: &[Selection<Anchor>],
11958) -> Vec<DiffHunk<MultiBufferRow>> {
11959 let buffer_rows_for_selections = selections.iter().map(|selection| {
11960 let head = selection.head();
11961 let tail = selection.tail();
11962 let start = MultiBufferRow(tail.to_point(&multi_buffer_snapshot).row);
11963 let end = MultiBufferRow(head.to_point(&multi_buffer_snapshot).row);
11964 if start > end {
11965 end..start
11966 } else {
11967 start..end
11968 }
11969 });
11970
11971 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
11972}
11973
11974pub fn hunks_for_rows(
11975 rows: impl Iterator<Item = Range<MultiBufferRow>>,
11976 multi_buffer_snapshot: &MultiBufferSnapshot,
11977) -> Vec<DiffHunk<MultiBufferRow>> {
11978 let mut hunks = Vec::new();
11979 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
11980 HashMap::default();
11981 for selected_multi_buffer_rows in rows {
11982 let query_rows =
11983 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
11984 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
11985 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
11986 // when the caret is just above or just below the deleted hunk.
11987 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
11988 let related_to_selection = if allow_adjacent {
11989 hunk.associated_range.overlaps(&query_rows)
11990 || hunk.associated_range.start == query_rows.end
11991 || hunk.associated_range.end == query_rows.start
11992 } else {
11993 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
11994 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
11995 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
11996 || selected_multi_buffer_rows.end == hunk.associated_range.start
11997 };
11998 if related_to_selection {
11999 if !processed_buffer_rows
12000 .entry(hunk.buffer_id)
12001 .or_default()
12002 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12003 {
12004 continue;
12005 }
12006 hunks.push(hunk);
12007 }
12008 }
12009 }
12010
12011 hunks
12012}
12013
12014pub trait CollaborationHub {
12015 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12016 fn user_participant_indices<'a>(
12017 &self,
12018 cx: &'a AppContext,
12019 ) -> &'a HashMap<u64, ParticipantIndex>;
12020 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12021}
12022
12023impl CollaborationHub for Model<Project> {
12024 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12025 self.read(cx).collaborators()
12026 }
12027
12028 fn user_participant_indices<'a>(
12029 &self,
12030 cx: &'a AppContext,
12031 ) -> &'a HashMap<u64, ParticipantIndex> {
12032 self.read(cx).user_store().read(cx).participant_indices()
12033 }
12034
12035 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12036 let this = self.read(cx);
12037 let user_ids = this.collaborators().values().map(|c| c.user_id);
12038 this.user_store().read_with(cx, |user_store, cx| {
12039 user_store.participant_names(user_ids, cx)
12040 })
12041 }
12042}
12043
12044pub trait CompletionProvider {
12045 fn completions(
12046 &self,
12047 buffer: &Model<Buffer>,
12048 buffer_position: text::Anchor,
12049 trigger: CompletionContext,
12050 cx: &mut ViewContext<Editor>,
12051 ) -> Task<Result<Vec<Completion>>>;
12052
12053 fn resolve_completions(
12054 &self,
12055 buffer: Model<Buffer>,
12056 completion_indices: Vec<usize>,
12057 completions: Arc<RwLock<Box<[Completion]>>>,
12058 cx: &mut ViewContext<Editor>,
12059 ) -> Task<Result<bool>>;
12060
12061 fn apply_additional_edits_for_completion(
12062 &self,
12063 buffer: Model<Buffer>,
12064 completion: Completion,
12065 push_to_history: bool,
12066 cx: &mut ViewContext<Editor>,
12067 ) -> Task<Result<Option<language::Transaction>>>;
12068
12069 fn is_completion_trigger(
12070 &self,
12071 buffer: &Model<Buffer>,
12072 position: language::Anchor,
12073 text: &str,
12074 trigger_in_words: bool,
12075 cx: &mut ViewContext<Editor>,
12076 ) -> bool;
12077
12078 fn sort_completions(&self) -> bool {
12079 true
12080 }
12081}
12082
12083fn snippet_completions(
12084 project: &Project,
12085 buffer: &Model<Buffer>,
12086 buffer_position: text::Anchor,
12087 cx: &mut AppContext,
12088) -> Vec<Completion> {
12089 let language = buffer.read(cx).language_at(buffer_position);
12090 let language_name = language.as_ref().map(|language| language.lsp_id());
12091 let snippet_store = project.snippets().read(cx);
12092 let snippets = snippet_store.snippets_for(language_name, cx);
12093
12094 if snippets.is_empty() {
12095 return vec![];
12096 }
12097 let snapshot = buffer.read(cx).text_snapshot();
12098 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12099
12100 let mut lines = chunks.lines();
12101 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12102 return vec![];
12103 };
12104
12105 let scope = language.map(|language| language.default_scope());
12106 let mut last_word = line_at
12107 .chars()
12108 .rev()
12109 .take_while(|c| char_kind(&scope, *c) == CharKind::Word)
12110 .collect::<String>();
12111 last_word = last_word.chars().rev().collect();
12112 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12113 let to_lsp = |point: &text::Anchor| {
12114 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12115 point_to_lsp(end)
12116 };
12117 let lsp_end = to_lsp(&buffer_position);
12118 snippets
12119 .into_iter()
12120 .filter_map(|snippet| {
12121 let matching_prefix = snippet
12122 .prefix
12123 .iter()
12124 .find(|prefix| prefix.starts_with(&last_word))?;
12125 let start = as_offset - last_word.len();
12126 let start = snapshot.anchor_before(start);
12127 let range = start..buffer_position;
12128 let lsp_start = to_lsp(&start);
12129 let lsp_range = lsp::Range {
12130 start: lsp_start,
12131 end: lsp_end,
12132 };
12133 Some(Completion {
12134 old_range: range,
12135 new_text: snippet.body.clone(),
12136 label: CodeLabel {
12137 text: matching_prefix.clone(),
12138 runs: vec![],
12139 filter_range: 0..matching_prefix.len(),
12140 },
12141 server_id: LanguageServerId(usize::MAX),
12142 documentation: snippet
12143 .description
12144 .clone()
12145 .map(|description| Documentation::SingleLine(description)),
12146 lsp_completion: lsp::CompletionItem {
12147 label: snippet.prefix.first().unwrap().clone(),
12148 kind: Some(CompletionItemKind::SNIPPET),
12149 label_details: snippet.description.as_ref().map(|description| {
12150 lsp::CompletionItemLabelDetails {
12151 detail: Some(description.clone()),
12152 description: None,
12153 }
12154 }),
12155 insert_text_format: Some(InsertTextFormat::SNIPPET),
12156 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12157 lsp::InsertReplaceEdit {
12158 new_text: snippet.body.clone(),
12159 insert: lsp_range,
12160 replace: lsp_range,
12161 },
12162 )),
12163 filter_text: Some(snippet.body.clone()),
12164 sort_text: Some(char::MAX.to_string()),
12165 ..Default::default()
12166 },
12167 confirm: None,
12168 })
12169 })
12170 .collect()
12171}
12172
12173impl CompletionProvider for Model<Project> {
12174 fn completions(
12175 &self,
12176 buffer: &Model<Buffer>,
12177 buffer_position: text::Anchor,
12178 options: CompletionContext,
12179 cx: &mut ViewContext<Editor>,
12180 ) -> Task<Result<Vec<Completion>>> {
12181 self.update(cx, |project, cx| {
12182 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12183 let project_completions = project.completions(&buffer, buffer_position, options, cx);
12184 cx.background_executor().spawn(async move {
12185 let mut completions = project_completions.await?;
12186 //let snippets = snippets.into_iter().;
12187 completions.extend(snippets);
12188 Ok(completions)
12189 })
12190 })
12191 }
12192
12193 fn resolve_completions(
12194 &self,
12195 buffer: Model<Buffer>,
12196 completion_indices: Vec<usize>,
12197 completions: Arc<RwLock<Box<[Completion]>>>,
12198 cx: &mut ViewContext<Editor>,
12199 ) -> Task<Result<bool>> {
12200 self.update(cx, |project, cx| {
12201 project.resolve_completions(buffer, completion_indices, completions, cx)
12202 })
12203 }
12204
12205 fn apply_additional_edits_for_completion(
12206 &self,
12207 buffer: Model<Buffer>,
12208 completion: Completion,
12209 push_to_history: bool,
12210 cx: &mut ViewContext<Editor>,
12211 ) -> Task<Result<Option<language::Transaction>>> {
12212 self.update(cx, |project, cx| {
12213 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12214 })
12215 }
12216
12217 fn is_completion_trigger(
12218 &self,
12219 buffer: &Model<Buffer>,
12220 position: language::Anchor,
12221 text: &str,
12222 trigger_in_words: bool,
12223 cx: &mut ViewContext<Editor>,
12224 ) -> bool {
12225 if !EditorSettings::get_global(cx).show_completions_on_input {
12226 return false;
12227 }
12228
12229 let mut chars = text.chars();
12230 let char = if let Some(char) = chars.next() {
12231 char
12232 } else {
12233 return false;
12234 };
12235 if chars.next().is_some() {
12236 return false;
12237 }
12238
12239 let buffer = buffer.read(cx);
12240 let scope = buffer.snapshot().language_scope_at(position);
12241 if trigger_in_words && char_kind(&scope, char) == CharKind::Word {
12242 return true;
12243 }
12244
12245 buffer
12246 .completion_triggers()
12247 .iter()
12248 .any(|string| string == text)
12249 }
12250}
12251
12252fn inlay_hint_settings(
12253 location: Anchor,
12254 snapshot: &MultiBufferSnapshot,
12255 cx: &mut ViewContext<'_, Editor>,
12256) -> InlayHintSettings {
12257 let file = snapshot.file_at(location);
12258 let language = snapshot.language_at(location);
12259 let settings = all_language_settings(file, cx);
12260 settings
12261 .language(language.map(|l| l.name()).as_deref())
12262 .inlay_hints
12263}
12264
12265fn consume_contiguous_rows(
12266 contiguous_row_selections: &mut Vec<Selection<Point>>,
12267 selection: &Selection<Point>,
12268 display_map: &DisplaySnapshot,
12269 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12270) -> (MultiBufferRow, MultiBufferRow) {
12271 contiguous_row_selections.push(selection.clone());
12272 let start_row = MultiBufferRow(selection.start.row);
12273 let mut end_row = ending_row(selection, display_map);
12274
12275 while let Some(next_selection) = selections.peek() {
12276 if next_selection.start.row <= end_row.0 {
12277 end_row = ending_row(next_selection, display_map);
12278 contiguous_row_selections.push(selections.next().unwrap().clone());
12279 } else {
12280 break;
12281 }
12282 }
12283 (start_row, end_row)
12284}
12285
12286fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12287 if next_selection.end.column > 0 || next_selection.is_empty() {
12288 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12289 } else {
12290 MultiBufferRow(next_selection.end.row)
12291 }
12292}
12293
12294impl EditorSnapshot {
12295 pub fn remote_selections_in_range<'a>(
12296 &'a self,
12297 range: &'a Range<Anchor>,
12298 collaboration_hub: &dyn CollaborationHub,
12299 cx: &'a AppContext,
12300 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12301 let participant_names = collaboration_hub.user_names(cx);
12302 let participant_indices = collaboration_hub.user_participant_indices(cx);
12303 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12304 let collaborators_by_replica_id = collaborators_by_peer_id
12305 .iter()
12306 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12307 .collect::<HashMap<_, _>>();
12308 self.buffer_snapshot
12309 .selections_in_range(range, false)
12310 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12311 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12312 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12313 let user_name = participant_names.get(&collaborator.user_id).cloned();
12314 Some(RemoteSelection {
12315 replica_id,
12316 selection,
12317 cursor_shape,
12318 line_mode,
12319 participant_index,
12320 peer_id: collaborator.peer_id,
12321 user_name,
12322 })
12323 })
12324 }
12325
12326 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12327 self.display_snapshot.buffer_snapshot.language_at(position)
12328 }
12329
12330 pub fn is_focused(&self) -> bool {
12331 self.is_focused
12332 }
12333
12334 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12335 self.placeholder_text.as_ref()
12336 }
12337
12338 pub fn scroll_position(&self) -> gpui::Point<f32> {
12339 self.scroll_anchor.scroll_position(&self.display_snapshot)
12340 }
12341
12342 fn gutter_dimensions(
12343 &self,
12344 font_id: FontId,
12345 font_size: Pixels,
12346 em_width: Pixels,
12347 max_line_number_width: Pixels,
12348 cx: &AppContext,
12349 ) -> GutterDimensions {
12350 if !self.show_gutter {
12351 return GutterDimensions::default();
12352 }
12353 let descent = cx.text_system().descent(font_id, font_size);
12354
12355 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12356 matches!(
12357 ProjectSettings::get_global(cx).git.git_gutter,
12358 Some(GitGutterSetting::TrackedFiles)
12359 )
12360 });
12361 let gutter_settings = EditorSettings::get_global(cx).gutter;
12362 let show_line_numbers = self
12363 .show_line_numbers
12364 .unwrap_or(gutter_settings.line_numbers);
12365 let line_gutter_width = if show_line_numbers {
12366 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12367 let min_width_for_number_on_gutter = em_width * 4.0;
12368 max_line_number_width.max(min_width_for_number_on_gutter)
12369 } else {
12370 0.0.into()
12371 };
12372
12373 let show_code_actions = self
12374 .show_code_actions
12375 .unwrap_or(gutter_settings.code_actions);
12376
12377 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12378
12379 let git_blame_entries_width = self
12380 .render_git_blame_gutter
12381 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12382
12383 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12384 left_padding += if show_code_actions || show_runnables {
12385 em_width * 3.0
12386 } else if show_git_gutter && show_line_numbers {
12387 em_width * 2.0
12388 } else if show_git_gutter || show_line_numbers {
12389 em_width
12390 } else {
12391 px(0.)
12392 };
12393
12394 let right_padding = if gutter_settings.folds && show_line_numbers {
12395 em_width * 4.0
12396 } else if gutter_settings.folds {
12397 em_width * 3.0
12398 } else if show_line_numbers {
12399 em_width
12400 } else {
12401 px(0.)
12402 };
12403
12404 GutterDimensions {
12405 left_padding,
12406 right_padding,
12407 width: line_gutter_width + left_padding + right_padding,
12408 margin: -descent,
12409 git_blame_entries_width,
12410 }
12411 }
12412
12413 pub fn render_fold_toggle(
12414 &self,
12415 buffer_row: MultiBufferRow,
12416 row_contains_cursor: bool,
12417 editor: View<Editor>,
12418 cx: &mut WindowContext,
12419 ) -> Option<AnyElement> {
12420 let folded = self.is_line_folded(buffer_row);
12421
12422 if let Some(crease) = self
12423 .crease_snapshot
12424 .query_row(buffer_row, &self.buffer_snapshot)
12425 {
12426 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12427 if folded {
12428 editor.update(cx, |editor, cx| {
12429 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12430 });
12431 } else {
12432 editor.update(cx, |editor, cx| {
12433 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12434 });
12435 }
12436 });
12437
12438 Some((crease.render_toggle)(
12439 buffer_row,
12440 folded,
12441 toggle_callback,
12442 cx,
12443 ))
12444 } else if folded
12445 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12446 {
12447 Some(
12448 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12449 .selected(folded)
12450 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12451 if folded {
12452 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12453 } else {
12454 this.fold_at(&FoldAt { buffer_row }, cx);
12455 }
12456 }))
12457 .into_any_element(),
12458 )
12459 } else {
12460 None
12461 }
12462 }
12463
12464 pub fn render_crease_trailer(
12465 &self,
12466 buffer_row: MultiBufferRow,
12467 cx: &mut WindowContext,
12468 ) -> Option<AnyElement> {
12469 let folded = self.is_line_folded(buffer_row);
12470 let crease = self
12471 .crease_snapshot
12472 .query_row(buffer_row, &self.buffer_snapshot)?;
12473 Some((crease.render_trailer)(buffer_row, folded, cx))
12474 }
12475}
12476
12477impl Deref for EditorSnapshot {
12478 type Target = DisplaySnapshot;
12479
12480 fn deref(&self) -> &Self::Target {
12481 &self.display_snapshot
12482 }
12483}
12484
12485#[derive(Clone, Debug, PartialEq, Eq)]
12486pub enum EditorEvent {
12487 InputIgnored {
12488 text: Arc<str>,
12489 },
12490 InputHandled {
12491 utf16_range_to_replace: Option<Range<isize>>,
12492 text: Arc<str>,
12493 },
12494 ExcerptsAdded {
12495 buffer: Model<Buffer>,
12496 predecessor: ExcerptId,
12497 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12498 },
12499 ExcerptsRemoved {
12500 ids: Vec<ExcerptId>,
12501 },
12502 ExcerptsEdited {
12503 ids: Vec<ExcerptId>,
12504 },
12505 ExcerptsExpanded {
12506 ids: Vec<ExcerptId>,
12507 },
12508 BufferEdited,
12509 Edited {
12510 transaction_id: clock::Lamport,
12511 },
12512 Reparsed(BufferId),
12513 Focused,
12514 FocusedIn,
12515 Blurred,
12516 DirtyChanged,
12517 Saved,
12518 TitleChanged,
12519 DiffBaseChanged,
12520 SelectionsChanged {
12521 local: bool,
12522 },
12523 ScrollPositionChanged {
12524 local: bool,
12525 autoscroll: bool,
12526 },
12527 Closed,
12528 TransactionUndone {
12529 transaction_id: clock::Lamport,
12530 },
12531 TransactionBegun {
12532 transaction_id: clock::Lamport,
12533 },
12534}
12535
12536impl EventEmitter<EditorEvent> for Editor {}
12537
12538impl FocusableView for Editor {
12539 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12540 self.focus_handle.clone()
12541 }
12542}
12543
12544impl Render for Editor {
12545 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12546 let settings = ThemeSettings::get_global(cx);
12547
12548 let text_style = match self.mode {
12549 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12550 color: cx.theme().colors().editor_foreground,
12551 font_family: settings.ui_font.family.clone(),
12552 font_features: settings.ui_font.features.clone(),
12553 font_fallbacks: settings.ui_font.fallbacks.clone(),
12554 font_size: rems(0.875).into(),
12555 font_weight: settings.ui_font.weight,
12556 line_height: relative(settings.buffer_line_height.value()),
12557 ..Default::default()
12558 },
12559 EditorMode::Full => TextStyle {
12560 color: cx.theme().colors().editor_foreground,
12561 font_family: settings.buffer_font.family.clone(),
12562 font_features: settings.buffer_font.features.clone(),
12563 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12564 font_size: settings.buffer_font_size(cx).into(),
12565 font_weight: settings.buffer_font.weight,
12566 line_height: relative(settings.buffer_line_height.value()),
12567 ..Default::default()
12568 },
12569 };
12570
12571 let background = match self.mode {
12572 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12573 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12574 EditorMode::Full => cx.theme().colors().editor_background,
12575 };
12576
12577 EditorElement::new(
12578 cx.view(),
12579 EditorStyle {
12580 background,
12581 local_player: cx.theme().players().local(),
12582 text: text_style,
12583 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
12584 syntax: cx.theme().syntax().clone(),
12585 status: cx.theme().status().clone(),
12586 inlay_hints_style: HighlightStyle {
12587 color: Some(cx.theme().status().hint),
12588 ..HighlightStyle::default()
12589 },
12590 suggestions_style: HighlightStyle {
12591 color: Some(cx.theme().status().predictive),
12592 ..HighlightStyle::default()
12593 },
12594 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
12595 },
12596 )
12597 }
12598}
12599
12600impl ViewInputHandler for Editor {
12601 fn text_for_range(
12602 &mut self,
12603 range_utf16: Range<usize>,
12604 cx: &mut ViewContext<Self>,
12605 ) -> Option<String> {
12606 Some(
12607 self.buffer
12608 .read(cx)
12609 .read(cx)
12610 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
12611 .collect(),
12612 )
12613 }
12614
12615 fn selected_text_range(&mut self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12616 // Prevent the IME menu from appearing when holding down an alphabetic key
12617 // while input is disabled.
12618 if !self.input_enabled {
12619 return None;
12620 }
12621
12622 let range = self.selections.newest::<OffsetUtf16>(cx).range();
12623 Some(range.start.0..range.end.0)
12624 }
12625
12626 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
12627 let snapshot = self.buffer.read(cx).read(cx);
12628 let range = self.text_highlights::<InputComposition>(cx)?.1.get(0)?;
12629 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
12630 }
12631
12632 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
12633 self.clear_highlights::<InputComposition>(cx);
12634 self.ime_transaction.take();
12635 }
12636
12637 fn replace_text_in_range(
12638 &mut self,
12639 range_utf16: Option<Range<usize>>,
12640 text: &str,
12641 cx: &mut ViewContext<Self>,
12642 ) {
12643 if !self.input_enabled {
12644 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12645 return;
12646 }
12647
12648 self.transact(cx, |this, cx| {
12649 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
12650 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12651 Some(this.selection_replacement_ranges(range_utf16, cx))
12652 } else {
12653 this.marked_text_ranges(cx)
12654 };
12655
12656 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
12657 let newest_selection_id = this.selections.newest_anchor().id;
12658 this.selections
12659 .all::<OffsetUtf16>(cx)
12660 .iter()
12661 .zip(ranges_to_replace.iter())
12662 .find_map(|(selection, range)| {
12663 if selection.id == newest_selection_id {
12664 Some(
12665 (range.start.0 as isize - selection.head().0 as isize)
12666 ..(range.end.0 as isize - selection.head().0 as isize),
12667 )
12668 } else {
12669 None
12670 }
12671 })
12672 });
12673
12674 cx.emit(EditorEvent::InputHandled {
12675 utf16_range_to_replace: range_to_replace,
12676 text: text.into(),
12677 });
12678
12679 if let Some(new_selected_ranges) = new_selected_ranges {
12680 this.change_selections(None, cx, |selections| {
12681 selections.select_ranges(new_selected_ranges)
12682 });
12683 this.backspace(&Default::default(), cx);
12684 }
12685
12686 this.handle_input(text, cx);
12687 });
12688
12689 if let Some(transaction) = self.ime_transaction {
12690 self.buffer.update(cx, |buffer, cx| {
12691 buffer.group_until_transaction(transaction, cx);
12692 });
12693 }
12694
12695 self.unmark_text(cx);
12696 }
12697
12698 fn replace_and_mark_text_in_range(
12699 &mut self,
12700 range_utf16: Option<Range<usize>>,
12701 text: &str,
12702 new_selected_range_utf16: Option<Range<usize>>,
12703 cx: &mut ViewContext<Self>,
12704 ) {
12705 if !self.input_enabled {
12706 return;
12707 }
12708
12709 let transaction = self.transact(cx, |this, cx| {
12710 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
12711 let snapshot = this.buffer.read(cx).read(cx);
12712 if let Some(relative_range_utf16) = range_utf16.as_ref() {
12713 for marked_range in &mut marked_ranges {
12714 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
12715 marked_range.start.0 += relative_range_utf16.start;
12716 marked_range.start =
12717 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
12718 marked_range.end =
12719 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
12720 }
12721 }
12722 Some(marked_ranges)
12723 } else if let Some(range_utf16) = range_utf16 {
12724 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
12725 Some(this.selection_replacement_ranges(range_utf16, cx))
12726 } else {
12727 None
12728 };
12729
12730 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
12731 let newest_selection_id = this.selections.newest_anchor().id;
12732 this.selections
12733 .all::<OffsetUtf16>(cx)
12734 .iter()
12735 .zip(ranges_to_replace.iter())
12736 .find_map(|(selection, range)| {
12737 if selection.id == newest_selection_id {
12738 Some(
12739 (range.start.0 as isize - selection.head().0 as isize)
12740 ..(range.end.0 as isize - selection.head().0 as isize),
12741 )
12742 } else {
12743 None
12744 }
12745 })
12746 });
12747
12748 cx.emit(EditorEvent::InputHandled {
12749 utf16_range_to_replace: range_to_replace,
12750 text: text.into(),
12751 });
12752
12753 if let Some(ranges) = ranges_to_replace {
12754 this.change_selections(None, cx, |s| s.select_ranges(ranges));
12755 }
12756
12757 let marked_ranges = {
12758 let snapshot = this.buffer.read(cx).read(cx);
12759 this.selections
12760 .disjoint_anchors()
12761 .iter()
12762 .map(|selection| {
12763 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
12764 })
12765 .collect::<Vec<_>>()
12766 };
12767
12768 if text.is_empty() {
12769 this.unmark_text(cx);
12770 } else {
12771 this.highlight_text::<InputComposition>(
12772 marked_ranges.clone(),
12773 HighlightStyle {
12774 underline: Some(UnderlineStyle {
12775 thickness: px(1.),
12776 color: None,
12777 wavy: false,
12778 }),
12779 ..Default::default()
12780 },
12781 cx,
12782 );
12783 }
12784
12785 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
12786 let use_autoclose = this.use_autoclose;
12787 let use_auto_surround = this.use_auto_surround;
12788 this.set_use_autoclose(false);
12789 this.set_use_auto_surround(false);
12790 this.handle_input(text, cx);
12791 this.set_use_autoclose(use_autoclose);
12792 this.set_use_auto_surround(use_auto_surround);
12793
12794 if let Some(new_selected_range) = new_selected_range_utf16 {
12795 let snapshot = this.buffer.read(cx).read(cx);
12796 let new_selected_ranges = marked_ranges
12797 .into_iter()
12798 .map(|marked_range| {
12799 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
12800 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
12801 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
12802 snapshot.clip_offset_utf16(new_start, Bias::Left)
12803 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
12804 })
12805 .collect::<Vec<_>>();
12806
12807 drop(snapshot);
12808 this.change_selections(None, cx, |selections| {
12809 selections.select_ranges(new_selected_ranges)
12810 });
12811 }
12812 });
12813
12814 self.ime_transaction = self.ime_transaction.or(transaction);
12815 if let Some(transaction) = self.ime_transaction {
12816 self.buffer.update(cx, |buffer, cx| {
12817 buffer.group_until_transaction(transaction, cx);
12818 });
12819 }
12820
12821 if self.text_highlights::<InputComposition>(cx).is_none() {
12822 self.ime_transaction.take();
12823 }
12824 }
12825
12826 fn bounds_for_range(
12827 &mut self,
12828 range_utf16: Range<usize>,
12829 element_bounds: gpui::Bounds<Pixels>,
12830 cx: &mut ViewContext<Self>,
12831 ) -> Option<gpui::Bounds<Pixels>> {
12832 let text_layout_details = self.text_layout_details(cx);
12833 let style = &text_layout_details.editor_style;
12834 let font_id = cx.text_system().resolve_font(&style.text.font());
12835 let font_size = style.text.font_size.to_pixels(cx.rem_size());
12836 let line_height = style.text.line_height_in_pixels(cx.rem_size());
12837
12838 let em_width = cx
12839 .text_system()
12840 .typographic_bounds(font_id, font_size, 'm')
12841 .unwrap()
12842 .size
12843 .width;
12844
12845 let snapshot = self.snapshot(cx);
12846 let scroll_position = snapshot.scroll_position();
12847 let scroll_left = scroll_position.x * em_width;
12848
12849 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
12850 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
12851 + self.gutter_dimensions.width;
12852 let y = line_height * (start.row().as_f32() - scroll_position.y);
12853
12854 Some(Bounds {
12855 origin: element_bounds.origin + point(x, y),
12856 size: size(em_width, line_height),
12857 })
12858 }
12859}
12860
12861trait SelectionExt {
12862 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
12863 fn spanned_rows(
12864 &self,
12865 include_end_if_at_line_start: bool,
12866 map: &DisplaySnapshot,
12867 ) -> Range<MultiBufferRow>;
12868}
12869
12870impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
12871 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
12872 let start = self
12873 .start
12874 .to_point(&map.buffer_snapshot)
12875 .to_display_point(map);
12876 let end = self
12877 .end
12878 .to_point(&map.buffer_snapshot)
12879 .to_display_point(map);
12880 if self.reversed {
12881 end..start
12882 } else {
12883 start..end
12884 }
12885 }
12886
12887 fn spanned_rows(
12888 &self,
12889 include_end_if_at_line_start: bool,
12890 map: &DisplaySnapshot,
12891 ) -> Range<MultiBufferRow> {
12892 let start = self.start.to_point(&map.buffer_snapshot);
12893 let mut end = self.end.to_point(&map.buffer_snapshot);
12894 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
12895 end.row -= 1;
12896 }
12897
12898 let buffer_start = map.prev_line_boundary(start).0;
12899 let buffer_end = map.next_line_boundary(end).0;
12900 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
12901 }
12902}
12903
12904impl<T: InvalidationRegion> InvalidationStack<T> {
12905 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
12906 where
12907 S: Clone + ToOffset,
12908 {
12909 while let Some(region) = self.last() {
12910 let all_selections_inside_invalidation_ranges =
12911 if selections.len() == region.ranges().len() {
12912 selections
12913 .iter()
12914 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
12915 .all(|(selection, invalidation_range)| {
12916 let head = selection.head().to_offset(buffer);
12917 invalidation_range.start <= head && invalidation_range.end >= head
12918 })
12919 } else {
12920 false
12921 };
12922
12923 if all_selections_inside_invalidation_ranges {
12924 break;
12925 } else {
12926 self.pop();
12927 }
12928 }
12929 }
12930}
12931
12932impl<T> Default for InvalidationStack<T> {
12933 fn default() -> Self {
12934 Self(Default::default())
12935 }
12936}
12937
12938impl<T> Deref for InvalidationStack<T> {
12939 type Target = Vec<T>;
12940
12941 fn deref(&self) -> &Self::Target {
12942 &self.0
12943 }
12944}
12945
12946impl<T> DerefMut for InvalidationStack<T> {
12947 fn deref_mut(&mut self) -> &mut Self::Target {
12948 &mut self.0
12949 }
12950}
12951
12952impl InvalidationRegion for SnippetState {
12953 fn ranges(&self) -> &[Range<Anchor>] {
12954 &self.ranges[self.active_index]
12955 }
12956}
12957
12958pub fn diagnostic_block_renderer(
12959 diagnostic: Diagnostic,
12960 max_message_rows: Option<u8>,
12961 allow_closing: bool,
12962 _is_valid: bool,
12963) -> RenderBlock {
12964 let (text_without_backticks, code_ranges) =
12965 highlight_diagnostic_message(&diagnostic, max_message_rows);
12966
12967 Box::new(move |cx: &mut BlockContext| {
12968 let group_id: SharedString = cx.block_id.to_string().into();
12969
12970 let mut text_style = cx.text_style().clone();
12971 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
12972 let theme_settings = ThemeSettings::get_global(cx);
12973 text_style.font_family = theme_settings.buffer_font.family.clone();
12974 text_style.font_style = theme_settings.buffer_font.style;
12975 text_style.font_features = theme_settings.buffer_font.features.clone();
12976 text_style.font_weight = theme_settings.buffer_font.weight;
12977
12978 let multi_line_diagnostic = diagnostic.message.contains('\n');
12979
12980 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
12981 if multi_line_diagnostic {
12982 v_flex()
12983 } else {
12984 h_flex()
12985 }
12986 .when(allow_closing, |div| {
12987 div.children(diagnostic.is_primary.then(|| {
12988 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
12989 .icon_color(Color::Muted)
12990 .size(ButtonSize::Compact)
12991 .style(ButtonStyle::Transparent)
12992 .visible_on_hover(group_id.clone())
12993 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
12994 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
12995 }))
12996 })
12997 .child(
12998 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
12999 .icon_color(Color::Muted)
13000 .size(ButtonSize::Compact)
13001 .style(ButtonStyle::Transparent)
13002 .visible_on_hover(group_id.clone())
13003 .on_click({
13004 let message = diagnostic.message.clone();
13005 move |_click, cx| {
13006 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13007 }
13008 })
13009 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13010 )
13011 };
13012
13013 let icon_size = buttons(&diagnostic, cx.block_id)
13014 .into_any_element()
13015 .layout_as_root(AvailableSpace::min_size(), cx);
13016
13017 h_flex()
13018 .id(cx.block_id)
13019 .group(group_id.clone())
13020 .relative()
13021 .size_full()
13022 .pl(cx.gutter_dimensions.width)
13023 .w(cx.max_width + cx.gutter_dimensions.width)
13024 .child(
13025 div()
13026 .flex()
13027 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13028 .flex_shrink(),
13029 )
13030 .child(buttons(&diagnostic, cx.block_id))
13031 .child(div().flex().flex_shrink_0().child(
13032 StyledText::new(text_without_backticks.clone()).with_highlights(
13033 &text_style,
13034 code_ranges.iter().map(|range| {
13035 (
13036 range.clone(),
13037 HighlightStyle {
13038 font_weight: Some(FontWeight::BOLD),
13039 ..Default::default()
13040 },
13041 )
13042 }),
13043 ),
13044 ))
13045 .into_any_element()
13046 })
13047}
13048
13049pub fn highlight_diagnostic_message(
13050 diagnostic: &Diagnostic,
13051 mut max_message_rows: Option<u8>,
13052) -> (SharedString, Vec<Range<usize>>) {
13053 let mut text_without_backticks = String::new();
13054 let mut code_ranges = Vec::new();
13055
13056 if let Some(source) = &diagnostic.source {
13057 text_without_backticks.push_str(&source);
13058 code_ranges.push(0..source.len());
13059 text_without_backticks.push_str(": ");
13060 }
13061
13062 let mut prev_offset = 0;
13063 let mut in_code_block = false;
13064 let has_row_limit = max_message_rows.is_some();
13065 let mut newline_indices = diagnostic
13066 .message
13067 .match_indices('\n')
13068 .filter(|_| has_row_limit)
13069 .map(|(ix, _)| ix)
13070 .fuse()
13071 .peekable();
13072
13073 for (quote_ix, _) in diagnostic
13074 .message
13075 .match_indices('`')
13076 .chain([(diagnostic.message.len(), "")])
13077 {
13078 let mut first_newline_ix = None;
13079 let mut last_newline_ix = None;
13080 while let Some(newline_ix) = newline_indices.peek() {
13081 if *newline_ix < quote_ix {
13082 if first_newline_ix.is_none() {
13083 first_newline_ix = Some(*newline_ix);
13084 }
13085 last_newline_ix = Some(*newline_ix);
13086
13087 if let Some(rows_left) = &mut max_message_rows {
13088 if *rows_left == 0 {
13089 break;
13090 } else {
13091 *rows_left -= 1;
13092 }
13093 }
13094 let _ = newline_indices.next();
13095 } else {
13096 break;
13097 }
13098 }
13099 let prev_len = text_without_backticks.len();
13100 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13101 text_without_backticks.push_str(new_text);
13102 if in_code_block {
13103 code_ranges.push(prev_len..text_without_backticks.len());
13104 }
13105 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13106 in_code_block = !in_code_block;
13107 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13108 text_without_backticks.push_str("...");
13109 break;
13110 }
13111 }
13112
13113 (text_without_backticks.into(), code_ranges)
13114}
13115
13116fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13117 match severity {
13118 DiagnosticSeverity::ERROR => colors.error,
13119 DiagnosticSeverity::WARNING => colors.warning,
13120 DiagnosticSeverity::INFORMATION => colors.info,
13121 DiagnosticSeverity::HINT => colors.info,
13122 _ => colors.ignored,
13123 }
13124}
13125
13126pub fn styled_runs_for_code_label<'a>(
13127 label: &'a CodeLabel,
13128 syntax_theme: &'a theme::SyntaxTheme,
13129) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13130 let fade_out = HighlightStyle {
13131 fade_out: Some(0.35),
13132 ..Default::default()
13133 };
13134
13135 let mut prev_end = label.filter_range.end;
13136 label
13137 .runs
13138 .iter()
13139 .enumerate()
13140 .flat_map(move |(ix, (range, highlight_id))| {
13141 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13142 style
13143 } else {
13144 return Default::default();
13145 };
13146 let mut muted_style = style;
13147 muted_style.highlight(fade_out);
13148
13149 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13150 if range.start >= label.filter_range.end {
13151 if range.start > prev_end {
13152 runs.push((prev_end..range.start, fade_out));
13153 }
13154 runs.push((range.clone(), muted_style));
13155 } else if range.end <= label.filter_range.end {
13156 runs.push((range.clone(), style));
13157 } else {
13158 runs.push((range.start..label.filter_range.end, style));
13159 runs.push((label.filter_range.end..range.end, muted_style));
13160 }
13161 prev_end = cmp::max(prev_end, range.end);
13162
13163 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13164 runs.push((prev_end..label.text.len(), fade_out));
13165 }
13166
13167 runs
13168 })
13169}
13170
13171pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13172 let mut prev_index = 0;
13173 let mut prev_codepoint: Option<char> = None;
13174 text.char_indices()
13175 .chain([(text.len(), '\0')])
13176 .filter_map(move |(index, codepoint)| {
13177 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13178 let is_boundary = index == text.len()
13179 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13180 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13181 if is_boundary {
13182 let chunk = &text[prev_index..index];
13183 prev_index = index;
13184 Some(chunk)
13185 } else {
13186 None
13187 }
13188 })
13189}
13190
13191pub trait RangeToAnchorExt: Sized {
13192 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13193
13194 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13195 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13196 anchor_range.start.to_display_point(&snapshot)..anchor_range.end.to_display_point(&snapshot)
13197 }
13198}
13199
13200impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13201 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13202 let start_offset = self.start.to_offset(snapshot);
13203 let end_offset = self.end.to_offset(snapshot);
13204 if start_offset == end_offset {
13205 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13206 } else {
13207 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13208 }
13209 }
13210}
13211
13212pub trait RowExt {
13213 fn as_f32(&self) -> f32;
13214
13215 fn next_row(&self) -> Self;
13216
13217 fn previous_row(&self) -> Self;
13218
13219 fn minus(&self, other: Self) -> u32;
13220}
13221
13222impl RowExt for DisplayRow {
13223 fn as_f32(&self) -> f32 {
13224 self.0 as f32
13225 }
13226
13227 fn next_row(&self) -> Self {
13228 Self(self.0 + 1)
13229 }
13230
13231 fn previous_row(&self) -> Self {
13232 Self(self.0.saturating_sub(1))
13233 }
13234
13235 fn minus(&self, other: Self) -> u32 {
13236 self.0 - other.0
13237 }
13238}
13239
13240impl RowExt for MultiBufferRow {
13241 fn as_f32(&self) -> f32 {
13242 self.0 as f32
13243 }
13244
13245 fn next_row(&self) -> Self {
13246 Self(self.0 + 1)
13247 }
13248
13249 fn previous_row(&self) -> Self {
13250 Self(self.0.saturating_sub(1))
13251 }
13252
13253 fn minus(&self, other: Self) -> u32 {
13254 self.0 - other.0
13255 }
13256}
13257
13258trait RowRangeExt {
13259 type Row;
13260
13261 fn len(&self) -> usize;
13262
13263 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13264}
13265
13266impl RowRangeExt for Range<MultiBufferRow> {
13267 type Row = MultiBufferRow;
13268
13269 fn len(&self) -> usize {
13270 (self.end.0 - self.start.0) as usize
13271 }
13272
13273 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13274 (self.start.0..self.end.0).map(MultiBufferRow)
13275 }
13276}
13277
13278impl RowRangeExt for Range<DisplayRow> {
13279 type Row = DisplayRow;
13280
13281 fn len(&self) -> usize {
13282 (self.end.0 - self.start.0) as usize
13283 }
13284
13285 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13286 (self.start.0..self.end.0).map(DisplayRow)
13287 }
13288}
13289
13290fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13291 if hunk.diff_base_byte_range.is_empty() {
13292 DiffHunkStatus::Added
13293 } else if hunk.associated_range.is_empty() {
13294 DiffHunkStatus::Removed
13295 } else {
13296 DiffHunkStatus::Modified
13297 }
13298}
13299
13300/// If select range has more than one line, we
13301/// just point the cursor to range.start.
13302fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13303 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13304 range
13305 } else {
13306 range.start..range.start
13307 }
13308}