1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31mod inline_completion_provider;
32pub mod items;
33mod linked_editing_ranges;
34mod lsp_ext;
35mod mouse_context_menu;
36pub mod movement;
37mod persistence;
38mod rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45mod signature_help;
46#[cfg(any(test, feature = "test-support"))]
47pub mod test;
48
49use ::git::diff::{DiffHunk, DiffHunkStatus};
50use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
51pub(crate) use actions::*;
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use client::{Collaborator, ParticipantIndex};
56use clock::ReplicaId;
57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
58use convert_case::{Case, Casing};
59use debounced_delay::DebouncedDelay;
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings,
64};
65pub use editor_settings_controls::*;
66use element::LineWithInvisibles;
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::FutureExt;
71use fuzzy::{StringMatch, StringMatchCandidate};
72use git::blame::GitBlame;
73use git::diff_hunk_to_display;
74use gpui::{
75 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
76 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
77 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
78 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
79 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
80 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
81 UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
82 VisualContext, WeakFocusHandle, WeakView, WindowContext,
83};
84use highlight_matching_bracket::refresh_matching_bracket_highlights;
85use hover_popover::{hide_hover, HoverState};
86use hunk_diff::ExpandedHunks;
87pub(crate) use hunk_diff::HoveredHunk;
88use indent_guides::ActiveIndentGuidesState;
89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
90pub use inline_completion_provider::*;
91pub use items::MAX_TAB_TITLE_LEN;
92use itertools::Itertools;
93use language::{
94 language_settings::{self, all_language_settings, InlayHintSettings},
95 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
96 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
97 Point, Selection, SelectionGoal, TransactionId,
98};
99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
100use linked_editing_ranges::refresh_linked_ranges;
101use similar::{ChangeTag, TextDiff};
102use task::{ResolvedTask, TaskTemplate, TaskVariables};
103
104use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
105pub use lsp::CompletionContext;
106use lsp::{
107 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
108 LanguageServerId,
109};
110use mouse_context_menu::MouseContextMenu;
111use movement::TextLayoutDetails;
112pub use multi_buffer::{
113 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
114 ToPoint,
115};
116use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
117use ordered_float::OrderedFloat;
118use parking_lot::{Mutex, RwLock};
119use project::project_settings::{GitGutterSetting, ProjectSettings};
120use project::{
121 CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
122 ProjectTransaction, TaskSourceKind,
123};
124use rand::prelude::*;
125use rpc::{proto::*, ErrorExt};
126use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
127use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
128use serde::{Deserialize, Serialize};
129use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
130use smallvec::SmallVec;
131use snippet::Snippet;
132use std::{
133 any::TypeId,
134 borrow::Cow,
135 cell::RefCell,
136 cmp::{self, Ordering, Reverse},
137 mem,
138 num::NonZeroU32,
139 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
140 path::{Path, PathBuf},
141 rc::Rc,
142 sync::Arc,
143 time::{Duration, Instant},
144};
145pub use sum_tree::Bias;
146use sum_tree::TreeMap;
147use text::{BufferId, OffsetUtf16, Rope};
148use theme::{
149 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
150 ThemeColors, ThemeSettings,
151};
152use ui::{
153 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
154 ListItem, Popover, Tooltip,
155};
156use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
157use workspace::item::{ItemHandle, PreviewTabsSettings};
158use workspace::notifications::{DetachAndPromptErr, NotificationId};
159use workspace::{
160 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
161};
162use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
163
164use crate::hover_links::find_url;
165use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
166
167pub const FILE_HEADER_HEIGHT: u32 = 1;
168pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
169pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
170pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
171const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
172const MAX_LINE_LEN: usize = 1024;
173const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
174const MAX_SELECTION_HISTORY_LEN: usize = 1024;
175pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
176#[doc(hidden)]
177pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
178#[doc(hidden)]
179pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
180
181pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
182pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
183
184pub fn render_parsed_markdown(
185 element_id: impl Into<ElementId>,
186 parsed: &language::ParsedMarkdown,
187 editor_style: &EditorStyle,
188 workspace: Option<WeakView<Workspace>>,
189 cx: &mut WindowContext,
190) -> InteractiveText {
191 let code_span_background_color = cx
192 .theme()
193 .colors()
194 .editor_document_highlight_read_background;
195
196 let highlights = gpui::combine_highlights(
197 parsed.highlights.iter().filter_map(|(range, highlight)| {
198 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
199 Some((range.clone(), highlight))
200 }),
201 parsed
202 .regions
203 .iter()
204 .zip(&parsed.region_ranges)
205 .filter_map(|(region, range)| {
206 if region.code {
207 Some((
208 range.clone(),
209 HighlightStyle {
210 background_color: Some(code_span_background_color),
211 ..Default::default()
212 },
213 ))
214 } else {
215 None
216 }
217 }),
218 );
219
220 let mut links = Vec::new();
221 let mut link_ranges = Vec::new();
222 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
223 if let Some(link) = region.link.clone() {
224 links.push(link);
225 link_ranges.push(range.clone());
226 }
227 }
228
229 InteractiveText::new(
230 element_id,
231 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
232 )
233 .on_click(link_ranges, move |clicked_range_ix, cx| {
234 match &links[clicked_range_ix] {
235 markdown::Link::Web { url } => cx.open_url(url),
236 markdown::Link::Path { path } => {
237 if let Some(workspace) = &workspace {
238 _ = workspace.update(cx, |workspace, cx| {
239 workspace.open_abs_path(path.clone(), false, cx).detach();
240 });
241 }
242 }
243 }
244 })
245}
246
247#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
248pub(crate) enum InlayId {
249 Suggestion(usize),
250 Hint(usize),
251}
252
253impl InlayId {
254 fn id(&self) -> usize {
255 match self {
256 Self::Suggestion(id) => *id,
257 Self::Hint(id) => *id,
258 }
259 }
260}
261
262enum DiffRowHighlight {}
263enum DocumentHighlightRead {}
264enum DocumentHighlightWrite {}
265enum InputComposition {}
266
267#[derive(Copy, Clone, PartialEq, Eq)]
268pub enum Direction {
269 Prev,
270 Next,
271}
272
273#[derive(Debug, Copy, Clone, PartialEq, Eq)]
274pub enum Navigated {
275 Yes,
276 No,
277}
278
279impl Navigated {
280 pub fn from_bool(yes: bool) -> Navigated {
281 if yes {
282 Navigated::Yes
283 } else {
284 Navigated::No
285 }
286 }
287}
288
289pub fn init_settings(cx: &mut AppContext) {
290 EditorSettings::register(cx);
291}
292
293pub fn init(cx: &mut AppContext) {
294 init_settings(cx);
295
296 workspace::register_project_item::<Editor>(cx);
297 workspace::FollowableViewRegistry::register::<Editor>(cx);
298 workspace::register_serializable_item::<Editor>(cx);
299
300 cx.observe_new_views(
301 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
302 workspace.register_action(Editor::new_file);
303 workspace.register_action(Editor::new_file_vertical);
304 workspace.register_action(Editor::new_file_horizontal);
305 },
306 )
307 .detach();
308
309 cx.on_action(move |_: &workspace::NewFile, cx| {
310 let app_state = workspace::AppState::global(cx);
311 if let Some(app_state) = app_state.upgrade() {
312 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
313 Editor::new_file(workspace, &Default::default(), cx)
314 })
315 .detach();
316 }
317 });
318 cx.on_action(move |_: &workspace::NewWindow, cx| {
319 let app_state = workspace::AppState::global(cx);
320 if let Some(app_state) = app_state.upgrade() {
321 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
322 Editor::new_file(workspace, &Default::default(), cx)
323 })
324 .detach();
325 }
326 });
327}
328
329pub struct SearchWithinRange;
330
331trait InvalidationRegion {
332 fn ranges(&self) -> &[Range<Anchor>];
333}
334
335#[derive(Clone, Debug, PartialEq)]
336pub enum SelectPhase {
337 Begin {
338 position: DisplayPoint,
339 add: bool,
340 click_count: usize,
341 },
342 BeginColumnar {
343 position: DisplayPoint,
344 reset: bool,
345 goal_column: u32,
346 },
347 Extend {
348 position: DisplayPoint,
349 click_count: usize,
350 },
351 Update {
352 position: DisplayPoint,
353 goal_column: u32,
354 scroll_delta: gpui::Point<f32>,
355 },
356 End,
357}
358
359#[derive(Clone, Debug)]
360pub enum SelectMode {
361 Character,
362 Word(Range<Anchor>),
363 Line(Range<Anchor>),
364 All,
365}
366
367#[derive(Copy, Clone, PartialEq, Eq, Debug)]
368pub enum EditorMode {
369 SingleLine { auto_width: bool },
370 AutoHeight { max_lines: usize },
371 Full,
372}
373
374#[derive(Clone, Debug)]
375pub enum SoftWrap {
376 None,
377 PreferLine,
378 EditorWidth,
379 Column(u32),
380 Bounded(u32),
381}
382
383#[derive(Clone)]
384pub struct EditorStyle {
385 pub background: Hsla,
386 pub local_player: PlayerColor,
387 pub text: TextStyle,
388 pub scrollbar_width: Pixels,
389 pub syntax: Arc<SyntaxTheme>,
390 pub status: StatusColors,
391 pub inlay_hints_style: HighlightStyle,
392 pub suggestions_style: HighlightStyle,
393 pub unnecessary_code_fade: f32,
394}
395
396impl Default for EditorStyle {
397 fn default() -> Self {
398 Self {
399 background: Hsla::default(),
400 local_player: PlayerColor::default(),
401 text: TextStyle::default(),
402 scrollbar_width: Pixels::default(),
403 syntax: Default::default(),
404 // HACK: Status colors don't have a real default.
405 // We should look into removing the status colors from the editor
406 // style and retrieve them directly from the theme.
407 status: StatusColors::dark(),
408 inlay_hints_style: HighlightStyle::default(),
409 suggestions_style: HighlightStyle::default(),
410 unnecessary_code_fade: Default::default(),
411 }
412 }
413}
414
415pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
416 let show_background = all_language_settings(None, cx)
417 .language(None)
418 .inlay_hints
419 .show_background;
420
421 HighlightStyle {
422 color: Some(cx.theme().status().hint),
423 background_color: show_background.then(|| cx.theme().status().hint_background),
424 ..HighlightStyle::default()
425 }
426}
427
428type CompletionId = usize;
429
430#[derive(Clone, Debug)]
431struct CompletionState {
432 // render_inlay_ids represents the inlay hints that are inserted
433 // for rendering the inline completions. They may be discontinuous
434 // in the event that the completion provider returns some intersection
435 // with the existing content.
436 render_inlay_ids: Vec<InlayId>,
437 // text is the resulting rope that is inserted when the user accepts a completion.
438 text: Rope,
439 // position is the position of the cursor when the completion was triggered.
440 position: multi_buffer::Anchor,
441 // delete_range is the range of text that this completion state covers.
442 // if the completion is accepted, this range should be deleted.
443 delete_range: Option<Range<multi_buffer::Anchor>>,
444}
445
446#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
447struct EditorActionId(usize);
448
449impl EditorActionId {
450 pub fn post_inc(&mut self) -> Self {
451 let answer = self.0;
452
453 *self = Self(answer + 1);
454
455 Self(answer)
456 }
457}
458
459// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
460// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
461
462type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
463type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
464
465#[derive(Default)]
466struct ScrollbarMarkerState {
467 scrollbar_size: Size<Pixels>,
468 dirty: bool,
469 markers: Arc<[PaintQuad]>,
470 pending_refresh: Option<Task<Result<()>>>,
471}
472
473impl ScrollbarMarkerState {
474 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
475 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
476 }
477}
478
479#[derive(Clone, Debug)]
480struct RunnableTasks {
481 templates: Vec<(TaskSourceKind, TaskTemplate)>,
482 offset: MultiBufferOffset,
483 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
484 column: u32,
485 // Values of all named captures, including those starting with '_'
486 extra_variables: HashMap<String, String>,
487 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
488 context_range: Range<BufferOffset>,
489}
490
491#[derive(Clone)]
492struct ResolvedTasks {
493 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
494 position: Anchor,
495}
496#[derive(Copy, Clone, Debug)]
497struct MultiBufferOffset(usize);
498#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
499struct BufferOffset(usize);
500
501// Addons allow storing per-editor state in other crates (e.g. Vim)
502pub trait Addon: 'static {
503 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
504
505 fn to_any(&self) -> &dyn std::any::Any;
506}
507
508/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
509///
510/// See the [module level documentation](self) for more information.
511pub struct Editor {
512 focus_handle: FocusHandle,
513 last_focused_descendant: Option<WeakFocusHandle>,
514 /// The text buffer being edited
515 buffer: Model<MultiBuffer>,
516 /// Map of how text in the buffer should be displayed.
517 /// Handles soft wraps, folds, fake inlay text insertions, etc.
518 pub display_map: Model<DisplayMap>,
519 pub selections: SelectionsCollection,
520 pub scroll_manager: ScrollManager,
521 /// When inline assist editors are linked, they all render cursors because
522 /// typing enters text into each of them, even the ones that aren't focused.
523 pub(crate) show_cursor_when_unfocused: bool,
524 columnar_selection_tail: Option<Anchor>,
525 add_selections_state: Option<AddSelectionsState>,
526 select_next_state: Option<SelectNextState>,
527 select_prev_state: Option<SelectNextState>,
528 selection_history: SelectionHistory,
529 autoclose_regions: Vec<AutocloseRegion>,
530 snippet_stack: InvalidationStack<SnippetState>,
531 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
532 ime_transaction: Option<TransactionId>,
533 active_diagnostics: Option<ActiveDiagnosticGroup>,
534 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
535 project: Option<Model<Project>>,
536 completion_provider: Option<Box<dyn CompletionProvider>>,
537 collaboration_hub: Option<Box<dyn CollaborationHub>>,
538 blink_manager: Model<BlinkManager>,
539 show_cursor_names: bool,
540 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
541 pub show_local_selections: bool,
542 mode: EditorMode,
543 show_breadcrumbs: bool,
544 show_gutter: bool,
545 show_line_numbers: Option<bool>,
546 use_relative_line_numbers: Option<bool>,
547 show_git_diff_gutter: Option<bool>,
548 show_code_actions: Option<bool>,
549 show_runnables: Option<bool>,
550 show_wrap_guides: Option<bool>,
551 show_indent_guides: Option<bool>,
552 placeholder_text: Option<Arc<str>>,
553 highlight_order: usize,
554 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
555 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
556 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
557 scrollbar_marker_state: ScrollbarMarkerState,
558 active_indent_guides_state: ActiveIndentGuidesState,
559 nav_history: Option<ItemNavHistory>,
560 context_menu: RwLock<Option<ContextMenu>>,
561 mouse_context_menu: Option<MouseContextMenu>,
562 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
563 signature_help_state: SignatureHelpState,
564 auto_signature_help: Option<bool>,
565 find_all_references_task_sources: Vec<Anchor>,
566 next_completion_id: CompletionId,
567 completion_documentation_pre_resolve_debounce: DebouncedDelay,
568 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
569 code_actions_task: Option<Task<()>>,
570 document_highlights_task: Option<Task<()>>,
571 linked_editing_range_task: Option<Task<Option<()>>>,
572 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
573 pending_rename: Option<RenameState>,
574 searchable: bool,
575 cursor_shape: CursorShape,
576 current_line_highlight: Option<CurrentLineHighlight>,
577 collapse_matches: bool,
578 autoindent_mode: Option<AutoindentMode>,
579 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
580 input_enabled: bool,
581 use_modal_editing: bool,
582 read_only: bool,
583 leader_peer_id: Option<PeerId>,
584 remote_id: Option<ViewId>,
585 hover_state: HoverState,
586 gutter_hovered: bool,
587 hovered_link_state: Option<HoveredLinkState>,
588 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
589 active_inline_completion: Option<CompletionState>,
590 // enable_inline_completions is a switch that Vim can use to disable
591 // inline completions based on its mode.
592 enable_inline_completions: bool,
593 show_inline_completions_override: Option<bool>,
594 inlay_hint_cache: InlayHintCache,
595 expanded_hunks: ExpandedHunks,
596 next_inlay_id: usize,
597 _subscriptions: Vec<Subscription>,
598 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
599 gutter_dimensions: GutterDimensions,
600 style: Option<EditorStyle>,
601 next_editor_action_id: EditorActionId,
602 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
603 use_autoclose: bool,
604 use_auto_surround: bool,
605 auto_replace_emoji_shortcode: bool,
606 show_git_blame_gutter: bool,
607 show_git_blame_inline: bool,
608 show_git_blame_inline_delay_task: Option<Task<()>>,
609 git_blame_inline_enabled: bool,
610 serialize_dirty_buffers: bool,
611 show_selection_menu: Option<bool>,
612 blame: Option<Model<GitBlame>>,
613 blame_subscription: Option<Subscription>,
614 custom_context_menu: Option<
615 Box<
616 dyn 'static
617 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
618 >,
619 >,
620 last_bounds: Option<Bounds<Pixels>>,
621 expect_bounds_change: Option<Bounds<Pixels>>,
622 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
623 tasks_update_task: Option<Task<()>>,
624 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
625 file_header_size: u32,
626 breadcrumb_header: Option<String>,
627 focused_block: Option<FocusedBlock>,
628 next_scroll_position: NextScrollCursorCenterTopBottom,
629 addons: HashMap<TypeId, Box<dyn Addon>>,
630 _scroll_cursor_center_top_bottom_task: Task<()>,
631}
632
633#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
634enum NextScrollCursorCenterTopBottom {
635 #[default]
636 Center,
637 Top,
638 Bottom,
639}
640
641impl NextScrollCursorCenterTopBottom {
642 fn next(&self) -> Self {
643 match self {
644 Self::Center => Self::Top,
645 Self::Top => Self::Bottom,
646 Self::Bottom => Self::Center,
647 }
648 }
649}
650
651#[derive(Clone)]
652pub struct EditorSnapshot {
653 pub mode: EditorMode,
654 show_gutter: bool,
655 show_line_numbers: Option<bool>,
656 show_git_diff_gutter: Option<bool>,
657 show_code_actions: Option<bool>,
658 show_runnables: Option<bool>,
659 render_git_blame_gutter: bool,
660 pub display_snapshot: DisplaySnapshot,
661 pub placeholder_text: Option<Arc<str>>,
662 is_focused: bool,
663 scroll_anchor: ScrollAnchor,
664 ongoing_scroll: OngoingScroll,
665 current_line_highlight: CurrentLineHighlight,
666 gutter_hovered: bool,
667}
668
669const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
670
671#[derive(Default, Debug, Clone, Copy)]
672pub struct GutterDimensions {
673 pub left_padding: Pixels,
674 pub right_padding: Pixels,
675 pub width: Pixels,
676 pub margin: Pixels,
677 pub git_blame_entries_width: Option<Pixels>,
678}
679
680impl GutterDimensions {
681 /// The full width of the space taken up by the gutter.
682 pub fn full_width(&self) -> Pixels {
683 self.margin + self.width
684 }
685
686 /// The width of the space reserved for the fold indicators,
687 /// use alongside 'justify_end' and `gutter_width` to
688 /// right align content with the line numbers
689 pub fn fold_area_width(&self) -> Pixels {
690 self.margin + self.right_padding
691 }
692}
693
694#[derive(Debug)]
695pub struct RemoteSelection {
696 pub replica_id: ReplicaId,
697 pub selection: Selection<Anchor>,
698 pub cursor_shape: CursorShape,
699 pub peer_id: PeerId,
700 pub line_mode: bool,
701 pub participant_index: Option<ParticipantIndex>,
702 pub user_name: Option<SharedString>,
703}
704
705#[derive(Clone, Debug)]
706struct SelectionHistoryEntry {
707 selections: Arc<[Selection<Anchor>]>,
708 select_next_state: Option<SelectNextState>,
709 select_prev_state: Option<SelectNextState>,
710 add_selections_state: Option<AddSelectionsState>,
711}
712
713enum SelectionHistoryMode {
714 Normal,
715 Undoing,
716 Redoing,
717}
718
719#[derive(Clone, PartialEq, Eq, Hash)]
720struct HoveredCursor {
721 replica_id: u16,
722 selection_id: usize,
723}
724
725impl Default for SelectionHistoryMode {
726 fn default() -> Self {
727 Self::Normal
728 }
729}
730
731#[derive(Default)]
732struct SelectionHistory {
733 #[allow(clippy::type_complexity)]
734 selections_by_transaction:
735 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
736 mode: SelectionHistoryMode,
737 undo_stack: VecDeque<SelectionHistoryEntry>,
738 redo_stack: VecDeque<SelectionHistoryEntry>,
739}
740
741impl SelectionHistory {
742 fn insert_transaction(
743 &mut self,
744 transaction_id: TransactionId,
745 selections: Arc<[Selection<Anchor>]>,
746 ) {
747 self.selections_by_transaction
748 .insert(transaction_id, (selections, None));
749 }
750
751 #[allow(clippy::type_complexity)]
752 fn transaction(
753 &self,
754 transaction_id: TransactionId,
755 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
756 self.selections_by_transaction.get(&transaction_id)
757 }
758
759 #[allow(clippy::type_complexity)]
760 fn transaction_mut(
761 &mut self,
762 transaction_id: TransactionId,
763 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
764 self.selections_by_transaction.get_mut(&transaction_id)
765 }
766
767 fn push(&mut self, entry: SelectionHistoryEntry) {
768 if !entry.selections.is_empty() {
769 match self.mode {
770 SelectionHistoryMode::Normal => {
771 self.push_undo(entry);
772 self.redo_stack.clear();
773 }
774 SelectionHistoryMode::Undoing => self.push_redo(entry),
775 SelectionHistoryMode::Redoing => self.push_undo(entry),
776 }
777 }
778 }
779
780 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
781 if self
782 .undo_stack
783 .back()
784 .map_or(true, |e| e.selections != entry.selections)
785 {
786 self.undo_stack.push_back(entry);
787 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
788 self.undo_stack.pop_front();
789 }
790 }
791 }
792
793 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
794 if self
795 .redo_stack
796 .back()
797 .map_or(true, |e| e.selections != entry.selections)
798 {
799 self.redo_stack.push_back(entry);
800 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
801 self.redo_stack.pop_front();
802 }
803 }
804 }
805}
806
807struct RowHighlight {
808 index: usize,
809 range: RangeInclusive<Anchor>,
810 color: Option<Hsla>,
811 should_autoscroll: bool,
812}
813
814#[derive(Clone, Debug)]
815struct AddSelectionsState {
816 above: bool,
817 stack: Vec<usize>,
818}
819
820#[derive(Clone)]
821struct SelectNextState {
822 query: AhoCorasick,
823 wordwise: bool,
824 done: bool,
825}
826
827impl std::fmt::Debug for SelectNextState {
828 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
829 f.debug_struct(std::any::type_name::<Self>())
830 .field("wordwise", &self.wordwise)
831 .field("done", &self.done)
832 .finish()
833 }
834}
835
836#[derive(Debug)]
837struct AutocloseRegion {
838 selection_id: usize,
839 range: Range<Anchor>,
840 pair: BracketPair,
841}
842
843#[derive(Debug)]
844struct SnippetState {
845 ranges: Vec<Vec<Range<Anchor>>>,
846 active_index: usize,
847}
848
849#[doc(hidden)]
850pub struct RenameState {
851 pub range: Range<Anchor>,
852 pub old_name: Arc<str>,
853 pub editor: View<Editor>,
854 block_id: CustomBlockId,
855}
856
857struct InvalidationStack<T>(Vec<T>);
858
859struct RegisteredInlineCompletionProvider {
860 provider: Arc<dyn InlineCompletionProviderHandle>,
861 _subscription: Subscription,
862}
863
864enum ContextMenu {
865 Completions(CompletionsMenu),
866 CodeActions(CodeActionsMenu),
867}
868
869impl ContextMenu {
870 fn select_first(
871 &mut self,
872 project: Option<&Model<Project>>,
873 cx: &mut ViewContext<Editor>,
874 ) -> bool {
875 if self.visible() {
876 match self {
877 ContextMenu::Completions(menu) => menu.select_first(project, cx),
878 ContextMenu::CodeActions(menu) => menu.select_first(cx),
879 }
880 true
881 } else {
882 false
883 }
884 }
885
886 fn select_prev(
887 &mut self,
888 project: Option<&Model<Project>>,
889 cx: &mut ViewContext<Editor>,
890 ) -> bool {
891 if self.visible() {
892 match self {
893 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
894 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
895 }
896 true
897 } else {
898 false
899 }
900 }
901
902 fn select_next(
903 &mut self,
904 project: Option<&Model<Project>>,
905 cx: &mut ViewContext<Editor>,
906 ) -> bool {
907 if self.visible() {
908 match self {
909 ContextMenu::Completions(menu) => menu.select_next(project, cx),
910 ContextMenu::CodeActions(menu) => menu.select_next(cx),
911 }
912 true
913 } else {
914 false
915 }
916 }
917
918 fn select_last(
919 &mut self,
920 project: Option<&Model<Project>>,
921 cx: &mut ViewContext<Editor>,
922 ) -> bool {
923 if self.visible() {
924 match self {
925 ContextMenu::Completions(menu) => menu.select_last(project, cx),
926 ContextMenu::CodeActions(menu) => menu.select_last(cx),
927 }
928 true
929 } else {
930 false
931 }
932 }
933
934 fn visible(&self) -> bool {
935 match self {
936 ContextMenu::Completions(menu) => menu.visible(),
937 ContextMenu::CodeActions(menu) => menu.visible(),
938 }
939 }
940
941 fn render(
942 &self,
943 cursor_position: DisplayPoint,
944 style: &EditorStyle,
945 max_height: Pixels,
946 workspace: Option<WeakView<Workspace>>,
947 cx: &mut ViewContext<Editor>,
948 ) -> (ContextMenuOrigin, AnyElement) {
949 match self {
950 ContextMenu::Completions(menu) => (
951 ContextMenuOrigin::EditorPoint(cursor_position),
952 menu.render(style, max_height, workspace, cx),
953 ),
954 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
955 }
956 }
957}
958
959enum ContextMenuOrigin {
960 EditorPoint(DisplayPoint),
961 GutterIndicator(DisplayRow),
962}
963
964#[derive(Clone)]
965struct CompletionsMenu {
966 id: CompletionId,
967 sort_completions: bool,
968 initial_position: Anchor,
969 buffer: Model<Buffer>,
970 completions: Arc<RwLock<Box<[Completion]>>>,
971 match_candidates: Arc<[StringMatchCandidate]>,
972 matches: Arc<[StringMatch]>,
973 selected_item: usize,
974 scroll_handle: UniformListScrollHandle,
975 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
976}
977
978impl CompletionsMenu {
979 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
980 self.selected_item = 0;
981 self.scroll_handle.scroll_to_item(self.selected_item);
982 self.attempt_resolve_selected_completion_documentation(project, cx);
983 cx.notify();
984 }
985
986 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
987 if self.selected_item > 0 {
988 self.selected_item -= 1;
989 } else {
990 self.selected_item = self.matches.len() - 1;
991 }
992 self.scroll_handle.scroll_to_item(self.selected_item);
993 self.attempt_resolve_selected_completion_documentation(project, cx);
994 cx.notify();
995 }
996
997 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
998 if self.selected_item + 1 < self.matches.len() {
999 self.selected_item += 1;
1000 } else {
1001 self.selected_item = 0;
1002 }
1003 self.scroll_handle.scroll_to_item(self.selected_item);
1004 self.attempt_resolve_selected_completion_documentation(project, cx);
1005 cx.notify();
1006 }
1007
1008 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
1009 self.selected_item = self.matches.len() - 1;
1010 self.scroll_handle.scroll_to_item(self.selected_item);
1011 self.attempt_resolve_selected_completion_documentation(project, cx);
1012 cx.notify();
1013 }
1014
1015 fn pre_resolve_completion_documentation(
1016 buffer: Model<Buffer>,
1017 completions: Arc<RwLock<Box<[Completion]>>>,
1018 matches: Arc<[StringMatch]>,
1019 editor: &Editor,
1020 cx: &mut ViewContext<Editor>,
1021 ) -> Task<()> {
1022 let settings = EditorSettings::get_global(cx);
1023 if !settings.show_completion_documentation {
1024 return Task::ready(());
1025 }
1026
1027 let Some(provider) = editor.completion_provider.as_ref() else {
1028 return Task::ready(());
1029 };
1030
1031 let resolve_task = provider.resolve_completions(
1032 buffer,
1033 matches.iter().map(|m| m.candidate_id).collect(),
1034 completions.clone(),
1035 cx,
1036 );
1037
1038 cx.spawn(move |this, mut cx| async move {
1039 if let Some(true) = resolve_task.await.log_err() {
1040 this.update(&mut cx, |_, cx| cx.notify()).ok();
1041 }
1042 })
1043 }
1044
1045 fn attempt_resolve_selected_completion_documentation(
1046 &mut self,
1047 project: Option<&Model<Project>>,
1048 cx: &mut ViewContext<Editor>,
1049 ) {
1050 let settings = EditorSettings::get_global(cx);
1051 if !settings.show_completion_documentation {
1052 return;
1053 }
1054
1055 let completion_index = self.matches[self.selected_item].candidate_id;
1056 let Some(project) = project else {
1057 return;
1058 };
1059
1060 let resolve_task = project.update(cx, |project, cx| {
1061 project.resolve_completions(
1062 self.buffer.clone(),
1063 vec![completion_index],
1064 self.completions.clone(),
1065 cx,
1066 )
1067 });
1068
1069 let delay_ms =
1070 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1071 let delay = Duration::from_millis(delay_ms);
1072
1073 self.selected_completion_documentation_resolve_debounce
1074 .lock()
1075 .fire_new(delay, cx, |_, cx| {
1076 cx.spawn(move |this, mut cx| async move {
1077 if let Some(true) = resolve_task.await.log_err() {
1078 this.update(&mut cx, |_, cx| cx.notify()).ok();
1079 }
1080 })
1081 });
1082 }
1083
1084 fn visible(&self) -> bool {
1085 !self.matches.is_empty()
1086 }
1087
1088 fn render(
1089 &self,
1090 style: &EditorStyle,
1091 max_height: Pixels,
1092 workspace: Option<WeakView<Workspace>>,
1093 cx: &mut ViewContext<Editor>,
1094 ) -> AnyElement {
1095 let settings = EditorSettings::get_global(cx);
1096 let show_completion_documentation = settings.show_completion_documentation;
1097
1098 let widest_completion_ix = self
1099 .matches
1100 .iter()
1101 .enumerate()
1102 .max_by_key(|(_, mat)| {
1103 let completions = self.completions.read();
1104 let completion = &completions[mat.candidate_id];
1105 let documentation = &completion.documentation;
1106
1107 let mut len = completion.label.text.chars().count();
1108 if let Some(Documentation::SingleLine(text)) = documentation {
1109 if show_completion_documentation {
1110 len += text.chars().count();
1111 }
1112 }
1113
1114 len
1115 })
1116 .map(|(ix, _)| ix);
1117
1118 let completions = self.completions.clone();
1119 let matches = self.matches.clone();
1120 let selected_item = self.selected_item;
1121 let style = style.clone();
1122
1123 let multiline_docs = if show_completion_documentation {
1124 let mat = &self.matches[selected_item];
1125 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1126 Some(Documentation::MultiLinePlainText(text)) => {
1127 Some(div().child(SharedString::from(text.clone())))
1128 }
1129 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1130 Some(div().child(render_parsed_markdown(
1131 "completions_markdown",
1132 parsed,
1133 &style,
1134 workspace,
1135 cx,
1136 )))
1137 }
1138 _ => None,
1139 };
1140 multiline_docs.map(|div| {
1141 div.id("multiline_docs")
1142 .max_h(max_height)
1143 .flex_1()
1144 .px_1p5()
1145 .py_1()
1146 .min_w(px(260.))
1147 .max_w(px(640.))
1148 .w(px(500.))
1149 .overflow_y_scroll()
1150 .occlude()
1151 })
1152 } else {
1153 None
1154 };
1155
1156 let list = uniform_list(
1157 cx.view().clone(),
1158 "completions",
1159 matches.len(),
1160 move |_editor, range, cx| {
1161 let start_ix = range.start;
1162 let completions_guard = completions.read();
1163
1164 matches[range]
1165 .iter()
1166 .enumerate()
1167 .map(|(ix, mat)| {
1168 let item_ix = start_ix + ix;
1169 let candidate_id = mat.candidate_id;
1170 let completion = &completions_guard[candidate_id];
1171
1172 let documentation = if show_completion_documentation {
1173 &completion.documentation
1174 } else {
1175 &None
1176 };
1177
1178 let highlights = gpui::combine_highlights(
1179 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1180 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1181 |(range, mut highlight)| {
1182 // Ignore font weight for syntax highlighting, as we'll use it
1183 // for fuzzy matches.
1184 highlight.font_weight = None;
1185
1186 if completion.lsp_completion.deprecated.unwrap_or(false) {
1187 highlight.strikethrough = Some(StrikethroughStyle {
1188 thickness: 1.0.into(),
1189 ..Default::default()
1190 });
1191 highlight.color = Some(cx.theme().colors().text_muted);
1192 }
1193
1194 (range, highlight)
1195 },
1196 ),
1197 );
1198 let completion_label = StyledText::new(completion.label.text.clone())
1199 .with_highlights(&style.text, highlights);
1200 let documentation_label =
1201 if let Some(Documentation::SingleLine(text)) = documentation {
1202 if text.trim().is_empty() {
1203 None
1204 } else {
1205 Some(
1206 Label::new(text.clone())
1207 .ml_4()
1208 .size(LabelSize::Small)
1209 .color(Color::Muted),
1210 )
1211 }
1212 } else {
1213 None
1214 };
1215
1216 div().min_w(px(220.)).max_w(px(540.)).child(
1217 ListItem::new(mat.candidate_id)
1218 .inset(true)
1219 .selected(item_ix == selected_item)
1220 .on_click(cx.listener(move |editor, _event, cx| {
1221 cx.stop_propagation();
1222 if let Some(task) = editor.confirm_completion(
1223 &ConfirmCompletion {
1224 item_ix: Some(item_ix),
1225 },
1226 cx,
1227 ) {
1228 task.detach_and_log_err(cx)
1229 }
1230 }))
1231 .child(h_flex().overflow_hidden().child(completion_label))
1232 .end_slot::<Label>(documentation_label),
1233 )
1234 })
1235 .collect()
1236 },
1237 )
1238 .occlude()
1239 .max_h(max_height)
1240 .track_scroll(self.scroll_handle.clone())
1241 .with_width_from_item(widest_completion_ix)
1242 .with_sizing_behavior(ListSizingBehavior::Infer);
1243
1244 Popover::new()
1245 .child(list)
1246 .when_some(multiline_docs, |popover, multiline_docs| {
1247 popover.aside(multiline_docs)
1248 })
1249 .into_any_element()
1250 }
1251
1252 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1253 let mut matches = if let Some(query) = query {
1254 fuzzy::match_strings(
1255 &self.match_candidates,
1256 query,
1257 query.chars().any(|c| c.is_uppercase()),
1258 100,
1259 &Default::default(),
1260 executor,
1261 )
1262 .await
1263 } else {
1264 self.match_candidates
1265 .iter()
1266 .enumerate()
1267 .map(|(candidate_id, candidate)| StringMatch {
1268 candidate_id,
1269 score: Default::default(),
1270 positions: Default::default(),
1271 string: candidate.string.clone(),
1272 })
1273 .collect()
1274 };
1275
1276 // Remove all candidates where the query's start does not match the start of any word in the candidate
1277 if let Some(query) = query {
1278 if let Some(query_start) = query.chars().next() {
1279 matches.retain(|string_match| {
1280 split_words(&string_match.string).any(|word| {
1281 // Check that the first codepoint of the word as lowercase matches the first
1282 // codepoint of the query as lowercase
1283 word.chars()
1284 .flat_map(|codepoint| codepoint.to_lowercase())
1285 .zip(query_start.to_lowercase())
1286 .all(|(word_cp, query_cp)| word_cp == query_cp)
1287 })
1288 });
1289 }
1290 }
1291
1292 let completions = self.completions.read();
1293 if self.sort_completions {
1294 matches.sort_unstable_by_key(|mat| {
1295 // We do want to strike a balance here between what the language server tells us
1296 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1297 // `Creat` and there is a local variable called `CreateComponent`).
1298 // So what we do is: we bucket all matches into two buckets
1299 // - Strong matches
1300 // - Weak matches
1301 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1302 // and the Weak matches are the rest.
1303 //
1304 // For the strong matches, we sort by the language-servers score first and for the weak
1305 // matches, we prefer our fuzzy finder first.
1306 //
1307 // The thinking behind that: it's useless to take the sort_text the language-server gives
1308 // us into account when it's obviously a bad match.
1309
1310 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1311 enum MatchScore<'a> {
1312 Strong {
1313 sort_text: Option<&'a str>,
1314 score: Reverse<OrderedFloat<f64>>,
1315 sort_key: (usize, &'a str),
1316 },
1317 Weak {
1318 score: Reverse<OrderedFloat<f64>>,
1319 sort_text: Option<&'a str>,
1320 sort_key: (usize, &'a str),
1321 },
1322 }
1323
1324 let completion = &completions[mat.candidate_id];
1325 let sort_key = completion.sort_key();
1326 let sort_text = completion.lsp_completion.sort_text.as_deref();
1327 let score = Reverse(OrderedFloat(mat.score));
1328
1329 if mat.score >= 0.2 {
1330 MatchScore::Strong {
1331 sort_text,
1332 score,
1333 sort_key,
1334 }
1335 } else {
1336 MatchScore::Weak {
1337 score,
1338 sort_text,
1339 sort_key,
1340 }
1341 }
1342 });
1343 }
1344
1345 for mat in &mut matches {
1346 let completion = &completions[mat.candidate_id];
1347 mat.string.clone_from(&completion.label.text);
1348 for position in &mut mat.positions {
1349 *position += completion.label.filter_range.start;
1350 }
1351 }
1352 drop(completions);
1353
1354 self.matches = matches.into();
1355 self.selected_item = 0;
1356 }
1357}
1358
1359#[derive(Clone)]
1360struct CodeActionContents {
1361 tasks: Option<Arc<ResolvedTasks>>,
1362 actions: Option<Arc<[CodeAction]>>,
1363}
1364
1365impl CodeActionContents {
1366 fn len(&self) -> usize {
1367 match (&self.tasks, &self.actions) {
1368 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1369 (Some(tasks), None) => tasks.templates.len(),
1370 (None, Some(actions)) => actions.len(),
1371 (None, None) => 0,
1372 }
1373 }
1374
1375 fn is_empty(&self) -> bool {
1376 match (&self.tasks, &self.actions) {
1377 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1378 (Some(tasks), None) => tasks.templates.is_empty(),
1379 (None, Some(actions)) => actions.is_empty(),
1380 (None, None) => true,
1381 }
1382 }
1383
1384 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1385 self.tasks
1386 .iter()
1387 .flat_map(|tasks| {
1388 tasks
1389 .templates
1390 .iter()
1391 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1392 })
1393 .chain(self.actions.iter().flat_map(|actions| {
1394 actions
1395 .iter()
1396 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1397 }))
1398 }
1399 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1400 match (&self.tasks, &self.actions) {
1401 (Some(tasks), Some(actions)) => {
1402 if index < tasks.templates.len() {
1403 tasks
1404 .templates
1405 .get(index)
1406 .cloned()
1407 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1408 } else {
1409 actions
1410 .get(index - tasks.templates.len())
1411 .cloned()
1412 .map(CodeActionsItem::CodeAction)
1413 }
1414 }
1415 (Some(tasks), None) => tasks
1416 .templates
1417 .get(index)
1418 .cloned()
1419 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1420 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1421 (None, None) => None,
1422 }
1423 }
1424}
1425
1426#[allow(clippy::large_enum_variant)]
1427#[derive(Clone)]
1428enum CodeActionsItem {
1429 Task(TaskSourceKind, ResolvedTask),
1430 CodeAction(CodeAction),
1431}
1432
1433impl CodeActionsItem {
1434 fn as_task(&self) -> Option<&ResolvedTask> {
1435 let Self::Task(_, task) = self else {
1436 return None;
1437 };
1438 Some(task)
1439 }
1440 fn as_code_action(&self) -> Option<&CodeAction> {
1441 let Self::CodeAction(action) = self else {
1442 return None;
1443 };
1444 Some(action)
1445 }
1446 fn label(&self) -> String {
1447 match self {
1448 Self::CodeAction(action) => action.lsp_action.title.clone(),
1449 Self::Task(_, task) => task.resolved_label.clone(),
1450 }
1451 }
1452}
1453
1454struct CodeActionsMenu {
1455 actions: CodeActionContents,
1456 buffer: Model<Buffer>,
1457 selected_item: usize,
1458 scroll_handle: UniformListScrollHandle,
1459 deployed_from_indicator: Option<DisplayRow>,
1460}
1461
1462impl CodeActionsMenu {
1463 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1464 self.selected_item = 0;
1465 self.scroll_handle.scroll_to_item(self.selected_item);
1466 cx.notify()
1467 }
1468
1469 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1470 if self.selected_item > 0 {
1471 self.selected_item -= 1;
1472 } else {
1473 self.selected_item = self.actions.len() - 1;
1474 }
1475 self.scroll_handle.scroll_to_item(self.selected_item);
1476 cx.notify();
1477 }
1478
1479 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1480 if self.selected_item + 1 < self.actions.len() {
1481 self.selected_item += 1;
1482 } else {
1483 self.selected_item = 0;
1484 }
1485 self.scroll_handle.scroll_to_item(self.selected_item);
1486 cx.notify();
1487 }
1488
1489 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1490 self.selected_item = self.actions.len() - 1;
1491 self.scroll_handle.scroll_to_item(self.selected_item);
1492 cx.notify()
1493 }
1494
1495 fn visible(&self) -> bool {
1496 !self.actions.is_empty()
1497 }
1498
1499 fn render(
1500 &self,
1501 cursor_position: DisplayPoint,
1502 _style: &EditorStyle,
1503 max_height: Pixels,
1504 cx: &mut ViewContext<Editor>,
1505 ) -> (ContextMenuOrigin, AnyElement) {
1506 let actions = self.actions.clone();
1507 let selected_item = self.selected_item;
1508 let element = uniform_list(
1509 cx.view().clone(),
1510 "code_actions_menu",
1511 self.actions.len(),
1512 move |_this, range, cx| {
1513 actions
1514 .iter()
1515 .skip(range.start)
1516 .take(range.end - range.start)
1517 .enumerate()
1518 .map(|(ix, action)| {
1519 let item_ix = range.start + ix;
1520 let selected = selected_item == item_ix;
1521 let colors = cx.theme().colors();
1522 div()
1523 .px_1()
1524 .rounded_md()
1525 .text_color(colors.text)
1526 .when(selected, |style| {
1527 style
1528 .bg(colors.element_active)
1529 .text_color(colors.text_accent)
1530 })
1531 .hover(|style| {
1532 style
1533 .bg(colors.element_hover)
1534 .text_color(colors.text_accent)
1535 })
1536 .whitespace_nowrap()
1537 .when_some(action.as_code_action(), |this, action| {
1538 this.on_mouse_down(
1539 MouseButton::Left,
1540 cx.listener(move |editor, _, cx| {
1541 cx.stop_propagation();
1542 if let Some(task) = editor.confirm_code_action(
1543 &ConfirmCodeAction {
1544 item_ix: Some(item_ix),
1545 },
1546 cx,
1547 ) {
1548 task.detach_and_log_err(cx)
1549 }
1550 }),
1551 )
1552 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1553 .child(SharedString::from(action.lsp_action.title.clone()))
1554 })
1555 .when_some(action.as_task(), |this, task| {
1556 this.on_mouse_down(
1557 MouseButton::Left,
1558 cx.listener(move |editor, _, cx| {
1559 cx.stop_propagation();
1560 if let Some(task) = editor.confirm_code_action(
1561 &ConfirmCodeAction {
1562 item_ix: Some(item_ix),
1563 },
1564 cx,
1565 ) {
1566 task.detach_and_log_err(cx)
1567 }
1568 }),
1569 )
1570 .child(SharedString::from(task.resolved_label.clone()))
1571 })
1572 })
1573 .collect()
1574 },
1575 )
1576 .elevation_1(cx)
1577 .p_1()
1578 .max_h(max_height)
1579 .occlude()
1580 .track_scroll(self.scroll_handle.clone())
1581 .with_width_from_item(
1582 self.actions
1583 .iter()
1584 .enumerate()
1585 .max_by_key(|(_, action)| match action {
1586 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1587 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1588 })
1589 .map(|(ix, _)| ix),
1590 )
1591 .with_sizing_behavior(ListSizingBehavior::Infer)
1592 .into_any_element();
1593
1594 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1595 ContextMenuOrigin::GutterIndicator(row)
1596 } else {
1597 ContextMenuOrigin::EditorPoint(cursor_position)
1598 };
1599
1600 (cursor_position, element)
1601 }
1602}
1603
1604#[derive(Debug)]
1605struct ActiveDiagnosticGroup {
1606 primary_range: Range<Anchor>,
1607 primary_message: String,
1608 group_id: usize,
1609 blocks: HashMap<CustomBlockId, Diagnostic>,
1610 is_valid: bool,
1611}
1612
1613#[derive(Serialize, Deserialize, Clone, Debug)]
1614pub struct ClipboardSelection {
1615 pub len: usize,
1616 pub is_entire_line: bool,
1617 pub first_line_indent: u32,
1618}
1619
1620#[derive(Debug)]
1621pub(crate) struct NavigationData {
1622 cursor_anchor: Anchor,
1623 cursor_position: Point,
1624 scroll_anchor: ScrollAnchor,
1625 scroll_top_row: u32,
1626}
1627
1628#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1629enum GotoDefinitionKind {
1630 Symbol,
1631 Declaration,
1632 Type,
1633 Implementation,
1634}
1635
1636#[derive(Debug, Clone)]
1637enum InlayHintRefreshReason {
1638 Toggle(bool),
1639 SettingsChange(InlayHintSettings),
1640 NewLinesShown,
1641 BufferEdited(HashSet<Arc<Language>>),
1642 RefreshRequested,
1643 ExcerptsRemoved(Vec<ExcerptId>),
1644}
1645
1646impl InlayHintRefreshReason {
1647 fn description(&self) -> &'static str {
1648 match self {
1649 Self::Toggle(_) => "toggle",
1650 Self::SettingsChange(_) => "settings change",
1651 Self::NewLinesShown => "new lines shown",
1652 Self::BufferEdited(_) => "buffer edited",
1653 Self::RefreshRequested => "refresh requested",
1654 Self::ExcerptsRemoved(_) => "excerpts removed",
1655 }
1656 }
1657}
1658
1659pub(crate) struct FocusedBlock {
1660 id: BlockId,
1661 focus_handle: WeakFocusHandle,
1662}
1663
1664impl Editor {
1665 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1666 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1667 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1668 Self::new(
1669 EditorMode::SingleLine { auto_width: false },
1670 buffer,
1671 None,
1672 false,
1673 cx,
1674 )
1675 }
1676
1677 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1678 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1679 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1680 Self::new(EditorMode::Full, buffer, None, false, cx)
1681 }
1682
1683 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1684 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1685 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1686 Self::new(
1687 EditorMode::SingleLine { auto_width: true },
1688 buffer,
1689 None,
1690 false,
1691 cx,
1692 )
1693 }
1694
1695 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1696 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1697 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1698 Self::new(
1699 EditorMode::AutoHeight { max_lines },
1700 buffer,
1701 None,
1702 false,
1703 cx,
1704 )
1705 }
1706
1707 pub fn for_buffer(
1708 buffer: Model<Buffer>,
1709 project: Option<Model<Project>>,
1710 cx: &mut ViewContext<Self>,
1711 ) -> Self {
1712 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1713 Self::new(EditorMode::Full, buffer, project, false, cx)
1714 }
1715
1716 pub fn for_multibuffer(
1717 buffer: Model<MultiBuffer>,
1718 project: Option<Model<Project>>,
1719 show_excerpt_controls: bool,
1720 cx: &mut ViewContext<Self>,
1721 ) -> Self {
1722 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1723 }
1724
1725 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1726 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1727 let mut clone = Self::new(
1728 self.mode,
1729 self.buffer.clone(),
1730 self.project.clone(),
1731 show_excerpt_controls,
1732 cx,
1733 );
1734 self.display_map.update(cx, |display_map, cx| {
1735 let snapshot = display_map.snapshot(cx);
1736 clone.display_map.update(cx, |display_map, cx| {
1737 display_map.set_state(&snapshot, cx);
1738 });
1739 });
1740 clone.selections.clone_state(&self.selections);
1741 clone.scroll_manager.clone_state(&self.scroll_manager);
1742 clone.searchable = self.searchable;
1743 clone
1744 }
1745
1746 pub fn new(
1747 mode: EditorMode,
1748 buffer: Model<MultiBuffer>,
1749 project: Option<Model<Project>>,
1750 show_excerpt_controls: bool,
1751 cx: &mut ViewContext<Self>,
1752 ) -> Self {
1753 let style = cx.text_style();
1754 let font_size = style.font_size.to_pixels(cx.rem_size());
1755 let editor = cx.view().downgrade();
1756 let fold_placeholder = FoldPlaceholder {
1757 constrain_width: true,
1758 render: Arc::new(move |fold_id, fold_range, cx| {
1759 let editor = editor.clone();
1760 div()
1761 .id(fold_id)
1762 .bg(cx.theme().colors().ghost_element_background)
1763 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1764 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1765 .rounded_sm()
1766 .size_full()
1767 .cursor_pointer()
1768 .child("⋯")
1769 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1770 .on_click(move |_, cx| {
1771 editor
1772 .update(cx, |editor, cx| {
1773 editor.unfold_ranges(
1774 [fold_range.start..fold_range.end],
1775 true,
1776 false,
1777 cx,
1778 );
1779 cx.stop_propagation();
1780 })
1781 .ok();
1782 })
1783 .into_any()
1784 }),
1785 merge_adjacent: true,
1786 };
1787 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1788 let display_map = cx.new_model(|cx| {
1789 DisplayMap::new(
1790 buffer.clone(),
1791 style.font(),
1792 font_size,
1793 None,
1794 show_excerpt_controls,
1795 file_header_size,
1796 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1797 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1798 fold_placeholder,
1799 cx,
1800 )
1801 });
1802
1803 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1804
1805 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1806
1807 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1808 .then(|| language_settings::SoftWrap::PreferLine);
1809
1810 let mut project_subscriptions = Vec::new();
1811 if mode == EditorMode::Full {
1812 if let Some(project) = project.as_ref() {
1813 if buffer.read(cx).is_singleton() {
1814 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1815 cx.emit(EditorEvent::TitleChanged);
1816 }));
1817 }
1818 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1819 if let project::Event::RefreshInlayHints = event {
1820 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1821 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1822 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1823 let focus_handle = editor.focus_handle(cx);
1824 if focus_handle.is_focused(cx) {
1825 let snapshot = buffer.read(cx).snapshot();
1826 for (range, snippet) in snippet_edits {
1827 let editor_range =
1828 language::range_from_lsp(*range).to_offset(&snapshot);
1829 editor
1830 .insert_snippet(&[editor_range], snippet.clone(), cx)
1831 .ok();
1832 }
1833 }
1834 }
1835 }
1836 }));
1837 let task_inventory = project.read(cx).task_inventory().clone();
1838 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1839 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1840 }));
1841 }
1842 }
1843
1844 let inlay_hint_settings = inlay_hint_settings(
1845 selections.newest_anchor().head(),
1846 &buffer.read(cx).snapshot(cx),
1847 cx,
1848 );
1849 let focus_handle = cx.focus_handle();
1850 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1851 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1852 .detach();
1853 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1854 .detach();
1855 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1856
1857 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1858 Some(false)
1859 } else {
1860 None
1861 };
1862
1863 let mut this = Self {
1864 focus_handle,
1865 show_cursor_when_unfocused: false,
1866 last_focused_descendant: None,
1867 buffer: buffer.clone(),
1868 display_map: display_map.clone(),
1869 selections,
1870 scroll_manager: ScrollManager::new(cx),
1871 columnar_selection_tail: None,
1872 add_selections_state: None,
1873 select_next_state: None,
1874 select_prev_state: None,
1875 selection_history: Default::default(),
1876 autoclose_regions: Default::default(),
1877 snippet_stack: Default::default(),
1878 select_larger_syntax_node_stack: Vec::new(),
1879 ime_transaction: Default::default(),
1880 active_diagnostics: None,
1881 soft_wrap_mode_override,
1882 completion_provider: project.clone().map(|project| Box::new(project) as _),
1883 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1884 project,
1885 blink_manager: blink_manager.clone(),
1886 show_local_selections: true,
1887 mode,
1888 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1889 show_gutter: mode == EditorMode::Full,
1890 show_line_numbers: None,
1891 use_relative_line_numbers: None,
1892 show_git_diff_gutter: None,
1893 show_code_actions: None,
1894 show_runnables: None,
1895 show_wrap_guides: None,
1896 show_indent_guides,
1897 placeholder_text: None,
1898 highlight_order: 0,
1899 highlighted_rows: HashMap::default(),
1900 background_highlights: Default::default(),
1901 gutter_highlights: TreeMap::default(),
1902 scrollbar_marker_state: ScrollbarMarkerState::default(),
1903 active_indent_guides_state: ActiveIndentGuidesState::default(),
1904 nav_history: None,
1905 context_menu: RwLock::new(None),
1906 mouse_context_menu: None,
1907 completion_tasks: Default::default(),
1908 signature_help_state: SignatureHelpState::default(),
1909 auto_signature_help: None,
1910 find_all_references_task_sources: Vec::new(),
1911 next_completion_id: 0,
1912 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1913 next_inlay_id: 0,
1914 available_code_actions: Default::default(),
1915 code_actions_task: Default::default(),
1916 document_highlights_task: Default::default(),
1917 linked_editing_range_task: Default::default(),
1918 pending_rename: Default::default(),
1919 searchable: true,
1920 cursor_shape: EditorSettings::get_global(cx)
1921 .cursor_shape
1922 .unwrap_or_default(),
1923 current_line_highlight: None,
1924 autoindent_mode: Some(AutoindentMode::EachLine),
1925 collapse_matches: false,
1926 workspace: None,
1927 input_enabled: true,
1928 use_modal_editing: mode == EditorMode::Full,
1929 read_only: false,
1930 use_autoclose: true,
1931 use_auto_surround: true,
1932 auto_replace_emoji_shortcode: false,
1933 leader_peer_id: None,
1934 remote_id: None,
1935 hover_state: Default::default(),
1936 hovered_link_state: Default::default(),
1937 inline_completion_provider: None,
1938 active_inline_completion: None,
1939 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1940 expanded_hunks: ExpandedHunks::default(),
1941 gutter_hovered: false,
1942 pixel_position_of_newest_cursor: None,
1943 last_bounds: None,
1944 expect_bounds_change: None,
1945 gutter_dimensions: GutterDimensions::default(),
1946 style: None,
1947 show_cursor_names: false,
1948 hovered_cursors: Default::default(),
1949 next_editor_action_id: EditorActionId::default(),
1950 editor_actions: Rc::default(),
1951 show_inline_completions_override: None,
1952 enable_inline_completions: true,
1953 custom_context_menu: None,
1954 show_git_blame_gutter: false,
1955 show_git_blame_inline: false,
1956 show_selection_menu: None,
1957 show_git_blame_inline_delay_task: None,
1958 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1959 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1960 .session
1961 .restore_unsaved_buffers,
1962 blame: None,
1963 blame_subscription: None,
1964 file_header_size,
1965 tasks: Default::default(),
1966 _subscriptions: vec![
1967 cx.observe(&buffer, Self::on_buffer_changed),
1968 cx.subscribe(&buffer, Self::on_buffer_event),
1969 cx.observe(&display_map, Self::on_display_map_changed),
1970 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1971 cx.observe_global::<SettingsStore>(Self::settings_changed),
1972 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1973 cx.observe_window_activation(|editor, cx| {
1974 let active = cx.is_window_active();
1975 editor.blink_manager.update(cx, |blink_manager, cx| {
1976 if active {
1977 blink_manager.enable(cx);
1978 } else {
1979 blink_manager.disable(cx);
1980 }
1981 });
1982 }),
1983 ],
1984 tasks_update_task: None,
1985 linked_edit_ranges: Default::default(),
1986 previous_search_ranges: None,
1987 breadcrumb_header: None,
1988 focused_block: None,
1989 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1990 addons: HashMap::default(),
1991 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1992 };
1993 this.tasks_update_task = Some(this.refresh_runnables(cx));
1994 this._subscriptions.extend(project_subscriptions);
1995
1996 this.end_selection(cx);
1997 this.scroll_manager.show_scrollbar(cx);
1998
1999 if mode == EditorMode::Full {
2000 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2001 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2002
2003 if this.git_blame_inline_enabled {
2004 this.git_blame_inline_enabled = true;
2005 this.start_git_blame_inline(false, cx);
2006 }
2007 }
2008
2009 this.report_editor_event("open", None, cx);
2010 this
2011 }
2012
2013 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2014 self.mouse_context_menu
2015 .as_ref()
2016 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2017 }
2018
2019 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2020 let mut key_context = KeyContext::new_with_defaults();
2021 key_context.add("Editor");
2022 let mode = match self.mode {
2023 EditorMode::SingleLine { .. } => "single_line",
2024 EditorMode::AutoHeight { .. } => "auto_height",
2025 EditorMode::Full => "full",
2026 };
2027
2028 if EditorSettings::jupyter_enabled(cx) {
2029 key_context.add("jupyter");
2030 }
2031
2032 key_context.set("mode", mode);
2033 if self.pending_rename.is_some() {
2034 key_context.add("renaming");
2035 }
2036 if self.context_menu_visible() {
2037 match self.context_menu.read().as_ref() {
2038 Some(ContextMenu::Completions(_)) => {
2039 key_context.add("menu");
2040 key_context.add("showing_completions")
2041 }
2042 Some(ContextMenu::CodeActions(_)) => {
2043 key_context.add("menu");
2044 key_context.add("showing_code_actions")
2045 }
2046 None => {}
2047 }
2048 }
2049
2050 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2051 if !self.focus_handle(cx).contains_focused(cx)
2052 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2053 {
2054 for addon in self.addons.values() {
2055 addon.extend_key_context(&mut key_context, cx)
2056 }
2057 }
2058
2059 if let Some(extension) = self
2060 .buffer
2061 .read(cx)
2062 .as_singleton()
2063 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2064 {
2065 key_context.set("extension", extension.to_string());
2066 }
2067
2068 if self.has_active_inline_completion(cx) {
2069 key_context.add("copilot_suggestion");
2070 key_context.add("inline_completion");
2071 }
2072
2073 key_context
2074 }
2075
2076 pub fn new_file(
2077 workspace: &mut Workspace,
2078 _: &workspace::NewFile,
2079 cx: &mut ViewContext<Workspace>,
2080 ) {
2081 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2082 "Failed to create buffer",
2083 cx,
2084 |e, _| match e.error_code() {
2085 ErrorCode::RemoteUpgradeRequired => Some(format!(
2086 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2087 e.error_tag("required").unwrap_or("the latest version")
2088 )),
2089 _ => None,
2090 },
2091 );
2092 }
2093
2094 pub fn new_in_workspace(
2095 workspace: &mut Workspace,
2096 cx: &mut ViewContext<Workspace>,
2097 ) -> Task<Result<View<Editor>>> {
2098 let project = workspace.project().clone();
2099 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2100
2101 cx.spawn(|workspace, mut cx| async move {
2102 let buffer = create.await?;
2103 workspace.update(&mut cx, |workspace, cx| {
2104 let editor =
2105 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2106 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2107 editor
2108 })
2109 })
2110 }
2111
2112 fn new_file_vertical(
2113 workspace: &mut Workspace,
2114 _: &workspace::NewFileSplitVertical,
2115 cx: &mut ViewContext<Workspace>,
2116 ) {
2117 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2118 }
2119
2120 fn new_file_horizontal(
2121 workspace: &mut Workspace,
2122 _: &workspace::NewFileSplitHorizontal,
2123 cx: &mut ViewContext<Workspace>,
2124 ) {
2125 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2126 }
2127
2128 fn new_file_in_direction(
2129 workspace: &mut Workspace,
2130 direction: SplitDirection,
2131 cx: &mut ViewContext<Workspace>,
2132 ) {
2133 let project = workspace.project().clone();
2134 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2135
2136 cx.spawn(|workspace, mut cx| async move {
2137 let buffer = create.await?;
2138 workspace.update(&mut cx, move |workspace, cx| {
2139 workspace.split_item(
2140 direction,
2141 Box::new(
2142 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2143 ),
2144 cx,
2145 )
2146 })?;
2147 anyhow::Ok(())
2148 })
2149 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2150 ErrorCode::RemoteUpgradeRequired => Some(format!(
2151 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2152 e.error_tag("required").unwrap_or("the latest version")
2153 )),
2154 _ => None,
2155 });
2156 }
2157
2158 pub fn replica_id(&self, cx: &AppContext) -> ReplicaId {
2159 self.buffer.read(cx).replica_id()
2160 }
2161
2162 pub fn leader_peer_id(&self) -> Option<PeerId> {
2163 self.leader_peer_id
2164 }
2165
2166 pub fn buffer(&self) -> &Model<MultiBuffer> {
2167 &self.buffer
2168 }
2169
2170 pub fn workspace(&self) -> Option<View<Workspace>> {
2171 self.workspace.as_ref()?.0.upgrade()
2172 }
2173
2174 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2175 self.buffer().read(cx).title(cx)
2176 }
2177
2178 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2179 EditorSnapshot {
2180 mode: self.mode,
2181 show_gutter: self.show_gutter,
2182 show_line_numbers: self.show_line_numbers,
2183 show_git_diff_gutter: self.show_git_diff_gutter,
2184 show_code_actions: self.show_code_actions,
2185 show_runnables: self.show_runnables,
2186 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2187 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2188 scroll_anchor: self.scroll_manager.anchor(),
2189 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2190 placeholder_text: self.placeholder_text.clone(),
2191 is_focused: self.focus_handle.is_focused(cx),
2192 current_line_highlight: self
2193 .current_line_highlight
2194 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2195 gutter_hovered: self.gutter_hovered,
2196 }
2197 }
2198
2199 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2200 self.buffer.read(cx).language_at(point, cx)
2201 }
2202
2203 pub fn file_at<T: ToOffset>(
2204 &self,
2205 point: T,
2206 cx: &AppContext,
2207 ) -> Option<Arc<dyn language::File>> {
2208 self.buffer.read(cx).read(cx).file_at(point).cloned()
2209 }
2210
2211 pub fn active_excerpt(
2212 &self,
2213 cx: &AppContext,
2214 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2215 self.buffer
2216 .read(cx)
2217 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2218 }
2219
2220 pub fn mode(&self) -> EditorMode {
2221 self.mode
2222 }
2223
2224 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2225 self.collaboration_hub.as_deref()
2226 }
2227
2228 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2229 self.collaboration_hub = Some(hub);
2230 }
2231
2232 pub fn set_custom_context_menu(
2233 &mut self,
2234 f: impl 'static
2235 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2236 ) {
2237 self.custom_context_menu = Some(Box::new(f))
2238 }
2239
2240 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2241 self.completion_provider = Some(provider);
2242 }
2243
2244 pub fn set_inline_completion_provider<T>(
2245 &mut self,
2246 provider: Option<Model<T>>,
2247 cx: &mut ViewContext<Self>,
2248 ) where
2249 T: InlineCompletionProvider,
2250 {
2251 self.inline_completion_provider =
2252 provider.map(|provider| RegisteredInlineCompletionProvider {
2253 _subscription: cx.observe(&provider, |this, _, cx| {
2254 if this.focus_handle.is_focused(cx) {
2255 this.update_visible_inline_completion(cx);
2256 }
2257 }),
2258 provider: Arc::new(provider),
2259 });
2260 self.refresh_inline_completion(false, false, cx);
2261 }
2262
2263 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2264 self.placeholder_text.as_deref()
2265 }
2266
2267 pub fn set_placeholder_text(
2268 &mut self,
2269 placeholder_text: impl Into<Arc<str>>,
2270 cx: &mut ViewContext<Self>,
2271 ) {
2272 let placeholder_text = Some(placeholder_text.into());
2273 if self.placeholder_text != placeholder_text {
2274 self.placeholder_text = placeholder_text;
2275 cx.notify();
2276 }
2277 }
2278
2279 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2280 self.cursor_shape = cursor_shape;
2281
2282 // Disrupt blink for immediate user feedback that the cursor shape has changed
2283 self.blink_manager.update(cx, BlinkManager::show_cursor);
2284
2285 cx.notify();
2286 }
2287
2288 pub fn set_current_line_highlight(
2289 &mut self,
2290 current_line_highlight: Option<CurrentLineHighlight>,
2291 ) {
2292 self.current_line_highlight = current_line_highlight;
2293 }
2294
2295 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2296 self.collapse_matches = collapse_matches;
2297 }
2298
2299 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2300 if self.collapse_matches {
2301 return range.start..range.start;
2302 }
2303 range.clone()
2304 }
2305
2306 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2307 if self.display_map.read(cx).clip_at_line_ends != clip {
2308 self.display_map
2309 .update(cx, |map, _| map.clip_at_line_ends = clip);
2310 }
2311 }
2312
2313 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2314 self.input_enabled = input_enabled;
2315 }
2316
2317 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2318 self.enable_inline_completions = enabled;
2319 }
2320
2321 pub fn set_autoindent(&mut self, autoindent: bool) {
2322 if autoindent {
2323 self.autoindent_mode = Some(AutoindentMode::EachLine);
2324 } else {
2325 self.autoindent_mode = None;
2326 }
2327 }
2328
2329 pub fn read_only(&self, cx: &AppContext) -> bool {
2330 self.read_only || self.buffer.read(cx).read_only()
2331 }
2332
2333 pub fn set_read_only(&mut self, read_only: bool) {
2334 self.read_only = read_only;
2335 }
2336
2337 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2338 self.use_autoclose = autoclose;
2339 }
2340
2341 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2342 self.use_auto_surround = auto_surround;
2343 }
2344
2345 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2346 self.auto_replace_emoji_shortcode = auto_replace;
2347 }
2348
2349 pub fn toggle_inline_completions(
2350 &mut self,
2351 _: &ToggleInlineCompletions,
2352 cx: &mut ViewContext<Self>,
2353 ) {
2354 if self.show_inline_completions_override.is_some() {
2355 self.set_show_inline_completions(None, cx);
2356 } else {
2357 let cursor = self.selections.newest_anchor().head();
2358 if let Some((buffer, cursor_buffer_position)) =
2359 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2360 {
2361 let show_inline_completions =
2362 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2363 self.set_show_inline_completions(Some(show_inline_completions), cx);
2364 }
2365 }
2366 }
2367
2368 pub fn set_show_inline_completions(
2369 &mut self,
2370 show_inline_completions: Option<bool>,
2371 cx: &mut ViewContext<Self>,
2372 ) {
2373 self.show_inline_completions_override = show_inline_completions;
2374 self.refresh_inline_completion(false, true, cx);
2375 }
2376
2377 fn should_show_inline_completions(
2378 &self,
2379 buffer: &Model<Buffer>,
2380 buffer_position: language::Anchor,
2381 cx: &AppContext,
2382 ) -> bool {
2383 if let Some(provider) = self.inline_completion_provider() {
2384 if let Some(show_inline_completions) = self.show_inline_completions_override {
2385 show_inline_completions
2386 } else {
2387 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2388 }
2389 } else {
2390 false
2391 }
2392 }
2393
2394 pub fn set_use_modal_editing(&mut self, to: bool) {
2395 self.use_modal_editing = to;
2396 }
2397
2398 pub fn use_modal_editing(&self) -> bool {
2399 self.use_modal_editing
2400 }
2401
2402 fn selections_did_change(
2403 &mut self,
2404 local: bool,
2405 old_cursor_position: &Anchor,
2406 show_completions: bool,
2407 cx: &mut ViewContext<Self>,
2408 ) {
2409 cx.invalidate_character_coordinates();
2410
2411 // Copy selections to primary selection buffer
2412 #[cfg(target_os = "linux")]
2413 if local {
2414 let selections = self.selections.all::<usize>(cx);
2415 let buffer_handle = self.buffer.read(cx).read(cx);
2416
2417 let mut text = String::new();
2418 for (index, selection) in selections.iter().enumerate() {
2419 let text_for_selection = buffer_handle
2420 .text_for_range(selection.start..selection.end)
2421 .collect::<String>();
2422
2423 text.push_str(&text_for_selection);
2424 if index != selections.len() - 1 {
2425 text.push('\n');
2426 }
2427 }
2428
2429 if !text.is_empty() {
2430 cx.write_to_primary(ClipboardItem::new_string(text));
2431 }
2432 }
2433
2434 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2435 self.buffer.update(cx, |buffer, cx| {
2436 buffer.set_active_selections(
2437 &self.selections.disjoint_anchors(),
2438 self.selections.line_mode,
2439 self.cursor_shape,
2440 cx,
2441 )
2442 });
2443 }
2444 let display_map = self
2445 .display_map
2446 .update(cx, |display_map, cx| display_map.snapshot(cx));
2447 let buffer = &display_map.buffer_snapshot;
2448 self.add_selections_state = None;
2449 self.select_next_state = None;
2450 self.select_prev_state = None;
2451 self.select_larger_syntax_node_stack.clear();
2452 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2453 self.snippet_stack
2454 .invalidate(&self.selections.disjoint_anchors(), buffer);
2455 self.take_rename(false, cx);
2456
2457 let new_cursor_position = self.selections.newest_anchor().head();
2458
2459 self.push_to_nav_history(
2460 *old_cursor_position,
2461 Some(new_cursor_position.to_point(buffer)),
2462 cx,
2463 );
2464
2465 if local {
2466 let new_cursor_position = self.selections.newest_anchor().head();
2467 let mut context_menu = self.context_menu.write();
2468 let completion_menu = match context_menu.as_ref() {
2469 Some(ContextMenu::Completions(menu)) => Some(menu),
2470
2471 _ => {
2472 *context_menu = None;
2473 None
2474 }
2475 };
2476
2477 if let Some(completion_menu) = completion_menu {
2478 let cursor_position = new_cursor_position.to_offset(buffer);
2479 let (word_range, kind) =
2480 buffer.surrounding_word(completion_menu.initial_position, true);
2481 if kind == Some(CharKind::Word)
2482 && word_range.to_inclusive().contains(&cursor_position)
2483 {
2484 let mut completion_menu = completion_menu.clone();
2485 drop(context_menu);
2486
2487 let query = Self::completion_query(buffer, cursor_position);
2488 cx.spawn(move |this, mut cx| async move {
2489 completion_menu
2490 .filter(query.as_deref(), cx.background_executor().clone())
2491 .await;
2492
2493 this.update(&mut cx, |this, cx| {
2494 let mut context_menu = this.context_menu.write();
2495 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2496 return;
2497 };
2498
2499 if menu.id > completion_menu.id {
2500 return;
2501 }
2502
2503 *context_menu = Some(ContextMenu::Completions(completion_menu));
2504 drop(context_menu);
2505 cx.notify();
2506 })
2507 })
2508 .detach();
2509
2510 if show_completions {
2511 self.show_completions(&ShowCompletions { trigger: None }, cx);
2512 }
2513 } else {
2514 drop(context_menu);
2515 self.hide_context_menu(cx);
2516 }
2517 } else {
2518 drop(context_menu);
2519 }
2520
2521 hide_hover(self, cx);
2522
2523 if old_cursor_position.to_display_point(&display_map).row()
2524 != new_cursor_position.to_display_point(&display_map).row()
2525 {
2526 self.available_code_actions.take();
2527 }
2528 self.refresh_code_actions(cx);
2529 self.refresh_document_highlights(cx);
2530 refresh_matching_bracket_highlights(self, cx);
2531 self.discard_inline_completion(false, cx);
2532 linked_editing_ranges::refresh_linked_ranges(self, cx);
2533 if self.git_blame_inline_enabled {
2534 self.start_inline_blame_timer(cx);
2535 }
2536 }
2537
2538 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2539 cx.emit(EditorEvent::SelectionsChanged { local });
2540
2541 if self.selections.disjoint_anchors().len() == 1 {
2542 cx.emit(SearchEvent::ActiveMatchChanged)
2543 }
2544 cx.notify();
2545 }
2546
2547 pub fn change_selections<R>(
2548 &mut self,
2549 autoscroll: Option<Autoscroll>,
2550 cx: &mut ViewContext<Self>,
2551 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2552 ) -> R {
2553 self.change_selections_inner(autoscroll, true, cx, change)
2554 }
2555
2556 pub fn change_selections_inner<R>(
2557 &mut self,
2558 autoscroll: Option<Autoscroll>,
2559 request_completions: bool,
2560 cx: &mut ViewContext<Self>,
2561 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2562 ) -> R {
2563 let old_cursor_position = self.selections.newest_anchor().head();
2564 self.push_to_selection_history();
2565
2566 let (changed, result) = self.selections.change_with(cx, change);
2567
2568 if changed {
2569 if let Some(autoscroll) = autoscroll {
2570 self.request_autoscroll(autoscroll, cx);
2571 }
2572 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2573
2574 if self.should_open_signature_help_automatically(
2575 &old_cursor_position,
2576 self.signature_help_state.backspace_pressed(),
2577 cx,
2578 ) {
2579 self.show_signature_help(&ShowSignatureHelp, cx);
2580 }
2581 self.signature_help_state.set_backspace_pressed(false);
2582 }
2583
2584 result
2585 }
2586
2587 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2588 where
2589 I: IntoIterator<Item = (Range<S>, T)>,
2590 S: ToOffset,
2591 T: Into<Arc<str>>,
2592 {
2593 if self.read_only(cx) {
2594 return;
2595 }
2596
2597 self.buffer
2598 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2599 }
2600
2601 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2602 where
2603 I: IntoIterator<Item = (Range<S>, T)>,
2604 S: ToOffset,
2605 T: Into<Arc<str>>,
2606 {
2607 if self.read_only(cx) {
2608 return;
2609 }
2610
2611 self.buffer.update(cx, |buffer, cx| {
2612 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2613 });
2614 }
2615
2616 pub fn edit_with_block_indent<I, S, T>(
2617 &mut self,
2618 edits: I,
2619 original_indent_columns: Vec<u32>,
2620 cx: &mut ViewContext<Self>,
2621 ) where
2622 I: IntoIterator<Item = (Range<S>, T)>,
2623 S: ToOffset,
2624 T: Into<Arc<str>>,
2625 {
2626 if self.read_only(cx) {
2627 return;
2628 }
2629
2630 self.buffer.update(cx, |buffer, cx| {
2631 buffer.edit(
2632 edits,
2633 Some(AutoindentMode::Block {
2634 original_indent_columns,
2635 }),
2636 cx,
2637 )
2638 });
2639 }
2640
2641 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2642 self.hide_context_menu(cx);
2643
2644 match phase {
2645 SelectPhase::Begin {
2646 position,
2647 add,
2648 click_count,
2649 } => self.begin_selection(position, add, click_count, cx),
2650 SelectPhase::BeginColumnar {
2651 position,
2652 goal_column,
2653 reset,
2654 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2655 SelectPhase::Extend {
2656 position,
2657 click_count,
2658 } => self.extend_selection(position, click_count, cx),
2659 SelectPhase::Update {
2660 position,
2661 goal_column,
2662 scroll_delta,
2663 } => self.update_selection(position, goal_column, scroll_delta, cx),
2664 SelectPhase::End => self.end_selection(cx),
2665 }
2666 }
2667
2668 fn extend_selection(
2669 &mut self,
2670 position: DisplayPoint,
2671 click_count: usize,
2672 cx: &mut ViewContext<Self>,
2673 ) {
2674 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2675 let tail = self.selections.newest::<usize>(cx).tail();
2676 self.begin_selection(position, false, click_count, cx);
2677
2678 let position = position.to_offset(&display_map, Bias::Left);
2679 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2680
2681 let mut pending_selection = self
2682 .selections
2683 .pending_anchor()
2684 .expect("extend_selection not called with pending selection");
2685 if position >= tail {
2686 pending_selection.start = tail_anchor;
2687 } else {
2688 pending_selection.end = tail_anchor;
2689 pending_selection.reversed = true;
2690 }
2691
2692 let mut pending_mode = self.selections.pending_mode().unwrap();
2693 match &mut pending_mode {
2694 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2695 _ => {}
2696 }
2697
2698 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2699 s.set_pending(pending_selection, pending_mode)
2700 });
2701 }
2702
2703 fn begin_selection(
2704 &mut self,
2705 position: DisplayPoint,
2706 add: bool,
2707 click_count: usize,
2708 cx: &mut ViewContext<Self>,
2709 ) {
2710 if !self.focus_handle.is_focused(cx) {
2711 self.last_focused_descendant = None;
2712 cx.focus(&self.focus_handle);
2713 }
2714
2715 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2716 let buffer = &display_map.buffer_snapshot;
2717 let newest_selection = self.selections.newest_anchor().clone();
2718 let position = display_map.clip_point(position, Bias::Left);
2719
2720 let start;
2721 let end;
2722 let mode;
2723 let auto_scroll;
2724 match click_count {
2725 1 => {
2726 start = buffer.anchor_before(position.to_point(&display_map));
2727 end = start;
2728 mode = SelectMode::Character;
2729 auto_scroll = true;
2730 }
2731 2 => {
2732 let range = movement::surrounding_word(&display_map, position);
2733 start = buffer.anchor_before(range.start.to_point(&display_map));
2734 end = buffer.anchor_before(range.end.to_point(&display_map));
2735 mode = SelectMode::Word(start..end);
2736 auto_scroll = true;
2737 }
2738 3 => {
2739 let position = display_map
2740 .clip_point(position, Bias::Left)
2741 .to_point(&display_map);
2742 let line_start = display_map.prev_line_boundary(position).0;
2743 let next_line_start = buffer.clip_point(
2744 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2745 Bias::Left,
2746 );
2747 start = buffer.anchor_before(line_start);
2748 end = buffer.anchor_before(next_line_start);
2749 mode = SelectMode::Line(start..end);
2750 auto_scroll = true;
2751 }
2752 _ => {
2753 start = buffer.anchor_before(0);
2754 end = buffer.anchor_before(buffer.len());
2755 mode = SelectMode::All;
2756 auto_scroll = false;
2757 }
2758 }
2759
2760 let point_to_delete: Option<usize> = {
2761 let selected_points: Vec<Selection<Point>> =
2762 self.selections.disjoint_in_range(start..end, cx);
2763
2764 if !add || click_count > 1 {
2765 None
2766 } else if !selected_points.is_empty() {
2767 Some(selected_points[0].id)
2768 } else {
2769 let clicked_point_already_selected =
2770 self.selections.disjoint.iter().find(|selection| {
2771 selection.start.to_point(buffer) == start.to_point(buffer)
2772 || selection.end.to_point(buffer) == end.to_point(buffer)
2773 });
2774
2775 clicked_point_already_selected.map(|selection| selection.id)
2776 }
2777 };
2778
2779 let selections_count = self.selections.count();
2780
2781 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2782 if let Some(point_to_delete) = point_to_delete {
2783 s.delete(point_to_delete);
2784
2785 if selections_count == 1 {
2786 s.set_pending_anchor_range(start..end, mode);
2787 }
2788 } else {
2789 if !add {
2790 s.clear_disjoint();
2791 } else if click_count > 1 {
2792 s.delete(newest_selection.id)
2793 }
2794
2795 s.set_pending_anchor_range(start..end, mode);
2796 }
2797 });
2798 }
2799
2800 fn begin_columnar_selection(
2801 &mut self,
2802 position: DisplayPoint,
2803 goal_column: u32,
2804 reset: bool,
2805 cx: &mut ViewContext<Self>,
2806 ) {
2807 if !self.focus_handle.is_focused(cx) {
2808 self.last_focused_descendant = None;
2809 cx.focus(&self.focus_handle);
2810 }
2811
2812 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2813
2814 if reset {
2815 let pointer_position = display_map
2816 .buffer_snapshot
2817 .anchor_before(position.to_point(&display_map));
2818
2819 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2820 s.clear_disjoint();
2821 s.set_pending_anchor_range(
2822 pointer_position..pointer_position,
2823 SelectMode::Character,
2824 );
2825 });
2826 }
2827
2828 let tail = self.selections.newest::<Point>(cx).tail();
2829 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2830
2831 if !reset {
2832 self.select_columns(
2833 tail.to_display_point(&display_map),
2834 position,
2835 goal_column,
2836 &display_map,
2837 cx,
2838 );
2839 }
2840 }
2841
2842 fn update_selection(
2843 &mut self,
2844 position: DisplayPoint,
2845 goal_column: u32,
2846 scroll_delta: gpui::Point<f32>,
2847 cx: &mut ViewContext<Self>,
2848 ) {
2849 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2850
2851 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2852 let tail = tail.to_display_point(&display_map);
2853 self.select_columns(tail, position, goal_column, &display_map, cx);
2854 } else if let Some(mut pending) = self.selections.pending_anchor() {
2855 let buffer = self.buffer.read(cx).snapshot(cx);
2856 let head;
2857 let tail;
2858 let mode = self.selections.pending_mode().unwrap();
2859 match &mode {
2860 SelectMode::Character => {
2861 head = position.to_point(&display_map);
2862 tail = pending.tail().to_point(&buffer);
2863 }
2864 SelectMode::Word(original_range) => {
2865 let original_display_range = original_range.start.to_display_point(&display_map)
2866 ..original_range.end.to_display_point(&display_map);
2867 let original_buffer_range = original_display_range.start.to_point(&display_map)
2868 ..original_display_range.end.to_point(&display_map);
2869 if movement::is_inside_word(&display_map, position)
2870 || original_display_range.contains(&position)
2871 {
2872 let word_range = movement::surrounding_word(&display_map, position);
2873 if word_range.start < original_display_range.start {
2874 head = word_range.start.to_point(&display_map);
2875 } else {
2876 head = word_range.end.to_point(&display_map);
2877 }
2878 } else {
2879 head = position.to_point(&display_map);
2880 }
2881
2882 if head <= original_buffer_range.start {
2883 tail = original_buffer_range.end;
2884 } else {
2885 tail = original_buffer_range.start;
2886 }
2887 }
2888 SelectMode::Line(original_range) => {
2889 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2890
2891 let position = display_map
2892 .clip_point(position, Bias::Left)
2893 .to_point(&display_map);
2894 let line_start = display_map.prev_line_boundary(position).0;
2895 let next_line_start = buffer.clip_point(
2896 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2897 Bias::Left,
2898 );
2899
2900 if line_start < original_range.start {
2901 head = line_start
2902 } else {
2903 head = next_line_start
2904 }
2905
2906 if head <= original_range.start {
2907 tail = original_range.end;
2908 } else {
2909 tail = original_range.start;
2910 }
2911 }
2912 SelectMode::All => {
2913 return;
2914 }
2915 };
2916
2917 if head < tail {
2918 pending.start = buffer.anchor_before(head);
2919 pending.end = buffer.anchor_before(tail);
2920 pending.reversed = true;
2921 } else {
2922 pending.start = buffer.anchor_before(tail);
2923 pending.end = buffer.anchor_before(head);
2924 pending.reversed = false;
2925 }
2926
2927 self.change_selections(None, cx, |s| {
2928 s.set_pending(pending, mode);
2929 });
2930 } else {
2931 log::error!("update_selection dispatched with no pending selection");
2932 return;
2933 }
2934
2935 self.apply_scroll_delta(scroll_delta, cx);
2936 cx.notify();
2937 }
2938
2939 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2940 self.columnar_selection_tail.take();
2941 if self.selections.pending_anchor().is_some() {
2942 let selections = self.selections.all::<usize>(cx);
2943 self.change_selections(None, cx, |s| {
2944 s.select(selections);
2945 s.clear_pending();
2946 });
2947 }
2948 }
2949
2950 fn select_columns(
2951 &mut self,
2952 tail: DisplayPoint,
2953 head: DisplayPoint,
2954 goal_column: u32,
2955 display_map: &DisplaySnapshot,
2956 cx: &mut ViewContext<Self>,
2957 ) {
2958 let start_row = cmp::min(tail.row(), head.row());
2959 let end_row = cmp::max(tail.row(), head.row());
2960 let start_column = cmp::min(tail.column(), goal_column);
2961 let end_column = cmp::max(tail.column(), goal_column);
2962 let reversed = start_column < tail.column();
2963
2964 let selection_ranges = (start_row.0..=end_row.0)
2965 .map(DisplayRow)
2966 .filter_map(|row| {
2967 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2968 let start = display_map
2969 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2970 .to_point(display_map);
2971 let end = display_map
2972 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2973 .to_point(display_map);
2974 if reversed {
2975 Some(end..start)
2976 } else {
2977 Some(start..end)
2978 }
2979 } else {
2980 None
2981 }
2982 })
2983 .collect::<Vec<_>>();
2984
2985 self.change_selections(None, cx, |s| {
2986 s.select_ranges(selection_ranges);
2987 });
2988 cx.notify();
2989 }
2990
2991 pub fn has_pending_nonempty_selection(&self) -> bool {
2992 let pending_nonempty_selection = match self.selections.pending_anchor() {
2993 Some(Selection { start, end, .. }) => start != end,
2994 None => false,
2995 };
2996
2997 pending_nonempty_selection
2998 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2999 }
3000
3001 pub fn has_pending_selection(&self) -> bool {
3002 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3003 }
3004
3005 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3006 if self.clear_clicked_diff_hunks(cx) {
3007 cx.notify();
3008 return;
3009 }
3010 if self.dismiss_menus_and_popups(true, cx) {
3011 return;
3012 }
3013
3014 if self.mode == EditorMode::Full
3015 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3016 {
3017 return;
3018 }
3019
3020 cx.propagate();
3021 }
3022
3023 pub fn dismiss_menus_and_popups(
3024 &mut self,
3025 should_report_inline_completion_event: bool,
3026 cx: &mut ViewContext<Self>,
3027 ) -> bool {
3028 if self.take_rename(false, cx).is_some() {
3029 return true;
3030 }
3031
3032 if hide_hover(self, cx) {
3033 return true;
3034 }
3035
3036 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3037 return true;
3038 }
3039
3040 if self.hide_context_menu(cx).is_some() {
3041 return true;
3042 }
3043
3044 if self.mouse_context_menu.take().is_some() {
3045 return true;
3046 }
3047
3048 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3049 return true;
3050 }
3051
3052 if self.snippet_stack.pop().is_some() {
3053 return true;
3054 }
3055
3056 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3057 self.dismiss_diagnostics(cx);
3058 return true;
3059 }
3060
3061 false
3062 }
3063
3064 fn linked_editing_ranges_for(
3065 &self,
3066 selection: Range<text::Anchor>,
3067 cx: &AppContext,
3068 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3069 if self.linked_edit_ranges.is_empty() {
3070 return None;
3071 }
3072 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3073 selection.end.buffer_id.and_then(|end_buffer_id| {
3074 if selection.start.buffer_id != Some(end_buffer_id) {
3075 return None;
3076 }
3077 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3078 let snapshot = buffer.read(cx).snapshot();
3079 self.linked_edit_ranges
3080 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3081 .map(|ranges| (ranges, snapshot, buffer))
3082 })?;
3083 use text::ToOffset as TO;
3084 // find offset from the start of current range to current cursor position
3085 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3086
3087 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3088 let start_difference = start_offset - start_byte_offset;
3089 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3090 let end_difference = end_offset - start_byte_offset;
3091 // Current range has associated linked ranges.
3092 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3093 for range in linked_ranges.iter() {
3094 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3095 let end_offset = start_offset + end_difference;
3096 let start_offset = start_offset + start_difference;
3097 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3098 continue;
3099 }
3100 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3101 if s.start.buffer_id != selection.start.buffer_id
3102 || s.end.buffer_id != selection.end.buffer_id
3103 {
3104 return false;
3105 }
3106 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3107 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3108 }) {
3109 continue;
3110 }
3111 let start = buffer_snapshot.anchor_after(start_offset);
3112 let end = buffer_snapshot.anchor_after(end_offset);
3113 linked_edits
3114 .entry(buffer.clone())
3115 .or_default()
3116 .push(start..end);
3117 }
3118 Some(linked_edits)
3119 }
3120
3121 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3122 let text: Arc<str> = text.into();
3123
3124 if self.read_only(cx) {
3125 return;
3126 }
3127
3128 let selections = self.selections.all_adjusted(cx);
3129 let mut bracket_inserted = false;
3130 let mut edits = Vec::new();
3131 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3132 let mut new_selections = Vec::with_capacity(selections.len());
3133 let mut new_autoclose_regions = Vec::new();
3134 let snapshot = self.buffer.read(cx).read(cx);
3135
3136 for (selection, autoclose_region) in
3137 self.selections_with_autoclose_regions(selections, &snapshot)
3138 {
3139 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3140 // Determine if the inserted text matches the opening or closing
3141 // bracket of any of this language's bracket pairs.
3142 let mut bracket_pair = None;
3143 let mut is_bracket_pair_start = false;
3144 let mut is_bracket_pair_end = false;
3145 if !text.is_empty() {
3146 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3147 // and they are removing the character that triggered IME popup.
3148 for (pair, enabled) in scope.brackets() {
3149 if !pair.close && !pair.surround {
3150 continue;
3151 }
3152
3153 if enabled && pair.start.ends_with(text.as_ref()) {
3154 bracket_pair = Some(pair.clone());
3155 is_bracket_pair_start = true;
3156 break;
3157 }
3158 if pair.end.as_str() == text.as_ref() {
3159 bracket_pair = Some(pair.clone());
3160 is_bracket_pair_end = true;
3161 break;
3162 }
3163 }
3164 }
3165
3166 if let Some(bracket_pair) = bracket_pair {
3167 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3168 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3169 let auto_surround =
3170 self.use_auto_surround && snapshot_settings.use_auto_surround;
3171 if selection.is_empty() {
3172 if is_bracket_pair_start {
3173 let prefix_len = bracket_pair.start.len() - text.len();
3174
3175 // If the inserted text is a suffix of an opening bracket and the
3176 // selection is preceded by the rest of the opening bracket, then
3177 // insert the closing bracket.
3178 let following_text_allows_autoclose = snapshot
3179 .chars_at(selection.start)
3180 .next()
3181 .map_or(true, |c| scope.should_autoclose_before(c));
3182 let preceding_text_matches_prefix = prefix_len == 0
3183 || (selection.start.column >= (prefix_len as u32)
3184 && snapshot.contains_str_at(
3185 Point::new(
3186 selection.start.row,
3187 selection.start.column - (prefix_len as u32),
3188 ),
3189 &bracket_pair.start[..prefix_len],
3190 ));
3191
3192 if autoclose
3193 && bracket_pair.close
3194 && following_text_allows_autoclose
3195 && preceding_text_matches_prefix
3196 {
3197 let anchor = snapshot.anchor_before(selection.end);
3198 new_selections.push((selection.map(|_| anchor), text.len()));
3199 new_autoclose_regions.push((
3200 anchor,
3201 text.len(),
3202 selection.id,
3203 bracket_pair.clone(),
3204 ));
3205 edits.push((
3206 selection.range(),
3207 format!("{}{}", text, bracket_pair.end).into(),
3208 ));
3209 bracket_inserted = true;
3210 continue;
3211 }
3212 }
3213
3214 if let Some(region) = autoclose_region {
3215 // If the selection is followed by an auto-inserted closing bracket,
3216 // then don't insert that closing bracket again; just move the selection
3217 // past the closing bracket.
3218 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3219 && text.as_ref() == region.pair.end.as_str();
3220 if should_skip {
3221 let anchor = snapshot.anchor_after(selection.end);
3222 new_selections
3223 .push((selection.map(|_| anchor), region.pair.end.len()));
3224 continue;
3225 }
3226 }
3227
3228 let always_treat_brackets_as_autoclosed = snapshot
3229 .settings_at(selection.start, cx)
3230 .always_treat_brackets_as_autoclosed;
3231 if always_treat_brackets_as_autoclosed
3232 && is_bracket_pair_end
3233 && snapshot.contains_str_at(selection.end, text.as_ref())
3234 {
3235 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3236 // and the inserted text is a closing bracket and the selection is followed
3237 // by the closing bracket then move the selection past the closing bracket.
3238 let anchor = snapshot.anchor_after(selection.end);
3239 new_selections.push((selection.map(|_| anchor), text.len()));
3240 continue;
3241 }
3242 }
3243 // If an opening bracket is 1 character long and is typed while
3244 // text is selected, then surround that text with the bracket pair.
3245 else if auto_surround
3246 && bracket_pair.surround
3247 && is_bracket_pair_start
3248 && bracket_pair.start.chars().count() == 1
3249 {
3250 edits.push((selection.start..selection.start, text.clone()));
3251 edits.push((
3252 selection.end..selection.end,
3253 bracket_pair.end.as_str().into(),
3254 ));
3255 bracket_inserted = true;
3256 new_selections.push((
3257 Selection {
3258 id: selection.id,
3259 start: snapshot.anchor_after(selection.start),
3260 end: snapshot.anchor_before(selection.end),
3261 reversed: selection.reversed,
3262 goal: selection.goal,
3263 },
3264 0,
3265 ));
3266 continue;
3267 }
3268 }
3269 }
3270
3271 if self.auto_replace_emoji_shortcode
3272 && selection.is_empty()
3273 && text.as_ref().ends_with(':')
3274 {
3275 if let Some(possible_emoji_short_code) =
3276 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3277 {
3278 if !possible_emoji_short_code.is_empty() {
3279 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3280 let emoji_shortcode_start = Point::new(
3281 selection.start.row,
3282 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3283 );
3284
3285 // Remove shortcode from buffer
3286 edits.push((
3287 emoji_shortcode_start..selection.start,
3288 "".to_string().into(),
3289 ));
3290 new_selections.push((
3291 Selection {
3292 id: selection.id,
3293 start: snapshot.anchor_after(emoji_shortcode_start),
3294 end: snapshot.anchor_before(selection.start),
3295 reversed: selection.reversed,
3296 goal: selection.goal,
3297 },
3298 0,
3299 ));
3300
3301 // Insert emoji
3302 let selection_start_anchor = snapshot.anchor_after(selection.start);
3303 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3304 edits.push((selection.start..selection.end, emoji.to_string().into()));
3305
3306 continue;
3307 }
3308 }
3309 }
3310 }
3311
3312 // If not handling any auto-close operation, then just replace the selected
3313 // text with the given input and move the selection to the end of the
3314 // newly inserted text.
3315 let anchor = snapshot.anchor_after(selection.end);
3316 if !self.linked_edit_ranges.is_empty() {
3317 let start_anchor = snapshot.anchor_before(selection.start);
3318
3319 let is_word_char = text.chars().next().map_or(true, |char| {
3320 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3321 classifier.is_word(char)
3322 });
3323
3324 if is_word_char {
3325 if let Some(ranges) = self
3326 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3327 {
3328 for (buffer, edits) in ranges {
3329 linked_edits
3330 .entry(buffer.clone())
3331 .or_default()
3332 .extend(edits.into_iter().map(|range| (range, text.clone())));
3333 }
3334 }
3335 }
3336 }
3337
3338 new_selections.push((selection.map(|_| anchor), 0));
3339 edits.push((selection.start..selection.end, text.clone()));
3340 }
3341
3342 drop(snapshot);
3343
3344 self.transact(cx, |this, cx| {
3345 this.buffer.update(cx, |buffer, cx| {
3346 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3347 });
3348 for (buffer, edits) in linked_edits {
3349 buffer.update(cx, |buffer, cx| {
3350 let snapshot = buffer.snapshot();
3351 let edits = edits
3352 .into_iter()
3353 .map(|(range, text)| {
3354 use text::ToPoint as TP;
3355 let end_point = TP::to_point(&range.end, &snapshot);
3356 let start_point = TP::to_point(&range.start, &snapshot);
3357 (start_point..end_point, text)
3358 })
3359 .sorted_by_key(|(range, _)| range.start)
3360 .collect::<Vec<_>>();
3361 buffer.edit(edits, None, cx);
3362 })
3363 }
3364 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3365 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3366 let snapshot = this.buffer.read(cx).read(cx);
3367 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3368 .zip(new_selection_deltas)
3369 .map(|(selection, delta)| Selection {
3370 id: selection.id,
3371 start: selection.start + delta,
3372 end: selection.end + delta,
3373 reversed: selection.reversed,
3374 goal: SelectionGoal::None,
3375 })
3376 .collect::<Vec<_>>();
3377
3378 let mut i = 0;
3379 for (position, delta, selection_id, pair) in new_autoclose_regions {
3380 let position = position.to_offset(&snapshot) + delta;
3381 let start = snapshot.anchor_before(position);
3382 let end = snapshot.anchor_after(position);
3383 while let Some(existing_state) = this.autoclose_regions.get(i) {
3384 match existing_state.range.start.cmp(&start, &snapshot) {
3385 Ordering::Less => i += 1,
3386 Ordering::Greater => break,
3387 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3388 Ordering::Less => i += 1,
3389 Ordering::Equal => break,
3390 Ordering::Greater => break,
3391 },
3392 }
3393 }
3394 this.autoclose_regions.insert(
3395 i,
3396 AutocloseRegion {
3397 selection_id,
3398 range: start..end,
3399 pair,
3400 },
3401 );
3402 }
3403
3404 drop(snapshot);
3405 let had_active_inline_completion = this.has_active_inline_completion(cx);
3406 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3407 s.select(new_selections)
3408 });
3409
3410 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3411 if let Some(on_type_format_task) =
3412 this.trigger_on_type_formatting(text.to_string(), cx)
3413 {
3414 on_type_format_task.detach_and_log_err(cx);
3415 }
3416 }
3417
3418 let editor_settings = EditorSettings::get_global(cx);
3419 if bracket_inserted
3420 && (editor_settings.auto_signature_help
3421 || editor_settings.show_signature_help_after_edits)
3422 {
3423 this.show_signature_help(&ShowSignatureHelp, cx);
3424 }
3425
3426 let trigger_in_words = !had_active_inline_completion;
3427 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3428 linked_editing_ranges::refresh_linked_ranges(this, cx);
3429 this.refresh_inline_completion(true, false, cx);
3430 });
3431 }
3432
3433 fn find_possible_emoji_shortcode_at_position(
3434 snapshot: &MultiBufferSnapshot,
3435 position: Point,
3436 ) -> Option<String> {
3437 let mut chars = Vec::new();
3438 let mut found_colon = false;
3439 for char in snapshot.reversed_chars_at(position).take(100) {
3440 // Found a possible emoji shortcode in the middle of the buffer
3441 if found_colon {
3442 if char.is_whitespace() {
3443 chars.reverse();
3444 return Some(chars.iter().collect());
3445 }
3446 // If the previous character is not a whitespace, we are in the middle of a word
3447 // and we only want to complete the shortcode if the word is made up of other emojis
3448 let mut containing_word = String::new();
3449 for ch in snapshot
3450 .reversed_chars_at(position)
3451 .skip(chars.len() + 1)
3452 .take(100)
3453 {
3454 if ch.is_whitespace() {
3455 break;
3456 }
3457 containing_word.push(ch);
3458 }
3459 let containing_word = containing_word.chars().rev().collect::<String>();
3460 if util::word_consists_of_emojis(containing_word.as_str()) {
3461 chars.reverse();
3462 return Some(chars.iter().collect());
3463 }
3464 }
3465
3466 if char.is_whitespace() || !char.is_ascii() {
3467 return None;
3468 }
3469 if char == ':' {
3470 found_colon = true;
3471 } else {
3472 chars.push(char);
3473 }
3474 }
3475 // Found a possible emoji shortcode at the beginning of the buffer
3476 chars.reverse();
3477 Some(chars.iter().collect())
3478 }
3479
3480 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3481 self.transact(cx, |this, cx| {
3482 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3483 let selections = this.selections.all::<usize>(cx);
3484 let multi_buffer = this.buffer.read(cx);
3485 let buffer = multi_buffer.snapshot(cx);
3486 selections
3487 .iter()
3488 .map(|selection| {
3489 let start_point = selection.start.to_point(&buffer);
3490 let mut indent =
3491 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3492 indent.len = cmp::min(indent.len, start_point.column);
3493 let start = selection.start;
3494 let end = selection.end;
3495 let selection_is_empty = start == end;
3496 let language_scope = buffer.language_scope_at(start);
3497 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3498 &language_scope
3499 {
3500 let leading_whitespace_len = buffer
3501 .reversed_chars_at(start)
3502 .take_while(|c| c.is_whitespace() && *c != '\n')
3503 .map(|c| c.len_utf8())
3504 .sum::<usize>();
3505
3506 let trailing_whitespace_len = buffer
3507 .chars_at(end)
3508 .take_while(|c| c.is_whitespace() && *c != '\n')
3509 .map(|c| c.len_utf8())
3510 .sum::<usize>();
3511
3512 let insert_extra_newline =
3513 language.brackets().any(|(pair, enabled)| {
3514 let pair_start = pair.start.trim_end();
3515 let pair_end = pair.end.trim_start();
3516
3517 enabled
3518 && pair.newline
3519 && buffer.contains_str_at(
3520 end + trailing_whitespace_len,
3521 pair_end,
3522 )
3523 && buffer.contains_str_at(
3524 (start - leading_whitespace_len)
3525 .saturating_sub(pair_start.len()),
3526 pair_start,
3527 )
3528 });
3529
3530 // Comment extension on newline is allowed only for cursor selections
3531 let comment_delimiter = maybe!({
3532 if !selection_is_empty {
3533 return None;
3534 }
3535
3536 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3537 return None;
3538 }
3539
3540 let delimiters = language.line_comment_prefixes();
3541 let max_len_of_delimiter =
3542 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3543 let (snapshot, range) =
3544 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3545
3546 let mut index_of_first_non_whitespace = 0;
3547 let comment_candidate = snapshot
3548 .chars_for_range(range)
3549 .skip_while(|c| {
3550 let should_skip = c.is_whitespace();
3551 if should_skip {
3552 index_of_first_non_whitespace += 1;
3553 }
3554 should_skip
3555 })
3556 .take(max_len_of_delimiter)
3557 .collect::<String>();
3558 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3559 comment_candidate.starts_with(comment_prefix.as_ref())
3560 })?;
3561 let cursor_is_placed_after_comment_marker =
3562 index_of_first_non_whitespace + comment_prefix.len()
3563 <= start_point.column as usize;
3564 if cursor_is_placed_after_comment_marker {
3565 Some(comment_prefix.clone())
3566 } else {
3567 None
3568 }
3569 });
3570 (comment_delimiter, insert_extra_newline)
3571 } else {
3572 (None, false)
3573 };
3574
3575 let capacity_for_delimiter = comment_delimiter
3576 .as_deref()
3577 .map(str::len)
3578 .unwrap_or_default();
3579 let mut new_text =
3580 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3581 new_text.push('\n');
3582 new_text.extend(indent.chars());
3583 if let Some(delimiter) = &comment_delimiter {
3584 new_text.push_str(delimiter);
3585 }
3586 if insert_extra_newline {
3587 new_text = new_text.repeat(2);
3588 }
3589
3590 let anchor = buffer.anchor_after(end);
3591 let new_selection = selection.map(|_| anchor);
3592 (
3593 (start..end, new_text),
3594 (insert_extra_newline, new_selection),
3595 )
3596 })
3597 .unzip()
3598 };
3599
3600 this.edit_with_autoindent(edits, cx);
3601 let buffer = this.buffer.read(cx).snapshot(cx);
3602 let new_selections = selection_fixup_info
3603 .into_iter()
3604 .map(|(extra_newline_inserted, new_selection)| {
3605 let mut cursor = new_selection.end.to_point(&buffer);
3606 if extra_newline_inserted {
3607 cursor.row -= 1;
3608 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3609 }
3610 new_selection.map(|_| cursor)
3611 })
3612 .collect();
3613
3614 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3615 this.refresh_inline_completion(true, false, cx);
3616 });
3617 }
3618
3619 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3620 let buffer = self.buffer.read(cx);
3621 let snapshot = buffer.snapshot(cx);
3622
3623 let mut edits = Vec::new();
3624 let mut rows = Vec::new();
3625
3626 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3627 let cursor = selection.head();
3628 let row = cursor.row;
3629
3630 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3631
3632 let newline = "\n".to_string();
3633 edits.push((start_of_line..start_of_line, newline));
3634
3635 rows.push(row + rows_inserted as u32);
3636 }
3637
3638 self.transact(cx, |editor, cx| {
3639 editor.edit(edits, cx);
3640
3641 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3642 let mut index = 0;
3643 s.move_cursors_with(|map, _, _| {
3644 let row = rows[index];
3645 index += 1;
3646
3647 let point = Point::new(row, 0);
3648 let boundary = map.next_line_boundary(point).1;
3649 let clipped = map.clip_point(boundary, Bias::Left);
3650
3651 (clipped, SelectionGoal::None)
3652 });
3653 });
3654
3655 let mut indent_edits = Vec::new();
3656 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3657 for row in rows {
3658 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3659 for (row, indent) in indents {
3660 if indent.len == 0 {
3661 continue;
3662 }
3663
3664 let text = match indent.kind {
3665 IndentKind::Space => " ".repeat(indent.len as usize),
3666 IndentKind::Tab => "\t".repeat(indent.len as usize),
3667 };
3668 let point = Point::new(row.0, 0);
3669 indent_edits.push((point..point, text));
3670 }
3671 }
3672 editor.edit(indent_edits, cx);
3673 });
3674 }
3675
3676 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3677 let buffer = self.buffer.read(cx);
3678 let snapshot = buffer.snapshot(cx);
3679
3680 let mut edits = Vec::new();
3681 let mut rows = Vec::new();
3682 let mut rows_inserted = 0;
3683
3684 for selection in self.selections.all_adjusted(cx) {
3685 let cursor = selection.head();
3686 let row = cursor.row;
3687
3688 let point = Point::new(row + 1, 0);
3689 let start_of_line = snapshot.clip_point(point, Bias::Left);
3690
3691 let newline = "\n".to_string();
3692 edits.push((start_of_line..start_of_line, newline));
3693
3694 rows_inserted += 1;
3695 rows.push(row + rows_inserted);
3696 }
3697
3698 self.transact(cx, |editor, cx| {
3699 editor.edit(edits, cx);
3700
3701 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3702 let mut index = 0;
3703 s.move_cursors_with(|map, _, _| {
3704 let row = rows[index];
3705 index += 1;
3706
3707 let point = Point::new(row, 0);
3708 let boundary = map.next_line_boundary(point).1;
3709 let clipped = map.clip_point(boundary, Bias::Left);
3710
3711 (clipped, SelectionGoal::None)
3712 });
3713 });
3714
3715 let mut indent_edits = Vec::new();
3716 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3717 for row in rows {
3718 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3719 for (row, indent) in indents {
3720 if indent.len == 0 {
3721 continue;
3722 }
3723
3724 let text = match indent.kind {
3725 IndentKind::Space => " ".repeat(indent.len as usize),
3726 IndentKind::Tab => "\t".repeat(indent.len as usize),
3727 };
3728 let point = Point::new(row.0, 0);
3729 indent_edits.push((point..point, text));
3730 }
3731 }
3732 editor.edit(indent_edits, cx);
3733 });
3734 }
3735
3736 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3737 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3738 original_indent_columns: Vec::new(),
3739 });
3740 self.insert_with_autoindent_mode(text, autoindent, cx);
3741 }
3742
3743 fn insert_with_autoindent_mode(
3744 &mut self,
3745 text: &str,
3746 autoindent_mode: Option<AutoindentMode>,
3747 cx: &mut ViewContext<Self>,
3748 ) {
3749 if self.read_only(cx) {
3750 return;
3751 }
3752
3753 let text: Arc<str> = text.into();
3754 self.transact(cx, |this, cx| {
3755 let old_selections = this.selections.all_adjusted(cx);
3756 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3757 let anchors = {
3758 let snapshot = buffer.read(cx);
3759 old_selections
3760 .iter()
3761 .map(|s| {
3762 let anchor = snapshot.anchor_after(s.head());
3763 s.map(|_| anchor)
3764 })
3765 .collect::<Vec<_>>()
3766 };
3767 buffer.edit(
3768 old_selections
3769 .iter()
3770 .map(|s| (s.start..s.end, text.clone())),
3771 autoindent_mode,
3772 cx,
3773 );
3774 anchors
3775 });
3776
3777 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3778 s.select_anchors(selection_anchors);
3779 })
3780 });
3781 }
3782
3783 fn trigger_completion_on_input(
3784 &mut self,
3785 text: &str,
3786 trigger_in_words: bool,
3787 cx: &mut ViewContext<Self>,
3788 ) {
3789 if self.is_completion_trigger(text, trigger_in_words, cx) {
3790 self.show_completions(
3791 &ShowCompletions {
3792 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3793 },
3794 cx,
3795 );
3796 } else {
3797 self.hide_context_menu(cx);
3798 }
3799 }
3800
3801 fn is_completion_trigger(
3802 &self,
3803 text: &str,
3804 trigger_in_words: bool,
3805 cx: &mut ViewContext<Self>,
3806 ) -> bool {
3807 let position = self.selections.newest_anchor().head();
3808 let multibuffer = self.buffer.read(cx);
3809 let Some(buffer) = position
3810 .buffer_id
3811 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3812 else {
3813 return false;
3814 };
3815
3816 if let Some(completion_provider) = &self.completion_provider {
3817 completion_provider.is_completion_trigger(
3818 &buffer,
3819 position.text_anchor,
3820 text,
3821 trigger_in_words,
3822 cx,
3823 )
3824 } else {
3825 false
3826 }
3827 }
3828
3829 /// If any empty selections is touching the start of its innermost containing autoclose
3830 /// region, expand it to select the brackets.
3831 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3832 let selections = self.selections.all::<usize>(cx);
3833 let buffer = self.buffer.read(cx).read(cx);
3834 let new_selections = self
3835 .selections_with_autoclose_regions(selections, &buffer)
3836 .map(|(mut selection, region)| {
3837 if !selection.is_empty() {
3838 return selection;
3839 }
3840
3841 if let Some(region) = region {
3842 let mut range = region.range.to_offset(&buffer);
3843 if selection.start == range.start && range.start >= region.pair.start.len() {
3844 range.start -= region.pair.start.len();
3845 if buffer.contains_str_at(range.start, ®ion.pair.start)
3846 && buffer.contains_str_at(range.end, ®ion.pair.end)
3847 {
3848 range.end += region.pair.end.len();
3849 selection.start = range.start;
3850 selection.end = range.end;
3851
3852 return selection;
3853 }
3854 }
3855 }
3856
3857 let always_treat_brackets_as_autoclosed = buffer
3858 .settings_at(selection.start, cx)
3859 .always_treat_brackets_as_autoclosed;
3860
3861 if !always_treat_brackets_as_autoclosed {
3862 return selection;
3863 }
3864
3865 if let Some(scope) = buffer.language_scope_at(selection.start) {
3866 for (pair, enabled) in scope.brackets() {
3867 if !enabled || !pair.close {
3868 continue;
3869 }
3870
3871 if buffer.contains_str_at(selection.start, &pair.end) {
3872 let pair_start_len = pair.start.len();
3873 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3874 {
3875 selection.start -= pair_start_len;
3876 selection.end += pair.end.len();
3877
3878 return selection;
3879 }
3880 }
3881 }
3882 }
3883
3884 selection
3885 })
3886 .collect();
3887
3888 drop(buffer);
3889 self.change_selections(None, cx, |selections| selections.select(new_selections));
3890 }
3891
3892 /// Iterate the given selections, and for each one, find the smallest surrounding
3893 /// autoclose region. This uses the ordering of the selections and the autoclose
3894 /// regions to avoid repeated comparisons.
3895 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3896 &'a self,
3897 selections: impl IntoIterator<Item = Selection<D>>,
3898 buffer: &'a MultiBufferSnapshot,
3899 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3900 let mut i = 0;
3901 let mut regions = self.autoclose_regions.as_slice();
3902 selections.into_iter().map(move |selection| {
3903 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3904
3905 let mut enclosing = None;
3906 while let Some(pair_state) = regions.get(i) {
3907 if pair_state.range.end.to_offset(buffer) < range.start {
3908 regions = ®ions[i + 1..];
3909 i = 0;
3910 } else if pair_state.range.start.to_offset(buffer) > range.end {
3911 break;
3912 } else {
3913 if pair_state.selection_id == selection.id {
3914 enclosing = Some(pair_state);
3915 }
3916 i += 1;
3917 }
3918 }
3919
3920 (selection.clone(), enclosing)
3921 })
3922 }
3923
3924 /// Remove any autoclose regions that no longer contain their selection.
3925 fn invalidate_autoclose_regions(
3926 &mut self,
3927 mut selections: &[Selection<Anchor>],
3928 buffer: &MultiBufferSnapshot,
3929 ) {
3930 self.autoclose_regions.retain(|state| {
3931 let mut i = 0;
3932 while let Some(selection) = selections.get(i) {
3933 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3934 selections = &selections[1..];
3935 continue;
3936 }
3937 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3938 break;
3939 }
3940 if selection.id == state.selection_id {
3941 return true;
3942 } else {
3943 i += 1;
3944 }
3945 }
3946 false
3947 });
3948 }
3949
3950 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3951 let offset = position.to_offset(buffer);
3952 let (word_range, kind) = buffer.surrounding_word(offset, true);
3953 if offset > word_range.start && kind == Some(CharKind::Word) {
3954 Some(
3955 buffer
3956 .text_for_range(word_range.start..offset)
3957 .collect::<String>(),
3958 )
3959 } else {
3960 None
3961 }
3962 }
3963
3964 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3965 self.refresh_inlay_hints(
3966 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3967 cx,
3968 );
3969 }
3970
3971 pub fn inlay_hints_enabled(&self) -> bool {
3972 self.inlay_hint_cache.enabled
3973 }
3974
3975 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3976 if self.project.is_none() || self.mode != EditorMode::Full {
3977 return;
3978 }
3979
3980 let reason_description = reason.description();
3981 let ignore_debounce = matches!(
3982 reason,
3983 InlayHintRefreshReason::SettingsChange(_)
3984 | InlayHintRefreshReason::Toggle(_)
3985 | InlayHintRefreshReason::ExcerptsRemoved(_)
3986 );
3987 let (invalidate_cache, required_languages) = match reason {
3988 InlayHintRefreshReason::Toggle(enabled) => {
3989 self.inlay_hint_cache.enabled = enabled;
3990 if enabled {
3991 (InvalidationStrategy::RefreshRequested, None)
3992 } else {
3993 self.inlay_hint_cache.clear();
3994 self.splice_inlays(
3995 self.visible_inlay_hints(cx)
3996 .iter()
3997 .map(|inlay| inlay.id)
3998 .collect(),
3999 Vec::new(),
4000 cx,
4001 );
4002 return;
4003 }
4004 }
4005 InlayHintRefreshReason::SettingsChange(new_settings) => {
4006 match self.inlay_hint_cache.update_settings(
4007 &self.buffer,
4008 new_settings,
4009 self.visible_inlay_hints(cx),
4010 cx,
4011 ) {
4012 ControlFlow::Break(Some(InlaySplice {
4013 to_remove,
4014 to_insert,
4015 })) => {
4016 self.splice_inlays(to_remove, to_insert, cx);
4017 return;
4018 }
4019 ControlFlow::Break(None) => return,
4020 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4021 }
4022 }
4023 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4024 if let Some(InlaySplice {
4025 to_remove,
4026 to_insert,
4027 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4028 {
4029 self.splice_inlays(to_remove, to_insert, cx);
4030 }
4031 return;
4032 }
4033 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4034 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4035 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4036 }
4037 InlayHintRefreshReason::RefreshRequested => {
4038 (InvalidationStrategy::RefreshRequested, None)
4039 }
4040 };
4041
4042 if let Some(InlaySplice {
4043 to_remove,
4044 to_insert,
4045 }) = self.inlay_hint_cache.spawn_hint_refresh(
4046 reason_description,
4047 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4048 invalidate_cache,
4049 ignore_debounce,
4050 cx,
4051 ) {
4052 self.splice_inlays(to_remove, to_insert, cx);
4053 }
4054 }
4055
4056 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4057 self.display_map
4058 .read(cx)
4059 .current_inlays()
4060 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4061 .cloned()
4062 .collect()
4063 }
4064
4065 pub fn excerpts_for_inlay_hints_query(
4066 &self,
4067 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4068 cx: &mut ViewContext<Editor>,
4069 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4070 let Some(project) = self.project.as_ref() else {
4071 return HashMap::default();
4072 };
4073 let project = project.read(cx);
4074 let multi_buffer = self.buffer().read(cx);
4075 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4076 let multi_buffer_visible_start = self
4077 .scroll_manager
4078 .anchor()
4079 .anchor
4080 .to_point(&multi_buffer_snapshot);
4081 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4082 multi_buffer_visible_start
4083 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4084 Bias::Left,
4085 );
4086 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4087 multi_buffer
4088 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4089 .into_iter()
4090 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4091 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4092 let buffer = buffer_handle.read(cx);
4093 let buffer_file = project::File::from_dyn(buffer.file())?;
4094 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4095 let worktree_entry = buffer_worktree
4096 .read(cx)
4097 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4098 if worktree_entry.is_ignored {
4099 return None;
4100 }
4101
4102 let language = buffer.language()?;
4103 if let Some(restrict_to_languages) = restrict_to_languages {
4104 if !restrict_to_languages.contains(language) {
4105 return None;
4106 }
4107 }
4108 Some((
4109 excerpt_id,
4110 (
4111 buffer_handle,
4112 buffer.version().clone(),
4113 excerpt_visible_range,
4114 ),
4115 ))
4116 })
4117 .collect()
4118 }
4119
4120 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4121 TextLayoutDetails {
4122 text_system: cx.text_system().clone(),
4123 editor_style: self.style.clone().unwrap(),
4124 rem_size: cx.rem_size(),
4125 scroll_anchor: self.scroll_manager.anchor(),
4126 visible_rows: self.visible_line_count(),
4127 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4128 }
4129 }
4130
4131 fn splice_inlays(
4132 &self,
4133 to_remove: Vec<InlayId>,
4134 to_insert: Vec<Inlay>,
4135 cx: &mut ViewContext<Self>,
4136 ) {
4137 self.display_map.update(cx, |display_map, cx| {
4138 display_map.splice_inlays(to_remove, to_insert, cx);
4139 });
4140 cx.notify();
4141 }
4142
4143 fn trigger_on_type_formatting(
4144 &self,
4145 input: String,
4146 cx: &mut ViewContext<Self>,
4147 ) -> Option<Task<Result<()>>> {
4148 if input.len() != 1 {
4149 return None;
4150 }
4151
4152 let project = self.project.as_ref()?;
4153 let position = self.selections.newest_anchor().head();
4154 let (buffer, buffer_position) = self
4155 .buffer
4156 .read(cx)
4157 .text_anchor_for_position(position, cx)?;
4158
4159 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4160 // hence we do LSP request & edit on host side only — add formats to host's history.
4161 let push_to_lsp_host_history = true;
4162 // If this is not the host, append its history with new edits.
4163 let push_to_client_history = project.read(cx).is_via_collab();
4164
4165 let on_type_formatting = project.update(cx, |project, cx| {
4166 project.on_type_format(
4167 buffer.clone(),
4168 buffer_position,
4169 input,
4170 push_to_lsp_host_history,
4171 cx,
4172 )
4173 });
4174 Some(cx.spawn(|editor, mut cx| async move {
4175 if let Some(transaction) = on_type_formatting.await? {
4176 if push_to_client_history {
4177 buffer
4178 .update(&mut cx, |buffer, _| {
4179 buffer.push_transaction(transaction, Instant::now());
4180 })
4181 .ok();
4182 }
4183 editor.update(&mut cx, |editor, cx| {
4184 editor.refresh_document_highlights(cx);
4185 })?;
4186 }
4187 Ok(())
4188 }))
4189 }
4190
4191 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4192 if self.pending_rename.is_some() {
4193 return;
4194 }
4195
4196 let Some(provider) = self.completion_provider.as_ref() else {
4197 return;
4198 };
4199
4200 let position = self.selections.newest_anchor().head();
4201 let (buffer, buffer_position) =
4202 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4203 output
4204 } else {
4205 return;
4206 };
4207
4208 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4209 let is_followup_invoke = {
4210 let context_menu_state = self.context_menu.read();
4211 matches!(
4212 context_menu_state.deref(),
4213 Some(ContextMenu::Completions(_))
4214 )
4215 };
4216 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4217 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4218 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4219 CompletionTriggerKind::TRIGGER_CHARACTER
4220 }
4221
4222 _ => CompletionTriggerKind::INVOKED,
4223 };
4224 let completion_context = CompletionContext {
4225 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4226 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4227 Some(String::from(trigger))
4228 } else {
4229 None
4230 }
4231 }),
4232 trigger_kind,
4233 };
4234 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4235 let sort_completions = provider.sort_completions();
4236
4237 let id = post_inc(&mut self.next_completion_id);
4238 let task = cx.spawn(|this, mut cx| {
4239 async move {
4240 this.update(&mut cx, |this, _| {
4241 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4242 })?;
4243 let completions = completions.await.log_err();
4244 let menu = if let Some(completions) = completions {
4245 let mut menu = CompletionsMenu {
4246 id,
4247 sort_completions,
4248 initial_position: position,
4249 match_candidates: completions
4250 .iter()
4251 .enumerate()
4252 .map(|(id, completion)| {
4253 StringMatchCandidate::new(
4254 id,
4255 completion.label.text[completion.label.filter_range.clone()]
4256 .into(),
4257 )
4258 })
4259 .collect(),
4260 buffer: buffer.clone(),
4261 completions: Arc::new(RwLock::new(completions.into())),
4262 matches: Vec::new().into(),
4263 selected_item: 0,
4264 scroll_handle: UniformListScrollHandle::new(),
4265 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4266 DebouncedDelay::new(),
4267 )),
4268 };
4269 menu.filter(query.as_deref(), cx.background_executor().clone())
4270 .await;
4271
4272 if menu.matches.is_empty() {
4273 None
4274 } else {
4275 this.update(&mut cx, |editor, cx| {
4276 let completions = menu.completions.clone();
4277 let matches = menu.matches.clone();
4278
4279 let delay_ms = EditorSettings::get_global(cx)
4280 .completion_documentation_secondary_query_debounce;
4281 let delay = Duration::from_millis(delay_ms);
4282 editor
4283 .completion_documentation_pre_resolve_debounce
4284 .fire_new(delay, cx, |editor, cx| {
4285 CompletionsMenu::pre_resolve_completion_documentation(
4286 buffer,
4287 completions,
4288 matches,
4289 editor,
4290 cx,
4291 )
4292 });
4293 })
4294 .ok();
4295 Some(menu)
4296 }
4297 } else {
4298 None
4299 };
4300
4301 this.update(&mut cx, |this, cx| {
4302 let mut context_menu = this.context_menu.write();
4303 match context_menu.as_ref() {
4304 None => {}
4305
4306 Some(ContextMenu::Completions(prev_menu)) => {
4307 if prev_menu.id > id {
4308 return;
4309 }
4310 }
4311
4312 _ => return,
4313 }
4314
4315 if this.focus_handle.is_focused(cx) && menu.is_some() {
4316 let menu = menu.unwrap();
4317 *context_menu = Some(ContextMenu::Completions(menu));
4318 drop(context_menu);
4319 this.discard_inline_completion(false, cx);
4320 cx.notify();
4321 } else if this.completion_tasks.len() <= 1 {
4322 // If there are no more completion tasks and the last menu was
4323 // empty, we should hide it. If it was already hidden, we should
4324 // also show the copilot completion when available.
4325 drop(context_menu);
4326 if this.hide_context_menu(cx).is_none() {
4327 this.update_visible_inline_completion(cx);
4328 }
4329 }
4330 })?;
4331
4332 Ok::<_, anyhow::Error>(())
4333 }
4334 .log_err()
4335 });
4336
4337 self.completion_tasks.push((id, task));
4338 }
4339
4340 pub fn confirm_completion(
4341 &mut self,
4342 action: &ConfirmCompletion,
4343 cx: &mut ViewContext<Self>,
4344 ) -> Option<Task<Result<()>>> {
4345 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4346 }
4347
4348 pub fn compose_completion(
4349 &mut self,
4350 action: &ComposeCompletion,
4351 cx: &mut ViewContext<Self>,
4352 ) -> Option<Task<Result<()>>> {
4353 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4354 }
4355
4356 fn do_completion(
4357 &mut self,
4358 item_ix: Option<usize>,
4359 intent: CompletionIntent,
4360 cx: &mut ViewContext<Editor>,
4361 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4362 use language::ToOffset as _;
4363
4364 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4365 menu
4366 } else {
4367 return None;
4368 };
4369
4370 let mat = completions_menu
4371 .matches
4372 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4373 let buffer_handle = completions_menu.buffer;
4374 let completions = completions_menu.completions.read();
4375 let completion = completions.get(mat.candidate_id)?;
4376 cx.stop_propagation();
4377
4378 let snippet;
4379 let text;
4380
4381 if completion.is_snippet() {
4382 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4383 text = snippet.as_ref().unwrap().text.clone();
4384 } else {
4385 snippet = None;
4386 text = completion.new_text.clone();
4387 };
4388 let selections = self.selections.all::<usize>(cx);
4389 let buffer = buffer_handle.read(cx);
4390 let old_range = completion.old_range.to_offset(buffer);
4391 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4392
4393 let newest_selection = self.selections.newest_anchor();
4394 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4395 return None;
4396 }
4397
4398 let lookbehind = newest_selection
4399 .start
4400 .text_anchor
4401 .to_offset(buffer)
4402 .saturating_sub(old_range.start);
4403 let lookahead = old_range
4404 .end
4405 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4406 let mut common_prefix_len = old_text
4407 .bytes()
4408 .zip(text.bytes())
4409 .take_while(|(a, b)| a == b)
4410 .count();
4411
4412 let snapshot = self.buffer.read(cx).snapshot(cx);
4413 let mut range_to_replace: Option<Range<isize>> = None;
4414 let mut ranges = Vec::new();
4415 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4416 for selection in &selections {
4417 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4418 let start = selection.start.saturating_sub(lookbehind);
4419 let end = selection.end + lookahead;
4420 if selection.id == newest_selection.id {
4421 range_to_replace = Some(
4422 ((start + common_prefix_len) as isize - selection.start as isize)
4423 ..(end as isize - selection.start as isize),
4424 );
4425 }
4426 ranges.push(start + common_prefix_len..end);
4427 } else {
4428 common_prefix_len = 0;
4429 ranges.clear();
4430 ranges.extend(selections.iter().map(|s| {
4431 if s.id == newest_selection.id {
4432 range_to_replace = Some(
4433 old_range.start.to_offset_utf16(&snapshot).0 as isize
4434 - selection.start as isize
4435 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4436 - selection.start as isize,
4437 );
4438 old_range.clone()
4439 } else {
4440 s.start..s.end
4441 }
4442 }));
4443 break;
4444 }
4445 if !self.linked_edit_ranges.is_empty() {
4446 let start_anchor = snapshot.anchor_before(selection.head());
4447 let end_anchor = snapshot.anchor_after(selection.tail());
4448 if let Some(ranges) = self
4449 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4450 {
4451 for (buffer, edits) in ranges {
4452 linked_edits.entry(buffer.clone()).or_default().extend(
4453 edits
4454 .into_iter()
4455 .map(|range| (range, text[common_prefix_len..].to_owned())),
4456 );
4457 }
4458 }
4459 }
4460 }
4461 let text = &text[common_prefix_len..];
4462
4463 cx.emit(EditorEvent::InputHandled {
4464 utf16_range_to_replace: range_to_replace,
4465 text: text.into(),
4466 });
4467
4468 self.transact(cx, |this, cx| {
4469 if let Some(mut snippet) = snippet {
4470 snippet.text = text.to_string();
4471 for tabstop in snippet.tabstops.iter_mut().flatten() {
4472 tabstop.start -= common_prefix_len as isize;
4473 tabstop.end -= common_prefix_len as isize;
4474 }
4475
4476 this.insert_snippet(&ranges, snippet, cx).log_err();
4477 } else {
4478 this.buffer.update(cx, |buffer, cx| {
4479 buffer.edit(
4480 ranges.iter().map(|range| (range.clone(), text)),
4481 this.autoindent_mode.clone(),
4482 cx,
4483 );
4484 });
4485 }
4486 for (buffer, edits) in linked_edits {
4487 buffer.update(cx, |buffer, cx| {
4488 let snapshot = buffer.snapshot();
4489 let edits = edits
4490 .into_iter()
4491 .map(|(range, text)| {
4492 use text::ToPoint as TP;
4493 let end_point = TP::to_point(&range.end, &snapshot);
4494 let start_point = TP::to_point(&range.start, &snapshot);
4495 (start_point..end_point, text)
4496 })
4497 .sorted_by_key(|(range, _)| range.start)
4498 .collect::<Vec<_>>();
4499 buffer.edit(edits, None, cx);
4500 })
4501 }
4502
4503 this.refresh_inline_completion(true, false, cx);
4504 });
4505
4506 let show_new_completions_on_confirm = completion
4507 .confirm
4508 .as_ref()
4509 .map_or(false, |confirm| confirm(intent, cx));
4510 if show_new_completions_on_confirm {
4511 self.show_completions(&ShowCompletions { trigger: None }, cx);
4512 }
4513
4514 let provider = self.completion_provider.as_ref()?;
4515 let apply_edits = provider.apply_additional_edits_for_completion(
4516 buffer_handle,
4517 completion.clone(),
4518 true,
4519 cx,
4520 );
4521
4522 let editor_settings = EditorSettings::get_global(cx);
4523 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4524 // After the code completion is finished, users often want to know what signatures are needed.
4525 // so we should automatically call signature_help
4526 self.show_signature_help(&ShowSignatureHelp, cx);
4527 }
4528
4529 Some(cx.foreground_executor().spawn(async move {
4530 apply_edits.await?;
4531 Ok(())
4532 }))
4533 }
4534
4535 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4536 let mut context_menu = self.context_menu.write();
4537 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4538 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4539 // Toggle if we're selecting the same one
4540 *context_menu = None;
4541 cx.notify();
4542 return;
4543 } else {
4544 // Otherwise, clear it and start a new one
4545 *context_menu = None;
4546 cx.notify();
4547 }
4548 }
4549 drop(context_menu);
4550 let snapshot = self.snapshot(cx);
4551 let deployed_from_indicator = action.deployed_from_indicator;
4552 let mut task = self.code_actions_task.take();
4553 let action = action.clone();
4554 cx.spawn(|editor, mut cx| async move {
4555 while let Some(prev_task) = task {
4556 prev_task.await;
4557 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4558 }
4559
4560 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4561 if editor.focus_handle.is_focused(cx) {
4562 let multibuffer_point = action
4563 .deployed_from_indicator
4564 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4565 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4566 let (buffer, buffer_row) = snapshot
4567 .buffer_snapshot
4568 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4569 .and_then(|(buffer_snapshot, range)| {
4570 editor
4571 .buffer
4572 .read(cx)
4573 .buffer(buffer_snapshot.remote_id())
4574 .map(|buffer| (buffer, range.start.row))
4575 })?;
4576 let (_, code_actions) = editor
4577 .available_code_actions
4578 .clone()
4579 .and_then(|(location, code_actions)| {
4580 let snapshot = location.buffer.read(cx).snapshot();
4581 let point_range = location.range.to_point(&snapshot);
4582 let point_range = point_range.start.row..=point_range.end.row;
4583 if point_range.contains(&buffer_row) {
4584 Some((location, code_actions))
4585 } else {
4586 None
4587 }
4588 })
4589 .unzip();
4590 let buffer_id = buffer.read(cx).remote_id();
4591 let tasks = editor
4592 .tasks
4593 .get(&(buffer_id, buffer_row))
4594 .map(|t| Arc::new(t.to_owned()));
4595 if tasks.is_none() && code_actions.is_none() {
4596 return None;
4597 }
4598
4599 editor.completion_tasks.clear();
4600 editor.discard_inline_completion(false, cx);
4601 let task_context =
4602 tasks
4603 .as_ref()
4604 .zip(editor.project.clone())
4605 .map(|(tasks, project)| {
4606 let position = Point::new(buffer_row, tasks.column);
4607 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4608 let location = Location {
4609 buffer: buffer.clone(),
4610 range: range_start..range_start,
4611 };
4612 // Fill in the environmental variables from the tree-sitter captures
4613 let mut captured_task_variables = TaskVariables::default();
4614 for (capture_name, value) in tasks.extra_variables.clone() {
4615 captured_task_variables.insert(
4616 task::VariableName::Custom(capture_name.into()),
4617 value.clone(),
4618 );
4619 }
4620 project.update(cx, |project, cx| {
4621 project.task_context_for_location(
4622 captured_task_variables,
4623 location,
4624 cx,
4625 )
4626 })
4627 });
4628
4629 Some(cx.spawn(|editor, mut cx| async move {
4630 let task_context = match task_context {
4631 Some(task_context) => task_context.await,
4632 None => None,
4633 };
4634 let resolved_tasks =
4635 tasks.zip(task_context).map(|(tasks, task_context)| {
4636 Arc::new(ResolvedTasks {
4637 templates: tasks
4638 .templates
4639 .iter()
4640 .filter_map(|(kind, template)| {
4641 template
4642 .resolve_task(&kind.to_id_base(), &task_context)
4643 .map(|task| (kind.clone(), task))
4644 })
4645 .collect(),
4646 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4647 multibuffer_point.row,
4648 tasks.column,
4649 )),
4650 })
4651 });
4652 let spawn_straight_away = resolved_tasks
4653 .as_ref()
4654 .map_or(false, |tasks| tasks.templates.len() == 1)
4655 && code_actions
4656 .as_ref()
4657 .map_or(true, |actions| actions.is_empty());
4658 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4659 *editor.context_menu.write() =
4660 Some(ContextMenu::CodeActions(CodeActionsMenu {
4661 buffer,
4662 actions: CodeActionContents {
4663 tasks: resolved_tasks,
4664 actions: code_actions,
4665 },
4666 selected_item: Default::default(),
4667 scroll_handle: UniformListScrollHandle::default(),
4668 deployed_from_indicator,
4669 }));
4670 if spawn_straight_away {
4671 if let Some(task) = editor.confirm_code_action(
4672 &ConfirmCodeAction { item_ix: Some(0) },
4673 cx,
4674 ) {
4675 cx.notify();
4676 return task;
4677 }
4678 }
4679 cx.notify();
4680 Task::ready(Ok(()))
4681 }) {
4682 task.await
4683 } else {
4684 Ok(())
4685 }
4686 }))
4687 } else {
4688 Some(Task::ready(Ok(())))
4689 }
4690 })?;
4691 if let Some(task) = spawned_test_task {
4692 task.await?;
4693 }
4694
4695 Ok::<_, anyhow::Error>(())
4696 })
4697 .detach_and_log_err(cx);
4698 }
4699
4700 pub fn confirm_code_action(
4701 &mut self,
4702 action: &ConfirmCodeAction,
4703 cx: &mut ViewContext<Self>,
4704 ) -> Option<Task<Result<()>>> {
4705 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4706 menu
4707 } else {
4708 return None;
4709 };
4710 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4711 let action = actions_menu.actions.get(action_ix)?;
4712 let title = action.label();
4713 let buffer = actions_menu.buffer;
4714 let workspace = self.workspace()?;
4715
4716 match action {
4717 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4718 workspace.update(cx, |workspace, cx| {
4719 workspace::tasks::schedule_resolved_task(
4720 workspace,
4721 task_source_kind,
4722 resolved_task,
4723 false,
4724 cx,
4725 );
4726
4727 Some(Task::ready(Ok(())))
4728 })
4729 }
4730 CodeActionsItem::CodeAction(action) => {
4731 let apply_code_actions = workspace
4732 .read(cx)
4733 .project()
4734 .clone()
4735 .update(cx, |project, cx| {
4736 project.apply_code_action(buffer, action, true, cx)
4737 });
4738 let workspace = workspace.downgrade();
4739 Some(cx.spawn(|editor, cx| async move {
4740 let project_transaction = apply_code_actions.await?;
4741 Self::open_project_transaction(
4742 &editor,
4743 workspace,
4744 project_transaction,
4745 title,
4746 cx,
4747 )
4748 .await
4749 }))
4750 }
4751 }
4752 }
4753
4754 pub async fn open_project_transaction(
4755 this: &WeakView<Editor>,
4756 workspace: WeakView<Workspace>,
4757 transaction: ProjectTransaction,
4758 title: String,
4759 mut cx: AsyncWindowContext,
4760 ) -> Result<()> {
4761 let replica_id = this.update(&mut cx, |this, cx| this.replica_id(cx))?;
4762
4763 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4764 cx.update(|cx| {
4765 entries.sort_unstable_by_key(|(buffer, _)| {
4766 buffer.read(cx).file().map(|f| f.path().clone())
4767 });
4768 })?;
4769
4770 // If the project transaction's edits are all contained within this editor, then
4771 // avoid opening a new editor to display them.
4772
4773 if let Some((buffer, transaction)) = entries.first() {
4774 if entries.len() == 1 {
4775 let excerpt = this.update(&mut cx, |editor, cx| {
4776 editor
4777 .buffer()
4778 .read(cx)
4779 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4780 })?;
4781 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4782 if excerpted_buffer == *buffer {
4783 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4784 let excerpt_range = excerpt_range.to_offset(buffer);
4785 buffer
4786 .edited_ranges_for_transaction::<usize>(transaction)
4787 .all(|range| {
4788 excerpt_range.start <= range.start
4789 && excerpt_range.end >= range.end
4790 })
4791 })?;
4792
4793 if all_edits_within_excerpt {
4794 return Ok(());
4795 }
4796 }
4797 }
4798 }
4799 } else {
4800 return Ok(());
4801 }
4802
4803 let mut ranges_to_highlight = Vec::new();
4804 let excerpt_buffer = cx.new_model(|cx| {
4805 let mut multibuffer =
4806 MultiBuffer::new(replica_id, Capability::ReadWrite).with_title(title);
4807 for (buffer_handle, transaction) in &entries {
4808 let buffer = buffer_handle.read(cx);
4809 ranges_to_highlight.extend(
4810 multibuffer.push_excerpts_with_context_lines(
4811 buffer_handle.clone(),
4812 buffer
4813 .edited_ranges_for_transaction::<usize>(transaction)
4814 .collect(),
4815 DEFAULT_MULTIBUFFER_CONTEXT,
4816 cx,
4817 ),
4818 );
4819 }
4820 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4821 multibuffer
4822 })?;
4823
4824 workspace.update(&mut cx, |workspace, cx| {
4825 let project = workspace.project().clone();
4826 let editor =
4827 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4828 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4829 editor.update(cx, |editor, cx| {
4830 editor.highlight_background::<Self>(
4831 &ranges_to_highlight,
4832 |theme| theme.editor_highlighted_line_background,
4833 cx,
4834 );
4835 });
4836 })?;
4837
4838 Ok(())
4839 }
4840
4841 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4842 let project = self.project.clone()?;
4843 let buffer = self.buffer.read(cx);
4844 let newest_selection = self.selections.newest_anchor().clone();
4845 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4846 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4847 if start_buffer != end_buffer {
4848 return None;
4849 }
4850
4851 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4852 cx.background_executor()
4853 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4854 .await;
4855
4856 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4857 project.code_actions(&start_buffer, start..end, cx)
4858 }) {
4859 code_actions.await
4860 } else {
4861 Vec::new()
4862 };
4863
4864 this.update(&mut cx, |this, cx| {
4865 this.available_code_actions = if actions.is_empty() {
4866 None
4867 } else {
4868 Some((
4869 Location {
4870 buffer: start_buffer,
4871 range: start..end,
4872 },
4873 actions.into(),
4874 ))
4875 };
4876 cx.notify();
4877 })
4878 .log_err();
4879 }));
4880 None
4881 }
4882
4883 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4884 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4885 self.show_git_blame_inline = false;
4886
4887 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4888 cx.background_executor().timer(delay).await;
4889
4890 this.update(&mut cx, |this, cx| {
4891 this.show_git_blame_inline = true;
4892 cx.notify();
4893 })
4894 .log_err();
4895 }));
4896 }
4897 }
4898
4899 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4900 if self.pending_rename.is_some() {
4901 return None;
4902 }
4903
4904 let project = self.project.clone()?;
4905 let buffer = self.buffer.read(cx);
4906 let newest_selection = self.selections.newest_anchor().clone();
4907 let cursor_position = newest_selection.head();
4908 let (cursor_buffer, cursor_buffer_position) =
4909 buffer.text_anchor_for_position(cursor_position, cx)?;
4910 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4911 if cursor_buffer != tail_buffer {
4912 return None;
4913 }
4914
4915 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4916 cx.background_executor()
4917 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4918 .await;
4919
4920 let highlights = if let Some(highlights) = project
4921 .update(&mut cx, |project, cx| {
4922 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4923 })
4924 .log_err()
4925 {
4926 highlights.await.log_err()
4927 } else {
4928 None
4929 };
4930
4931 if let Some(highlights) = highlights {
4932 this.update(&mut cx, |this, cx| {
4933 if this.pending_rename.is_some() {
4934 return;
4935 }
4936
4937 let buffer_id = cursor_position.buffer_id;
4938 let buffer = this.buffer.read(cx);
4939 if !buffer
4940 .text_anchor_for_position(cursor_position, cx)
4941 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4942 {
4943 return;
4944 }
4945
4946 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4947 let mut write_ranges = Vec::new();
4948 let mut read_ranges = Vec::new();
4949 for highlight in highlights {
4950 for (excerpt_id, excerpt_range) in
4951 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4952 {
4953 let start = highlight
4954 .range
4955 .start
4956 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4957 let end = highlight
4958 .range
4959 .end
4960 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4961 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4962 continue;
4963 }
4964
4965 let range = Anchor {
4966 buffer_id,
4967 excerpt_id,
4968 text_anchor: start,
4969 }..Anchor {
4970 buffer_id,
4971 excerpt_id,
4972 text_anchor: end,
4973 };
4974 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4975 write_ranges.push(range);
4976 } else {
4977 read_ranges.push(range);
4978 }
4979 }
4980 }
4981
4982 this.highlight_background::<DocumentHighlightRead>(
4983 &read_ranges,
4984 |theme| theme.editor_document_highlight_read_background,
4985 cx,
4986 );
4987 this.highlight_background::<DocumentHighlightWrite>(
4988 &write_ranges,
4989 |theme| theme.editor_document_highlight_write_background,
4990 cx,
4991 );
4992 cx.notify();
4993 })
4994 .log_err();
4995 }
4996 }));
4997 None
4998 }
4999
5000 pub fn refresh_inline_completion(
5001 &mut self,
5002 debounce: bool,
5003 user_requested: bool,
5004 cx: &mut ViewContext<Self>,
5005 ) -> Option<()> {
5006 let provider = self.inline_completion_provider()?;
5007 let cursor = self.selections.newest_anchor().head();
5008 let (buffer, cursor_buffer_position) =
5009 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5010
5011 if !user_requested
5012 && (!self.enable_inline_completions
5013 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5014 {
5015 self.discard_inline_completion(false, cx);
5016 return None;
5017 }
5018
5019 self.update_visible_inline_completion(cx);
5020 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5021 Some(())
5022 }
5023
5024 fn cycle_inline_completion(
5025 &mut self,
5026 direction: Direction,
5027 cx: &mut ViewContext<Self>,
5028 ) -> Option<()> {
5029 let provider = self.inline_completion_provider()?;
5030 let cursor = self.selections.newest_anchor().head();
5031 let (buffer, cursor_buffer_position) =
5032 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5033 if !self.enable_inline_completions
5034 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5035 {
5036 return None;
5037 }
5038
5039 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5040 self.update_visible_inline_completion(cx);
5041
5042 Some(())
5043 }
5044
5045 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5046 if !self.has_active_inline_completion(cx) {
5047 self.refresh_inline_completion(false, true, cx);
5048 return;
5049 }
5050
5051 self.update_visible_inline_completion(cx);
5052 }
5053
5054 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5055 self.show_cursor_names(cx);
5056 }
5057
5058 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5059 self.show_cursor_names = true;
5060 cx.notify();
5061 cx.spawn(|this, mut cx| async move {
5062 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5063 this.update(&mut cx, |this, cx| {
5064 this.show_cursor_names = false;
5065 cx.notify()
5066 })
5067 .ok()
5068 })
5069 .detach();
5070 }
5071
5072 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5073 if self.has_active_inline_completion(cx) {
5074 self.cycle_inline_completion(Direction::Next, cx);
5075 } else {
5076 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5077 if is_copilot_disabled {
5078 cx.propagate();
5079 }
5080 }
5081 }
5082
5083 pub fn previous_inline_completion(
5084 &mut self,
5085 _: &PreviousInlineCompletion,
5086 cx: &mut ViewContext<Self>,
5087 ) {
5088 if self.has_active_inline_completion(cx) {
5089 self.cycle_inline_completion(Direction::Prev, cx);
5090 } else {
5091 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5092 if is_copilot_disabled {
5093 cx.propagate();
5094 }
5095 }
5096 }
5097
5098 pub fn accept_inline_completion(
5099 &mut self,
5100 _: &AcceptInlineCompletion,
5101 cx: &mut ViewContext<Self>,
5102 ) {
5103 let Some(completion) = self.take_active_inline_completion(cx) else {
5104 return;
5105 };
5106 if let Some(provider) = self.inline_completion_provider() {
5107 provider.accept(cx);
5108 }
5109
5110 cx.emit(EditorEvent::InputHandled {
5111 utf16_range_to_replace: None,
5112 text: completion.text.to_string().into(),
5113 });
5114
5115 if let Some(range) = completion.delete_range {
5116 self.change_selections(None, cx, |s| s.select_ranges([range]))
5117 }
5118 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5119 self.refresh_inline_completion(true, true, cx);
5120 cx.notify();
5121 }
5122
5123 pub fn accept_partial_inline_completion(
5124 &mut self,
5125 _: &AcceptPartialInlineCompletion,
5126 cx: &mut ViewContext<Self>,
5127 ) {
5128 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5129 if let Some(completion) = self.take_active_inline_completion(cx) {
5130 let mut partial_completion = completion
5131 .text
5132 .chars()
5133 .by_ref()
5134 .take_while(|c| c.is_alphabetic())
5135 .collect::<String>();
5136 if partial_completion.is_empty() {
5137 partial_completion = completion
5138 .text
5139 .chars()
5140 .by_ref()
5141 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5142 .collect::<String>();
5143 }
5144
5145 cx.emit(EditorEvent::InputHandled {
5146 utf16_range_to_replace: None,
5147 text: partial_completion.clone().into(),
5148 });
5149
5150 if let Some(range) = completion.delete_range {
5151 self.change_selections(None, cx, |s| s.select_ranges([range]))
5152 }
5153 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5154
5155 self.refresh_inline_completion(true, true, cx);
5156 cx.notify();
5157 }
5158 }
5159 }
5160
5161 fn discard_inline_completion(
5162 &mut self,
5163 should_report_inline_completion_event: bool,
5164 cx: &mut ViewContext<Self>,
5165 ) -> bool {
5166 if let Some(provider) = self.inline_completion_provider() {
5167 provider.discard(should_report_inline_completion_event, cx);
5168 }
5169
5170 self.take_active_inline_completion(cx).is_some()
5171 }
5172
5173 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5174 if let Some(completion) = self.active_inline_completion.as_ref() {
5175 let buffer = self.buffer.read(cx).read(cx);
5176 completion.position.is_valid(&buffer)
5177 } else {
5178 false
5179 }
5180 }
5181
5182 fn take_active_inline_completion(
5183 &mut self,
5184 cx: &mut ViewContext<Self>,
5185 ) -> Option<CompletionState> {
5186 let completion = self.active_inline_completion.take()?;
5187 let render_inlay_ids = completion.render_inlay_ids.clone();
5188 self.display_map.update(cx, |map, cx| {
5189 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5190 });
5191 let buffer = self.buffer.read(cx).read(cx);
5192
5193 if completion.position.is_valid(&buffer) {
5194 Some(completion)
5195 } else {
5196 None
5197 }
5198 }
5199
5200 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5201 let selection = self.selections.newest_anchor();
5202 let cursor = selection.head();
5203
5204 let excerpt_id = cursor.excerpt_id;
5205
5206 if self.context_menu.read().is_none()
5207 && self.completion_tasks.is_empty()
5208 && selection.start == selection.end
5209 {
5210 if let Some(provider) = self.inline_completion_provider() {
5211 if let Some((buffer, cursor_buffer_position)) =
5212 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5213 {
5214 if let Some(proposal) =
5215 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5216 {
5217 let mut to_remove = Vec::new();
5218 if let Some(completion) = self.active_inline_completion.take() {
5219 to_remove.extend(completion.render_inlay_ids.iter());
5220 }
5221
5222 let to_add = proposal
5223 .inlays
5224 .iter()
5225 .filter_map(|inlay| {
5226 let snapshot = self.buffer.read(cx).snapshot(cx);
5227 let id = post_inc(&mut self.next_inlay_id);
5228 match inlay {
5229 InlayProposal::Hint(position, hint) => {
5230 let position =
5231 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5232 Some(Inlay::hint(id, position, hint))
5233 }
5234 InlayProposal::Suggestion(position, text) => {
5235 let position =
5236 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5237 Some(Inlay::suggestion(id, position, text.clone()))
5238 }
5239 }
5240 })
5241 .collect_vec();
5242
5243 self.active_inline_completion = Some(CompletionState {
5244 position: cursor,
5245 text: proposal.text,
5246 delete_range: proposal.delete_range.and_then(|range| {
5247 let snapshot = self.buffer.read(cx).snapshot(cx);
5248 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5249 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5250 Some(start?..end?)
5251 }),
5252 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5253 });
5254
5255 self.display_map
5256 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5257
5258 cx.notify();
5259 return;
5260 }
5261 }
5262 }
5263 }
5264
5265 self.discard_inline_completion(false, cx);
5266 }
5267
5268 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5269 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5270 }
5271
5272 fn render_code_actions_indicator(
5273 &self,
5274 _style: &EditorStyle,
5275 row: DisplayRow,
5276 is_active: bool,
5277 cx: &mut ViewContext<Self>,
5278 ) -> Option<IconButton> {
5279 if self.available_code_actions.is_some() {
5280 Some(
5281 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5282 .shape(ui::IconButtonShape::Square)
5283 .icon_size(IconSize::XSmall)
5284 .icon_color(Color::Muted)
5285 .selected(is_active)
5286 .on_click(cx.listener(move |editor, _e, cx| {
5287 editor.focus(cx);
5288 editor.toggle_code_actions(
5289 &ToggleCodeActions {
5290 deployed_from_indicator: Some(row),
5291 },
5292 cx,
5293 );
5294 })),
5295 )
5296 } else {
5297 None
5298 }
5299 }
5300
5301 fn clear_tasks(&mut self) {
5302 self.tasks.clear()
5303 }
5304
5305 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5306 if self.tasks.insert(key, value).is_some() {
5307 // This case should hopefully be rare, but just in case...
5308 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5309 }
5310 }
5311
5312 fn render_run_indicator(
5313 &self,
5314 _style: &EditorStyle,
5315 is_active: bool,
5316 row: DisplayRow,
5317 cx: &mut ViewContext<Self>,
5318 ) -> IconButton {
5319 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5320 .shape(ui::IconButtonShape::Square)
5321 .icon_size(IconSize::XSmall)
5322 .icon_color(Color::Muted)
5323 .selected(is_active)
5324 .on_click(cx.listener(move |editor, _e, cx| {
5325 editor.focus(cx);
5326 editor.toggle_code_actions(
5327 &ToggleCodeActions {
5328 deployed_from_indicator: Some(row),
5329 },
5330 cx,
5331 );
5332 }))
5333 }
5334
5335 fn close_hunk_diff_button(
5336 &self,
5337 hunk: HoveredHunk,
5338 row: DisplayRow,
5339 cx: &mut ViewContext<Self>,
5340 ) -> IconButton {
5341 IconButton::new(
5342 ("close_hunk_diff_indicator", row.0 as usize),
5343 ui::IconName::Close,
5344 )
5345 .shape(ui::IconButtonShape::Square)
5346 .icon_size(IconSize::XSmall)
5347 .icon_color(Color::Muted)
5348 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5349 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5350 }
5351
5352 pub fn context_menu_visible(&self) -> bool {
5353 self.context_menu
5354 .read()
5355 .as_ref()
5356 .map_or(false, |menu| menu.visible())
5357 }
5358
5359 fn render_context_menu(
5360 &self,
5361 cursor_position: DisplayPoint,
5362 style: &EditorStyle,
5363 max_height: Pixels,
5364 cx: &mut ViewContext<Editor>,
5365 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5366 self.context_menu.read().as_ref().map(|menu| {
5367 menu.render(
5368 cursor_position,
5369 style,
5370 max_height,
5371 self.workspace.as_ref().map(|(w, _)| w.clone()),
5372 cx,
5373 )
5374 })
5375 }
5376
5377 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5378 cx.notify();
5379 self.completion_tasks.clear();
5380 let context_menu = self.context_menu.write().take();
5381 if context_menu.is_some() {
5382 self.update_visible_inline_completion(cx);
5383 }
5384 context_menu
5385 }
5386
5387 pub fn insert_snippet(
5388 &mut self,
5389 insertion_ranges: &[Range<usize>],
5390 snippet: Snippet,
5391 cx: &mut ViewContext<Self>,
5392 ) -> Result<()> {
5393 struct Tabstop<T> {
5394 is_end_tabstop: bool,
5395 ranges: Vec<Range<T>>,
5396 }
5397
5398 let tabstops = self.buffer.update(cx, |buffer, cx| {
5399 let snippet_text: Arc<str> = snippet.text.clone().into();
5400 buffer.edit(
5401 insertion_ranges
5402 .iter()
5403 .cloned()
5404 .map(|range| (range, snippet_text.clone())),
5405 Some(AutoindentMode::EachLine),
5406 cx,
5407 );
5408
5409 let snapshot = &*buffer.read(cx);
5410 let snippet = &snippet;
5411 snippet
5412 .tabstops
5413 .iter()
5414 .map(|tabstop| {
5415 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5416 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5417 });
5418 let mut tabstop_ranges = tabstop
5419 .iter()
5420 .flat_map(|tabstop_range| {
5421 let mut delta = 0_isize;
5422 insertion_ranges.iter().map(move |insertion_range| {
5423 let insertion_start = insertion_range.start as isize + delta;
5424 delta +=
5425 snippet.text.len() as isize - insertion_range.len() as isize;
5426
5427 let start = ((insertion_start + tabstop_range.start) as usize)
5428 .min(snapshot.len());
5429 let end = ((insertion_start + tabstop_range.end) as usize)
5430 .min(snapshot.len());
5431 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5432 })
5433 })
5434 .collect::<Vec<_>>();
5435 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5436
5437 Tabstop {
5438 is_end_tabstop,
5439 ranges: tabstop_ranges,
5440 }
5441 })
5442 .collect::<Vec<_>>()
5443 });
5444 if let Some(tabstop) = tabstops.first() {
5445 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5446 s.select_ranges(tabstop.ranges.iter().cloned());
5447 });
5448
5449 // If we're already at the last tabstop and it's at the end of the snippet,
5450 // we're done, we don't need to keep the state around.
5451 if !tabstop.is_end_tabstop {
5452 let ranges = tabstops
5453 .into_iter()
5454 .map(|tabstop| tabstop.ranges)
5455 .collect::<Vec<_>>();
5456 self.snippet_stack.push(SnippetState {
5457 active_index: 0,
5458 ranges,
5459 });
5460 }
5461
5462 // Check whether the just-entered snippet ends with an auto-closable bracket.
5463 if self.autoclose_regions.is_empty() {
5464 let snapshot = self.buffer.read(cx).snapshot(cx);
5465 for selection in &mut self.selections.all::<Point>(cx) {
5466 let selection_head = selection.head();
5467 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5468 continue;
5469 };
5470
5471 let mut bracket_pair = None;
5472 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5473 let prev_chars = snapshot
5474 .reversed_chars_at(selection_head)
5475 .collect::<String>();
5476 for (pair, enabled) in scope.brackets() {
5477 if enabled
5478 && pair.close
5479 && prev_chars.starts_with(pair.start.as_str())
5480 && next_chars.starts_with(pair.end.as_str())
5481 {
5482 bracket_pair = Some(pair.clone());
5483 break;
5484 }
5485 }
5486 if let Some(pair) = bracket_pair {
5487 let start = snapshot.anchor_after(selection_head);
5488 let end = snapshot.anchor_after(selection_head);
5489 self.autoclose_regions.push(AutocloseRegion {
5490 selection_id: selection.id,
5491 range: start..end,
5492 pair,
5493 });
5494 }
5495 }
5496 }
5497 }
5498 Ok(())
5499 }
5500
5501 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5502 self.move_to_snippet_tabstop(Bias::Right, cx)
5503 }
5504
5505 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5506 self.move_to_snippet_tabstop(Bias::Left, cx)
5507 }
5508
5509 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5510 if let Some(mut snippet) = self.snippet_stack.pop() {
5511 match bias {
5512 Bias::Left => {
5513 if snippet.active_index > 0 {
5514 snippet.active_index -= 1;
5515 } else {
5516 self.snippet_stack.push(snippet);
5517 return false;
5518 }
5519 }
5520 Bias::Right => {
5521 if snippet.active_index + 1 < snippet.ranges.len() {
5522 snippet.active_index += 1;
5523 } else {
5524 self.snippet_stack.push(snippet);
5525 return false;
5526 }
5527 }
5528 }
5529 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5530 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5531 s.select_anchor_ranges(current_ranges.iter().cloned())
5532 });
5533 // If snippet state is not at the last tabstop, push it back on the stack
5534 if snippet.active_index + 1 < snippet.ranges.len() {
5535 self.snippet_stack.push(snippet);
5536 }
5537 return true;
5538 }
5539 }
5540
5541 false
5542 }
5543
5544 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5545 self.transact(cx, |this, cx| {
5546 this.select_all(&SelectAll, cx);
5547 this.insert("", cx);
5548 });
5549 }
5550
5551 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5552 self.transact(cx, |this, cx| {
5553 this.select_autoclose_pair(cx);
5554 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5555 if !this.linked_edit_ranges.is_empty() {
5556 let selections = this.selections.all::<MultiBufferPoint>(cx);
5557 let snapshot = this.buffer.read(cx).snapshot(cx);
5558
5559 for selection in selections.iter() {
5560 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5561 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5562 if selection_start.buffer_id != selection_end.buffer_id {
5563 continue;
5564 }
5565 if let Some(ranges) =
5566 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5567 {
5568 for (buffer, entries) in ranges {
5569 linked_ranges.entry(buffer).or_default().extend(entries);
5570 }
5571 }
5572 }
5573 }
5574
5575 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5576 if !this.selections.line_mode {
5577 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5578 for selection in &mut selections {
5579 if selection.is_empty() {
5580 let old_head = selection.head();
5581 let mut new_head =
5582 movement::left(&display_map, old_head.to_display_point(&display_map))
5583 .to_point(&display_map);
5584 if let Some((buffer, line_buffer_range)) = display_map
5585 .buffer_snapshot
5586 .buffer_line_for_row(MultiBufferRow(old_head.row))
5587 {
5588 let indent_size =
5589 buffer.indent_size_for_line(line_buffer_range.start.row);
5590 let indent_len = match indent_size.kind {
5591 IndentKind::Space => {
5592 buffer.settings_at(line_buffer_range.start, cx).tab_size
5593 }
5594 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5595 };
5596 if old_head.column <= indent_size.len && old_head.column > 0 {
5597 let indent_len = indent_len.get();
5598 new_head = cmp::min(
5599 new_head,
5600 MultiBufferPoint::new(
5601 old_head.row,
5602 ((old_head.column - 1) / indent_len) * indent_len,
5603 ),
5604 );
5605 }
5606 }
5607
5608 selection.set_head(new_head, SelectionGoal::None);
5609 }
5610 }
5611 }
5612
5613 this.signature_help_state.set_backspace_pressed(true);
5614 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5615 this.insert("", cx);
5616 let empty_str: Arc<str> = Arc::from("");
5617 for (buffer, edits) in linked_ranges {
5618 let snapshot = buffer.read(cx).snapshot();
5619 use text::ToPoint as TP;
5620
5621 let edits = edits
5622 .into_iter()
5623 .map(|range| {
5624 let end_point = TP::to_point(&range.end, &snapshot);
5625 let mut start_point = TP::to_point(&range.start, &snapshot);
5626
5627 if end_point == start_point {
5628 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5629 .saturating_sub(1);
5630 start_point = TP::to_point(&offset, &snapshot);
5631 };
5632
5633 (start_point..end_point, empty_str.clone())
5634 })
5635 .sorted_by_key(|(range, _)| range.start)
5636 .collect::<Vec<_>>();
5637 buffer.update(cx, |this, cx| {
5638 this.edit(edits, None, cx);
5639 })
5640 }
5641 this.refresh_inline_completion(true, false, cx);
5642 linked_editing_ranges::refresh_linked_ranges(this, cx);
5643 });
5644 }
5645
5646 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5647 self.transact(cx, |this, cx| {
5648 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5649 let line_mode = s.line_mode;
5650 s.move_with(|map, selection| {
5651 if selection.is_empty() && !line_mode {
5652 let cursor = movement::right(map, selection.head());
5653 selection.end = cursor;
5654 selection.reversed = true;
5655 selection.goal = SelectionGoal::None;
5656 }
5657 })
5658 });
5659 this.insert("", cx);
5660 this.refresh_inline_completion(true, false, cx);
5661 });
5662 }
5663
5664 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5665 if self.move_to_prev_snippet_tabstop(cx) {
5666 return;
5667 }
5668
5669 self.outdent(&Outdent, cx);
5670 }
5671
5672 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5673 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5674 return;
5675 }
5676
5677 let mut selections = self.selections.all_adjusted(cx);
5678 let buffer = self.buffer.read(cx);
5679 let snapshot = buffer.snapshot(cx);
5680 let rows_iter = selections.iter().map(|s| s.head().row);
5681 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5682
5683 let mut edits = Vec::new();
5684 let mut prev_edited_row = 0;
5685 let mut row_delta = 0;
5686 for selection in &mut selections {
5687 if selection.start.row != prev_edited_row {
5688 row_delta = 0;
5689 }
5690 prev_edited_row = selection.end.row;
5691
5692 // If the selection is non-empty, then increase the indentation of the selected lines.
5693 if !selection.is_empty() {
5694 row_delta =
5695 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5696 continue;
5697 }
5698
5699 // If the selection is empty and the cursor is in the leading whitespace before the
5700 // suggested indentation, then auto-indent the line.
5701 let cursor = selection.head();
5702 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5703 if let Some(suggested_indent) =
5704 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5705 {
5706 if cursor.column < suggested_indent.len
5707 && cursor.column <= current_indent.len
5708 && current_indent.len <= suggested_indent.len
5709 {
5710 selection.start = Point::new(cursor.row, suggested_indent.len);
5711 selection.end = selection.start;
5712 if row_delta == 0 {
5713 edits.extend(Buffer::edit_for_indent_size_adjustment(
5714 cursor.row,
5715 current_indent,
5716 suggested_indent,
5717 ));
5718 row_delta = suggested_indent.len - current_indent.len;
5719 }
5720 continue;
5721 }
5722 }
5723
5724 // Otherwise, insert a hard or soft tab.
5725 let settings = buffer.settings_at(cursor, cx);
5726 let tab_size = if settings.hard_tabs {
5727 IndentSize::tab()
5728 } else {
5729 let tab_size = settings.tab_size.get();
5730 let char_column = snapshot
5731 .text_for_range(Point::new(cursor.row, 0)..cursor)
5732 .flat_map(str::chars)
5733 .count()
5734 + row_delta as usize;
5735 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5736 IndentSize::spaces(chars_to_next_tab_stop)
5737 };
5738 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5739 selection.end = selection.start;
5740 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5741 row_delta += tab_size.len;
5742 }
5743
5744 self.transact(cx, |this, cx| {
5745 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5746 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5747 this.refresh_inline_completion(true, false, cx);
5748 });
5749 }
5750
5751 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5752 if self.read_only(cx) {
5753 return;
5754 }
5755 let mut selections = self.selections.all::<Point>(cx);
5756 let mut prev_edited_row = 0;
5757 let mut row_delta = 0;
5758 let mut edits = Vec::new();
5759 let buffer = self.buffer.read(cx);
5760 let snapshot = buffer.snapshot(cx);
5761 for selection in &mut selections {
5762 if selection.start.row != prev_edited_row {
5763 row_delta = 0;
5764 }
5765 prev_edited_row = selection.end.row;
5766
5767 row_delta =
5768 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5769 }
5770
5771 self.transact(cx, |this, cx| {
5772 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5773 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5774 });
5775 }
5776
5777 fn indent_selection(
5778 buffer: &MultiBuffer,
5779 snapshot: &MultiBufferSnapshot,
5780 selection: &mut Selection<Point>,
5781 edits: &mut Vec<(Range<Point>, String)>,
5782 delta_for_start_row: u32,
5783 cx: &AppContext,
5784 ) -> u32 {
5785 let settings = buffer.settings_at(selection.start, cx);
5786 let tab_size = settings.tab_size.get();
5787 let indent_kind = if settings.hard_tabs {
5788 IndentKind::Tab
5789 } else {
5790 IndentKind::Space
5791 };
5792 let mut start_row = selection.start.row;
5793 let mut end_row = selection.end.row + 1;
5794
5795 // If a selection ends at the beginning of a line, don't indent
5796 // that last line.
5797 if selection.end.column == 0 && selection.end.row > selection.start.row {
5798 end_row -= 1;
5799 }
5800
5801 // Avoid re-indenting a row that has already been indented by a
5802 // previous selection, but still update this selection's column
5803 // to reflect that indentation.
5804 if delta_for_start_row > 0 {
5805 start_row += 1;
5806 selection.start.column += delta_for_start_row;
5807 if selection.end.row == selection.start.row {
5808 selection.end.column += delta_for_start_row;
5809 }
5810 }
5811
5812 let mut delta_for_end_row = 0;
5813 let has_multiple_rows = start_row + 1 != end_row;
5814 for row in start_row..end_row {
5815 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5816 let indent_delta = match (current_indent.kind, indent_kind) {
5817 (IndentKind::Space, IndentKind::Space) => {
5818 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5819 IndentSize::spaces(columns_to_next_tab_stop)
5820 }
5821 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5822 (_, IndentKind::Tab) => IndentSize::tab(),
5823 };
5824
5825 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5826 0
5827 } else {
5828 selection.start.column
5829 };
5830 let row_start = Point::new(row, start);
5831 edits.push((
5832 row_start..row_start,
5833 indent_delta.chars().collect::<String>(),
5834 ));
5835
5836 // Update this selection's endpoints to reflect the indentation.
5837 if row == selection.start.row {
5838 selection.start.column += indent_delta.len;
5839 }
5840 if row == selection.end.row {
5841 selection.end.column += indent_delta.len;
5842 delta_for_end_row = indent_delta.len;
5843 }
5844 }
5845
5846 if selection.start.row == selection.end.row {
5847 delta_for_start_row + delta_for_end_row
5848 } else {
5849 delta_for_end_row
5850 }
5851 }
5852
5853 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5854 if self.read_only(cx) {
5855 return;
5856 }
5857 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5858 let selections = self.selections.all::<Point>(cx);
5859 let mut deletion_ranges = Vec::new();
5860 let mut last_outdent = None;
5861 {
5862 let buffer = self.buffer.read(cx);
5863 let snapshot = buffer.snapshot(cx);
5864 for selection in &selections {
5865 let settings = buffer.settings_at(selection.start, cx);
5866 let tab_size = settings.tab_size.get();
5867 let mut rows = selection.spanned_rows(false, &display_map);
5868
5869 // Avoid re-outdenting a row that has already been outdented by a
5870 // previous selection.
5871 if let Some(last_row) = last_outdent {
5872 if last_row == rows.start {
5873 rows.start = rows.start.next_row();
5874 }
5875 }
5876 let has_multiple_rows = rows.len() > 1;
5877 for row in rows.iter_rows() {
5878 let indent_size = snapshot.indent_size_for_line(row);
5879 if indent_size.len > 0 {
5880 let deletion_len = match indent_size.kind {
5881 IndentKind::Space => {
5882 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5883 if columns_to_prev_tab_stop == 0 {
5884 tab_size
5885 } else {
5886 columns_to_prev_tab_stop
5887 }
5888 }
5889 IndentKind::Tab => 1,
5890 };
5891 let start = if has_multiple_rows
5892 || deletion_len > selection.start.column
5893 || indent_size.len < selection.start.column
5894 {
5895 0
5896 } else {
5897 selection.start.column - deletion_len
5898 };
5899 deletion_ranges.push(
5900 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5901 );
5902 last_outdent = Some(row);
5903 }
5904 }
5905 }
5906 }
5907
5908 self.transact(cx, |this, cx| {
5909 this.buffer.update(cx, |buffer, cx| {
5910 let empty_str: Arc<str> = Arc::default();
5911 buffer.edit(
5912 deletion_ranges
5913 .into_iter()
5914 .map(|range| (range, empty_str.clone())),
5915 None,
5916 cx,
5917 );
5918 });
5919 let selections = this.selections.all::<usize>(cx);
5920 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5921 });
5922 }
5923
5924 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5925 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5926 let selections = self.selections.all::<Point>(cx);
5927
5928 let mut new_cursors = Vec::new();
5929 let mut edit_ranges = Vec::new();
5930 let mut selections = selections.iter().peekable();
5931 while let Some(selection) = selections.next() {
5932 let mut rows = selection.spanned_rows(false, &display_map);
5933 let goal_display_column = selection.head().to_display_point(&display_map).column();
5934
5935 // Accumulate contiguous regions of rows that we want to delete.
5936 while let Some(next_selection) = selections.peek() {
5937 let next_rows = next_selection.spanned_rows(false, &display_map);
5938 if next_rows.start <= rows.end {
5939 rows.end = next_rows.end;
5940 selections.next().unwrap();
5941 } else {
5942 break;
5943 }
5944 }
5945
5946 let buffer = &display_map.buffer_snapshot;
5947 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5948 let edit_end;
5949 let cursor_buffer_row;
5950 if buffer.max_point().row >= rows.end.0 {
5951 // If there's a line after the range, delete the \n from the end of the row range
5952 // and position the cursor on the next line.
5953 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5954 cursor_buffer_row = rows.end;
5955 } else {
5956 // If there isn't a line after the range, delete the \n from the line before the
5957 // start of the row range and position the cursor there.
5958 edit_start = edit_start.saturating_sub(1);
5959 edit_end = buffer.len();
5960 cursor_buffer_row = rows.start.previous_row();
5961 }
5962
5963 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5964 *cursor.column_mut() =
5965 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5966
5967 new_cursors.push((
5968 selection.id,
5969 buffer.anchor_after(cursor.to_point(&display_map)),
5970 ));
5971 edit_ranges.push(edit_start..edit_end);
5972 }
5973
5974 self.transact(cx, |this, cx| {
5975 let buffer = this.buffer.update(cx, |buffer, cx| {
5976 let empty_str: Arc<str> = Arc::default();
5977 buffer.edit(
5978 edit_ranges
5979 .into_iter()
5980 .map(|range| (range, empty_str.clone())),
5981 None,
5982 cx,
5983 );
5984 buffer.snapshot(cx)
5985 });
5986 let new_selections = new_cursors
5987 .into_iter()
5988 .map(|(id, cursor)| {
5989 let cursor = cursor.to_point(&buffer);
5990 Selection {
5991 id,
5992 start: cursor,
5993 end: cursor,
5994 reversed: false,
5995 goal: SelectionGoal::None,
5996 }
5997 })
5998 .collect();
5999
6000 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6001 s.select(new_selections);
6002 });
6003 });
6004 }
6005
6006 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6007 if self.read_only(cx) {
6008 return;
6009 }
6010 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6011 for selection in self.selections.all::<Point>(cx) {
6012 let start = MultiBufferRow(selection.start.row);
6013 let end = if selection.start.row == selection.end.row {
6014 MultiBufferRow(selection.start.row + 1)
6015 } else {
6016 MultiBufferRow(selection.end.row)
6017 };
6018
6019 if let Some(last_row_range) = row_ranges.last_mut() {
6020 if start <= last_row_range.end {
6021 last_row_range.end = end;
6022 continue;
6023 }
6024 }
6025 row_ranges.push(start..end);
6026 }
6027
6028 let snapshot = self.buffer.read(cx).snapshot(cx);
6029 let mut cursor_positions = Vec::new();
6030 for row_range in &row_ranges {
6031 let anchor = snapshot.anchor_before(Point::new(
6032 row_range.end.previous_row().0,
6033 snapshot.line_len(row_range.end.previous_row()),
6034 ));
6035 cursor_positions.push(anchor..anchor);
6036 }
6037
6038 self.transact(cx, |this, cx| {
6039 for row_range in row_ranges.into_iter().rev() {
6040 for row in row_range.iter_rows().rev() {
6041 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6042 let next_line_row = row.next_row();
6043 let indent = snapshot.indent_size_for_line(next_line_row);
6044 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6045
6046 let replace = if snapshot.line_len(next_line_row) > indent.len {
6047 " "
6048 } else {
6049 ""
6050 };
6051
6052 this.buffer.update(cx, |buffer, cx| {
6053 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6054 });
6055 }
6056 }
6057
6058 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6059 s.select_anchor_ranges(cursor_positions)
6060 });
6061 });
6062 }
6063
6064 pub fn sort_lines_case_sensitive(
6065 &mut self,
6066 _: &SortLinesCaseSensitive,
6067 cx: &mut ViewContext<Self>,
6068 ) {
6069 self.manipulate_lines(cx, |lines| lines.sort())
6070 }
6071
6072 pub fn sort_lines_case_insensitive(
6073 &mut self,
6074 _: &SortLinesCaseInsensitive,
6075 cx: &mut ViewContext<Self>,
6076 ) {
6077 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6078 }
6079
6080 pub fn unique_lines_case_insensitive(
6081 &mut self,
6082 _: &UniqueLinesCaseInsensitive,
6083 cx: &mut ViewContext<Self>,
6084 ) {
6085 self.manipulate_lines(cx, |lines| {
6086 let mut seen = HashSet::default();
6087 lines.retain(|line| seen.insert(line.to_lowercase()));
6088 })
6089 }
6090
6091 pub fn unique_lines_case_sensitive(
6092 &mut self,
6093 _: &UniqueLinesCaseSensitive,
6094 cx: &mut ViewContext<Self>,
6095 ) {
6096 self.manipulate_lines(cx, |lines| {
6097 let mut seen = HashSet::default();
6098 lines.retain(|line| seen.insert(*line));
6099 })
6100 }
6101
6102 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6103 let mut revert_changes = HashMap::default();
6104 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6105 for hunk in hunks_for_rows(
6106 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6107 &multi_buffer_snapshot,
6108 ) {
6109 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6110 }
6111 if !revert_changes.is_empty() {
6112 self.transact(cx, |editor, cx| {
6113 editor.revert(revert_changes, cx);
6114 });
6115 }
6116 }
6117
6118 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6119 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6120 if !revert_changes.is_empty() {
6121 self.transact(cx, |editor, cx| {
6122 editor.revert(revert_changes, cx);
6123 });
6124 }
6125 }
6126
6127 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6128 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6129 let project_path = buffer.read(cx).project_path(cx)?;
6130 let project = self.project.as_ref()?.read(cx);
6131 let entry = project.entry_for_path(&project_path, cx)?;
6132 let abs_path = project.absolute_path(&project_path, cx)?;
6133 let parent = if entry.is_symlink {
6134 abs_path.canonicalize().ok()?
6135 } else {
6136 abs_path
6137 }
6138 .parent()?
6139 .to_path_buf();
6140 Some(parent)
6141 }) {
6142 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6143 }
6144 }
6145
6146 fn gather_revert_changes(
6147 &mut self,
6148 selections: &[Selection<Anchor>],
6149 cx: &mut ViewContext<'_, Editor>,
6150 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6151 let mut revert_changes = HashMap::default();
6152 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6153 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6154 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6155 }
6156 revert_changes
6157 }
6158
6159 pub fn prepare_revert_change(
6160 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6161 multi_buffer: &Model<MultiBuffer>,
6162 hunk: &DiffHunk<MultiBufferRow>,
6163 cx: &AppContext,
6164 ) -> Option<()> {
6165 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6166 let buffer = buffer.read(cx);
6167 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6168 let buffer_snapshot = buffer.snapshot();
6169 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6170 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6171 probe
6172 .0
6173 .start
6174 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6175 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6176 }) {
6177 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6178 Some(())
6179 } else {
6180 None
6181 }
6182 }
6183
6184 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6185 self.manipulate_lines(cx, |lines| lines.reverse())
6186 }
6187
6188 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6189 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6190 }
6191
6192 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6193 where
6194 Fn: FnMut(&mut Vec<&str>),
6195 {
6196 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6197 let buffer = self.buffer.read(cx).snapshot(cx);
6198
6199 let mut edits = Vec::new();
6200
6201 let selections = self.selections.all::<Point>(cx);
6202 let mut selections = selections.iter().peekable();
6203 let mut contiguous_row_selections = Vec::new();
6204 let mut new_selections = Vec::new();
6205 let mut added_lines = 0;
6206 let mut removed_lines = 0;
6207
6208 while let Some(selection) = selections.next() {
6209 let (start_row, end_row) = consume_contiguous_rows(
6210 &mut contiguous_row_selections,
6211 selection,
6212 &display_map,
6213 &mut selections,
6214 );
6215
6216 let start_point = Point::new(start_row.0, 0);
6217 let end_point = Point::new(
6218 end_row.previous_row().0,
6219 buffer.line_len(end_row.previous_row()),
6220 );
6221 let text = buffer
6222 .text_for_range(start_point..end_point)
6223 .collect::<String>();
6224
6225 let mut lines = text.split('\n').collect_vec();
6226
6227 let lines_before = lines.len();
6228 callback(&mut lines);
6229 let lines_after = lines.len();
6230
6231 edits.push((start_point..end_point, lines.join("\n")));
6232
6233 // Selections must change based on added and removed line count
6234 let start_row =
6235 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6236 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6237 new_selections.push(Selection {
6238 id: selection.id,
6239 start: start_row,
6240 end: end_row,
6241 goal: SelectionGoal::None,
6242 reversed: selection.reversed,
6243 });
6244
6245 if lines_after > lines_before {
6246 added_lines += lines_after - lines_before;
6247 } else if lines_before > lines_after {
6248 removed_lines += lines_before - lines_after;
6249 }
6250 }
6251
6252 self.transact(cx, |this, cx| {
6253 let buffer = this.buffer.update(cx, |buffer, cx| {
6254 buffer.edit(edits, None, cx);
6255 buffer.snapshot(cx)
6256 });
6257
6258 // Recalculate offsets on newly edited buffer
6259 let new_selections = new_selections
6260 .iter()
6261 .map(|s| {
6262 let start_point = Point::new(s.start.0, 0);
6263 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6264 Selection {
6265 id: s.id,
6266 start: buffer.point_to_offset(start_point),
6267 end: buffer.point_to_offset(end_point),
6268 goal: s.goal,
6269 reversed: s.reversed,
6270 }
6271 })
6272 .collect();
6273
6274 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6275 s.select(new_selections);
6276 });
6277
6278 this.request_autoscroll(Autoscroll::fit(), cx);
6279 });
6280 }
6281
6282 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6283 self.manipulate_text(cx, |text| text.to_uppercase())
6284 }
6285
6286 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6287 self.manipulate_text(cx, |text| text.to_lowercase())
6288 }
6289
6290 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6291 self.manipulate_text(cx, |text| {
6292 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6293 // https://github.com/rutrum/convert-case/issues/16
6294 text.split('\n')
6295 .map(|line| line.to_case(Case::Title))
6296 .join("\n")
6297 })
6298 }
6299
6300 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6301 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6302 }
6303
6304 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6305 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6306 }
6307
6308 pub fn convert_to_upper_camel_case(
6309 &mut self,
6310 _: &ConvertToUpperCamelCase,
6311 cx: &mut ViewContext<Self>,
6312 ) {
6313 self.manipulate_text(cx, |text| {
6314 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6315 // https://github.com/rutrum/convert-case/issues/16
6316 text.split('\n')
6317 .map(|line| line.to_case(Case::UpperCamel))
6318 .join("\n")
6319 })
6320 }
6321
6322 pub fn convert_to_lower_camel_case(
6323 &mut self,
6324 _: &ConvertToLowerCamelCase,
6325 cx: &mut ViewContext<Self>,
6326 ) {
6327 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6328 }
6329
6330 pub fn convert_to_opposite_case(
6331 &mut self,
6332 _: &ConvertToOppositeCase,
6333 cx: &mut ViewContext<Self>,
6334 ) {
6335 self.manipulate_text(cx, |text| {
6336 text.chars()
6337 .fold(String::with_capacity(text.len()), |mut t, c| {
6338 if c.is_uppercase() {
6339 t.extend(c.to_lowercase());
6340 } else {
6341 t.extend(c.to_uppercase());
6342 }
6343 t
6344 })
6345 })
6346 }
6347
6348 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6349 where
6350 Fn: FnMut(&str) -> String,
6351 {
6352 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6353 let buffer = self.buffer.read(cx).snapshot(cx);
6354
6355 let mut new_selections = Vec::new();
6356 let mut edits = Vec::new();
6357 let mut selection_adjustment = 0i32;
6358
6359 for selection in self.selections.all::<usize>(cx) {
6360 let selection_is_empty = selection.is_empty();
6361
6362 let (start, end) = if selection_is_empty {
6363 let word_range = movement::surrounding_word(
6364 &display_map,
6365 selection.start.to_display_point(&display_map),
6366 );
6367 let start = word_range.start.to_offset(&display_map, Bias::Left);
6368 let end = word_range.end.to_offset(&display_map, Bias::Left);
6369 (start, end)
6370 } else {
6371 (selection.start, selection.end)
6372 };
6373
6374 let text = buffer.text_for_range(start..end).collect::<String>();
6375 let old_length = text.len() as i32;
6376 let text = callback(&text);
6377
6378 new_selections.push(Selection {
6379 start: (start as i32 - selection_adjustment) as usize,
6380 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6381 goal: SelectionGoal::None,
6382 ..selection
6383 });
6384
6385 selection_adjustment += old_length - text.len() as i32;
6386
6387 edits.push((start..end, text));
6388 }
6389
6390 self.transact(cx, |this, cx| {
6391 this.buffer.update(cx, |buffer, cx| {
6392 buffer.edit(edits, None, cx);
6393 });
6394
6395 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6396 s.select(new_selections);
6397 });
6398
6399 this.request_autoscroll(Autoscroll::fit(), cx);
6400 });
6401 }
6402
6403 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6404 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6405 let buffer = &display_map.buffer_snapshot;
6406 let selections = self.selections.all::<Point>(cx);
6407
6408 let mut edits = Vec::new();
6409 let mut selections_iter = selections.iter().peekable();
6410 while let Some(selection) = selections_iter.next() {
6411 // Avoid duplicating the same lines twice.
6412 let mut rows = selection.spanned_rows(false, &display_map);
6413
6414 while let Some(next_selection) = selections_iter.peek() {
6415 let next_rows = next_selection.spanned_rows(false, &display_map);
6416 if next_rows.start < rows.end {
6417 rows.end = next_rows.end;
6418 selections_iter.next().unwrap();
6419 } else {
6420 break;
6421 }
6422 }
6423
6424 // Copy the text from the selected row region and splice it either at the start
6425 // or end of the region.
6426 let start = Point::new(rows.start.0, 0);
6427 let end = Point::new(
6428 rows.end.previous_row().0,
6429 buffer.line_len(rows.end.previous_row()),
6430 );
6431 let text = buffer
6432 .text_for_range(start..end)
6433 .chain(Some("\n"))
6434 .collect::<String>();
6435 let insert_location = if upwards {
6436 Point::new(rows.end.0, 0)
6437 } else {
6438 start
6439 };
6440 edits.push((insert_location..insert_location, text));
6441 }
6442
6443 self.transact(cx, |this, cx| {
6444 this.buffer.update(cx, |buffer, cx| {
6445 buffer.edit(edits, None, cx);
6446 });
6447
6448 this.request_autoscroll(Autoscroll::fit(), cx);
6449 });
6450 }
6451
6452 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6453 self.duplicate_line(true, cx);
6454 }
6455
6456 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6457 self.duplicate_line(false, cx);
6458 }
6459
6460 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6461 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6462 let buffer = self.buffer.read(cx).snapshot(cx);
6463
6464 let mut edits = Vec::new();
6465 let mut unfold_ranges = Vec::new();
6466 let mut refold_ranges = Vec::new();
6467
6468 let selections = self.selections.all::<Point>(cx);
6469 let mut selections = selections.iter().peekable();
6470 let mut contiguous_row_selections = Vec::new();
6471 let mut new_selections = Vec::new();
6472
6473 while let Some(selection) = selections.next() {
6474 // Find all the selections that span a contiguous row range
6475 let (start_row, end_row) = consume_contiguous_rows(
6476 &mut contiguous_row_selections,
6477 selection,
6478 &display_map,
6479 &mut selections,
6480 );
6481
6482 // Move the text spanned by the row range to be before the line preceding the row range
6483 if start_row.0 > 0 {
6484 let range_to_move = Point::new(
6485 start_row.previous_row().0,
6486 buffer.line_len(start_row.previous_row()),
6487 )
6488 ..Point::new(
6489 end_row.previous_row().0,
6490 buffer.line_len(end_row.previous_row()),
6491 );
6492 let insertion_point = display_map
6493 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6494 .0;
6495
6496 // Don't move lines across excerpts
6497 if buffer
6498 .excerpt_boundaries_in_range((
6499 Bound::Excluded(insertion_point),
6500 Bound::Included(range_to_move.end),
6501 ))
6502 .next()
6503 .is_none()
6504 {
6505 let text = buffer
6506 .text_for_range(range_to_move.clone())
6507 .flat_map(|s| s.chars())
6508 .skip(1)
6509 .chain(['\n'])
6510 .collect::<String>();
6511
6512 edits.push((
6513 buffer.anchor_after(range_to_move.start)
6514 ..buffer.anchor_before(range_to_move.end),
6515 String::new(),
6516 ));
6517 let insertion_anchor = buffer.anchor_after(insertion_point);
6518 edits.push((insertion_anchor..insertion_anchor, text));
6519
6520 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6521
6522 // Move selections up
6523 new_selections.extend(contiguous_row_selections.drain(..).map(
6524 |mut selection| {
6525 selection.start.row -= row_delta;
6526 selection.end.row -= row_delta;
6527 selection
6528 },
6529 ));
6530
6531 // Move folds up
6532 unfold_ranges.push(range_to_move.clone());
6533 for fold in display_map.folds_in_range(
6534 buffer.anchor_before(range_to_move.start)
6535 ..buffer.anchor_after(range_to_move.end),
6536 ) {
6537 let mut start = fold.range.start.to_point(&buffer);
6538 let mut end = fold.range.end.to_point(&buffer);
6539 start.row -= row_delta;
6540 end.row -= row_delta;
6541 refold_ranges.push((start..end, fold.placeholder.clone()));
6542 }
6543 }
6544 }
6545
6546 // If we didn't move line(s), preserve the existing selections
6547 new_selections.append(&mut contiguous_row_selections);
6548 }
6549
6550 self.transact(cx, |this, cx| {
6551 this.unfold_ranges(unfold_ranges, true, true, cx);
6552 this.buffer.update(cx, |buffer, cx| {
6553 for (range, text) in edits {
6554 buffer.edit([(range, text)], None, cx);
6555 }
6556 });
6557 this.fold_ranges(refold_ranges, true, cx);
6558 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6559 s.select(new_selections);
6560 })
6561 });
6562 }
6563
6564 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6565 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6566 let buffer = self.buffer.read(cx).snapshot(cx);
6567
6568 let mut edits = Vec::new();
6569 let mut unfold_ranges = Vec::new();
6570 let mut refold_ranges = Vec::new();
6571
6572 let selections = self.selections.all::<Point>(cx);
6573 let mut selections = selections.iter().peekable();
6574 let mut contiguous_row_selections = Vec::new();
6575 let mut new_selections = Vec::new();
6576
6577 while let Some(selection) = selections.next() {
6578 // Find all the selections that span a contiguous row range
6579 let (start_row, end_row) = consume_contiguous_rows(
6580 &mut contiguous_row_selections,
6581 selection,
6582 &display_map,
6583 &mut selections,
6584 );
6585
6586 // Move the text spanned by the row range to be after the last line of the row range
6587 if end_row.0 <= buffer.max_point().row {
6588 let range_to_move =
6589 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6590 let insertion_point = display_map
6591 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6592 .0;
6593
6594 // Don't move lines across excerpt boundaries
6595 if buffer
6596 .excerpt_boundaries_in_range((
6597 Bound::Excluded(range_to_move.start),
6598 Bound::Included(insertion_point),
6599 ))
6600 .next()
6601 .is_none()
6602 {
6603 let mut text = String::from("\n");
6604 text.extend(buffer.text_for_range(range_to_move.clone()));
6605 text.pop(); // Drop trailing newline
6606 edits.push((
6607 buffer.anchor_after(range_to_move.start)
6608 ..buffer.anchor_before(range_to_move.end),
6609 String::new(),
6610 ));
6611 let insertion_anchor = buffer.anchor_after(insertion_point);
6612 edits.push((insertion_anchor..insertion_anchor, text));
6613
6614 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6615
6616 // Move selections down
6617 new_selections.extend(contiguous_row_selections.drain(..).map(
6618 |mut selection| {
6619 selection.start.row += row_delta;
6620 selection.end.row += row_delta;
6621 selection
6622 },
6623 ));
6624
6625 // Move folds down
6626 unfold_ranges.push(range_to_move.clone());
6627 for fold in display_map.folds_in_range(
6628 buffer.anchor_before(range_to_move.start)
6629 ..buffer.anchor_after(range_to_move.end),
6630 ) {
6631 let mut start = fold.range.start.to_point(&buffer);
6632 let mut end = fold.range.end.to_point(&buffer);
6633 start.row += row_delta;
6634 end.row += row_delta;
6635 refold_ranges.push((start..end, fold.placeholder.clone()));
6636 }
6637 }
6638 }
6639
6640 // If we didn't move line(s), preserve the existing selections
6641 new_selections.append(&mut contiguous_row_selections);
6642 }
6643
6644 self.transact(cx, |this, cx| {
6645 this.unfold_ranges(unfold_ranges, true, true, cx);
6646 this.buffer.update(cx, |buffer, cx| {
6647 for (range, text) in edits {
6648 buffer.edit([(range, text)], None, cx);
6649 }
6650 });
6651 this.fold_ranges(refold_ranges, true, cx);
6652 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6653 });
6654 }
6655
6656 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6657 let text_layout_details = &self.text_layout_details(cx);
6658 self.transact(cx, |this, cx| {
6659 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6660 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6661 let line_mode = s.line_mode;
6662 s.move_with(|display_map, selection| {
6663 if !selection.is_empty() || line_mode {
6664 return;
6665 }
6666
6667 let mut head = selection.head();
6668 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6669 if head.column() == display_map.line_len(head.row()) {
6670 transpose_offset = display_map
6671 .buffer_snapshot
6672 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6673 }
6674
6675 if transpose_offset == 0 {
6676 return;
6677 }
6678
6679 *head.column_mut() += 1;
6680 head = display_map.clip_point(head, Bias::Right);
6681 let goal = SelectionGoal::HorizontalPosition(
6682 display_map
6683 .x_for_display_point(head, text_layout_details)
6684 .into(),
6685 );
6686 selection.collapse_to(head, goal);
6687
6688 let transpose_start = display_map
6689 .buffer_snapshot
6690 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6691 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6692 let transpose_end = display_map
6693 .buffer_snapshot
6694 .clip_offset(transpose_offset + 1, Bias::Right);
6695 if let Some(ch) =
6696 display_map.buffer_snapshot.chars_at(transpose_start).next()
6697 {
6698 edits.push((transpose_start..transpose_offset, String::new()));
6699 edits.push((transpose_end..transpose_end, ch.to_string()));
6700 }
6701 }
6702 });
6703 edits
6704 });
6705 this.buffer
6706 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6707 let selections = this.selections.all::<usize>(cx);
6708 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6709 s.select(selections);
6710 });
6711 });
6712 }
6713
6714 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6715 let buffer = self.buffer.read(cx).snapshot(cx);
6716 let selections = self.selections.all::<Point>(cx);
6717 let mut selections = selections.iter().peekable();
6718
6719 let mut edits = Vec::new();
6720 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6721
6722 while let Some(selection) = selections.next() {
6723 let mut start_row = selection.start.row;
6724 let mut end_row = selection.end.row;
6725
6726 // Skip selections that overlap with a range that has already been rewrapped.
6727 let selection_range = start_row..end_row;
6728 if rewrapped_row_ranges
6729 .iter()
6730 .any(|range| range.overlaps(&selection_range))
6731 {
6732 continue;
6733 }
6734
6735 let mut should_rewrap = false;
6736
6737 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6738 match language_scope.language_name().0.as_ref() {
6739 "Markdown" | "Plain Text" => {
6740 should_rewrap = true;
6741 }
6742 _ => {}
6743 }
6744 }
6745
6746 let row = selection.head().row;
6747 let indent_size = buffer.indent_size_for_line(MultiBufferRow(row));
6748 let indent_end = Point::new(row, indent_size.len);
6749
6750 let mut line_prefix = indent_size.chars().collect::<String>();
6751
6752 if let Some(comment_prefix) =
6753 buffer
6754 .language_scope_at(selection.head())
6755 .and_then(|language| {
6756 language
6757 .line_comment_prefixes()
6758 .iter()
6759 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6760 .cloned()
6761 })
6762 {
6763 line_prefix.push_str(&comment_prefix);
6764 should_rewrap = true;
6765 }
6766
6767 if selection.is_empty() {
6768 'expand_upwards: while start_row > 0 {
6769 let prev_row = start_row - 1;
6770 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6771 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6772 {
6773 start_row = prev_row;
6774 } else {
6775 break 'expand_upwards;
6776 }
6777 }
6778
6779 'expand_downwards: while end_row < buffer.max_point().row {
6780 let next_row = end_row + 1;
6781 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6782 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6783 {
6784 end_row = next_row;
6785 } else {
6786 break 'expand_downwards;
6787 }
6788 }
6789 }
6790
6791 if !should_rewrap {
6792 continue;
6793 }
6794
6795 let start = Point::new(start_row, 0);
6796 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6797 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6798 let unwrapped_text = selection_text
6799 .lines()
6800 .map(|line| line.strip_prefix(&line_prefix).unwrap())
6801 .join(" ");
6802 let wrap_column = buffer
6803 .settings_at(Point::new(start_row, 0), cx)
6804 .preferred_line_length as usize;
6805 let mut wrapped_text = String::new();
6806 let mut current_line = line_prefix.clone();
6807 for word in unwrapped_text.split_whitespace() {
6808 if current_line.len() + word.len() >= wrap_column {
6809 wrapped_text.push_str(¤t_line);
6810 wrapped_text.push('\n');
6811 current_line.truncate(line_prefix.len());
6812 }
6813
6814 if current_line.len() > line_prefix.len() {
6815 current_line.push(' ');
6816 }
6817
6818 current_line.push_str(word);
6819 }
6820
6821 if !current_line.is_empty() {
6822 wrapped_text.push_str(¤t_line);
6823 }
6824
6825 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
6826 let mut offset = start.to_offset(&buffer);
6827 let mut moved_since_edit = true;
6828
6829 for change in diff.iter_all_changes() {
6830 let value = change.value();
6831 match change.tag() {
6832 ChangeTag::Equal => {
6833 offset += value.len();
6834 moved_since_edit = true;
6835 }
6836 ChangeTag::Delete => {
6837 let start = buffer.anchor_after(offset);
6838 let end = buffer.anchor_before(offset + value.len());
6839
6840 if moved_since_edit {
6841 edits.push((start..end, String::new()));
6842 } else {
6843 edits.last_mut().unwrap().0.end = end;
6844 }
6845
6846 offset += value.len();
6847 moved_since_edit = false;
6848 }
6849 ChangeTag::Insert => {
6850 if moved_since_edit {
6851 let anchor = buffer.anchor_after(offset);
6852 edits.push((anchor..anchor, value.to_string()));
6853 } else {
6854 edits.last_mut().unwrap().1.push_str(value);
6855 }
6856
6857 moved_since_edit = false;
6858 }
6859 }
6860 }
6861
6862 rewrapped_row_ranges.push(start_row..=end_row);
6863 }
6864
6865 self.buffer
6866 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6867 }
6868
6869 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6870 let mut text = String::new();
6871 let buffer = self.buffer.read(cx).snapshot(cx);
6872 let mut selections = self.selections.all::<Point>(cx);
6873 let mut clipboard_selections = Vec::with_capacity(selections.len());
6874 {
6875 let max_point = buffer.max_point();
6876 let mut is_first = true;
6877 for selection in &mut selections {
6878 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6879 if is_entire_line {
6880 selection.start = Point::new(selection.start.row, 0);
6881 if !selection.is_empty() && selection.end.column == 0 {
6882 selection.end = cmp::min(max_point, selection.end);
6883 } else {
6884 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6885 }
6886 selection.goal = SelectionGoal::None;
6887 }
6888 if is_first {
6889 is_first = false;
6890 } else {
6891 text += "\n";
6892 }
6893 let mut len = 0;
6894 for chunk in buffer.text_for_range(selection.start..selection.end) {
6895 text.push_str(chunk);
6896 len += chunk.len();
6897 }
6898 clipboard_selections.push(ClipboardSelection {
6899 len,
6900 is_entire_line,
6901 first_line_indent: buffer
6902 .indent_size_for_line(MultiBufferRow(selection.start.row))
6903 .len,
6904 });
6905 }
6906 }
6907
6908 self.transact(cx, |this, cx| {
6909 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6910 s.select(selections);
6911 });
6912 this.insert("", cx);
6913 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6914 text,
6915 clipboard_selections,
6916 ));
6917 });
6918 }
6919
6920 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6921 let selections = self.selections.all::<Point>(cx);
6922 let buffer = self.buffer.read(cx).read(cx);
6923 let mut text = String::new();
6924
6925 let mut clipboard_selections = Vec::with_capacity(selections.len());
6926 {
6927 let max_point = buffer.max_point();
6928 let mut is_first = true;
6929 for selection in selections.iter() {
6930 let mut start = selection.start;
6931 let mut end = selection.end;
6932 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6933 if is_entire_line {
6934 start = Point::new(start.row, 0);
6935 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6936 }
6937 if is_first {
6938 is_first = false;
6939 } else {
6940 text += "\n";
6941 }
6942 let mut len = 0;
6943 for chunk in buffer.text_for_range(start..end) {
6944 text.push_str(chunk);
6945 len += chunk.len();
6946 }
6947 clipboard_selections.push(ClipboardSelection {
6948 len,
6949 is_entire_line,
6950 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6951 });
6952 }
6953 }
6954
6955 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6956 text,
6957 clipboard_selections,
6958 ));
6959 }
6960
6961 pub fn do_paste(
6962 &mut self,
6963 text: &String,
6964 clipboard_selections: Option<Vec<ClipboardSelection>>,
6965 handle_entire_lines: bool,
6966 cx: &mut ViewContext<Self>,
6967 ) {
6968 if self.read_only(cx) {
6969 return;
6970 }
6971
6972 let clipboard_text = Cow::Borrowed(text);
6973
6974 self.transact(cx, |this, cx| {
6975 if let Some(mut clipboard_selections) = clipboard_selections {
6976 let old_selections = this.selections.all::<usize>(cx);
6977 let all_selections_were_entire_line =
6978 clipboard_selections.iter().all(|s| s.is_entire_line);
6979 let first_selection_indent_column =
6980 clipboard_selections.first().map(|s| s.first_line_indent);
6981 if clipboard_selections.len() != old_selections.len() {
6982 clipboard_selections.drain(..);
6983 }
6984
6985 this.buffer.update(cx, |buffer, cx| {
6986 let snapshot = buffer.read(cx);
6987 let mut start_offset = 0;
6988 let mut edits = Vec::new();
6989 let mut original_indent_columns = Vec::new();
6990 for (ix, selection) in old_selections.iter().enumerate() {
6991 let to_insert;
6992 let entire_line;
6993 let original_indent_column;
6994 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
6995 let end_offset = start_offset + clipboard_selection.len;
6996 to_insert = &clipboard_text[start_offset..end_offset];
6997 entire_line = clipboard_selection.is_entire_line;
6998 start_offset = end_offset + 1;
6999 original_indent_column = Some(clipboard_selection.first_line_indent);
7000 } else {
7001 to_insert = clipboard_text.as_str();
7002 entire_line = all_selections_were_entire_line;
7003 original_indent_column = first_selection_indent_column
7004 }
7005
7006 // If the corresponding selection was empty when this slice of the
7007 // clipboard text was written, then the entire line containing the
7008 // selection was copied. If this selection is also currently empty,
7009 // then paste the line before the current line of the buffer.
7010 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7011 let column = selection.start.to_point(&snapshot).column as usize;
7012 let line_start = selection.start - column;
7013 line_start..line_start
7014 } else {
7015 selection.range()
7016 };
7017
7018 edits.push((range, to_insert));
7019 original_indent_columns.extend(original_indent_column);
7020 }
7021 drop(snapshot);
7022
7023 buffer.edit(
7024 edits,
7025 Some(AutoindentMode::Block {
7026 original_indent_columns,
7027 }),
7028 cx,
7029 );
7030 });
7031
7032 let selections = this.selections.all::<usize>(cx);
7033 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7034 } else {
7035 this.insert(&clipboard_text, cx);
7036 }
7037 });
7038 }
7039
7040 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7041 if let Some(item) = cx.read_from_clipboard() {
7042 let entries = item.entries();
7043
7044 match entries.first() {
7045 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7046 // of all the pasted entries.
7047 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7048 .do_paste(
7049 clipboard_string.text(),
7050 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7051 true,
7052 cx,
7053 ),
7054 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7055 }
7056 }
7057 }
7058
7059 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7060 if self.read_only(cx) {
7061 return;
7062 }
7063
7064 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7065 if let Some((selections, _)) =
7066 self.selection_history.transaction(transaction_id).cloned()
7067 {
7068 self.change_selections(None, cx, |s| {
7069 s.select_anchors(selections.to_vec());
7070 });
7071 }
7072 self.request_autoscroll(Autoscroll::fit(), cx);
7073 self.unmark_text(cx);
7074 self.refresh_inline_completion(true, false, cx);
7075 cx.emit(EditorEvent::Edited { transaction_id });
7076 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7077 }
7078 }
7079
7080 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7081 if self.read_only(cx) {
7082 return;
7083 }
7084
7085 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7086 if let Some((_, Some(selections))) =
7087 self.selection_history.transaction(transaction_id).cloned()
7088 {
7089 self.change_selections(None, cx, |s| {
7090 s.select_anchors(selections.to_vec());
7091 });
7092 }
7093 self.request_autoscroll(Autoscroll::fit(), cx);
7094 self.unmark_text(cx);
7095 self.refresh_inline_completion(true, false, cx);
7096 cx.emit(EditorEvent::Edited { transaction_id });
7097 }
7098 }
7099
7100 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7101 self.buffer
7102 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7103 }
7104
7105 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7106 self.buffer
7107 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7108 }
7109
7110 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7111 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7112 let line_mode = s.line_mode;
7113 s.move_with(|map, selection| {
7114 let cursor = if selection.is_empty() && !line_mode {
7115 movement::left(map, selection.start)
7116 } else {
7117 selection.start
7118 };
7119 selection.collapse_to(cursor, SelectionGoal::None);
7120 });
7121 })
7122 }
7123
7124 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7125 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7126 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7127 })
7128 }
7129
7130 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7131 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7132 let line_mode = s.line_mode;
7133 s.move_with(|map, selection| {
7134 let cursor = if selection.is_empty() && !line_mode {
7135 movement::right(map, selection.end)
7136 } else {
7137 selection.end
7138 };
7139 selection.collapse_to(cursor, SelectionGoal::None)
7140 });
7141 })
7142 }
7143
7144 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7145 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7146 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7147 })
7148 }
7149
7150 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7151 if self.take_rename(true, cx).is_some() {
7152 return;
7153 }
7154
7155 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7156 cx.propagate();
7157 return;
7158 }
7159
7160 let text_layout_details = &self.text_layout_details(cx);
7161 let selection_count = self.selections.count();
7162 let first_selection = self.selections.first_anchor();
7163
7164 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7165 let line_mode = s.line_mode;
7166 s.move_with(|map, selection| {
7167 if !selection.is_empty() && !line_mode {
7168 selection.goal = SelectionGoal::None;
7169 }
7170 let (cursor, goal) = movement::up(
7171 map,
7172 selection.start,
7173 selection.goal,
7174 false,
7175 text_layout_details,
7176 );
7177 selection.collapse_to(cursor, goal);
7178 });
7179 });
7180
7181 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7182 {
7183 cx.propagate();
7184 }
7185 }
7186
7187 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7188 if self.take_rename(true, cx).is_some() {
7189 return;
7190 }
7191
7192 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7193 cx.propagate();
7194 return;
7195 }
7196
7197 let text_layout_details = &self.text_layout_details(cx);
7198
7199 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7200 let line_mode = s.line_mode;
7201 s.move_with(|map, selection| {
7202 if !selection.is_empty() && !line_mode {
7203 selection.goal = SelectionGoal::None;
7204 }
7205 let (cursor, goal) = movement::up_by_rows(
7206 map,
7207 selection.start,
7208 action.lines,
7209 selection.goal,
7210 false,
7211 text_layout_details,
7212 );
7213 selection.collapse_to(cursor, goal);
7214 });
7215 })
7216 }
7217
7218 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7219 if self.take_rename(true, cx).is_some() {
7220 return;
7221 }
7222
7223 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7224 cx.propagate();
7225 return;
7226 }
7227
7228 let text_layout_details = &self.text_layout_details(cx);
7229
7230 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7231 let line_mode = s.line_mode;
7232 s.move_with(|map, selection| {
7233 if !selection.is_empty() && !line_mode {
7234 selection.goal = SelectionGoal::None;
7235 }
7236 let (cursor, goal) = movement::down_by_rows(
7237 map,
7238 selection.start,
7239 action.lines,
7240 selection.goal,
7241 false,
7242 text_layout_details,
7243 );
7244 selection.collapse_to(cursor, goal);
7245 });
7246 })
7247 }
7248
7249 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7250 let text_layout_details = &self.text_layout_details(cx);
7251 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7252 s.move_heads_with(|map, head, goal| {
7253 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7254 })
7255 })
7256 }
7257
7258 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7259 let text_layout_details = &self.text_layout_details(cx);
7260 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7261 s.move_heads_with(|map, head, goal| {
7262 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7263 })
7264 })
7265 }
7266
7267 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7268 let Some(row_count) = self.visible_row_count() else {
7269 return;
7270 };
7271
7272 let text_layout_details = &self.text_layout_details(cx);
7273
7274 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7275 s.move_heads_with(|map, head, goal| {
7276 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7277 })
7278 })
7279 }
7280
7281 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7282 if self.take_rename(true, cx).is_some() {
7283 return;
7284 }
7285
7286 if self
7287 .context_menu
7288 .write()
7289 .as_mut()
7290 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7291 .unwrap_or(false)
7292 {
7293 return;
7294 }
7295
7296 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7297 cx.propagate();
7298 return;
7299 }
7300
7301 let Some(row_count) = self.visible_row_count() else {
7302 return;
7303 };
7304
7305 let autoscroll = if action.center_cursor {
7306 Autoscroll::center()
7307 } else {
7308 Autoscroll::fit()
7309 };
7310
7311 let text_layout_details = &self.text_layout_details(cx);
7312
7313 self.change_selections(Some(autoscroll), cx, |s| {
7314 let line_mode = s.line_mode;
7315 s.move_with(|map, selection| {
7316 if !selection.is_empty() && !line_mode {
7317 selection.goal = SelectionGoal::None;
7318 }
7319 let (cursor, goal) = movement::up_by_rows(
7320 map,
7321 selection.end,
7322 row_count,
7323 selection.goal,
7324 false,
7325 text_layout_details,
7326 );
7327 selection.collapse_to(cursor, goal);
7328 });
7329 });
7330 }
7331
7332 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7333 let text_layout_details = &self.text_layout_details(cx);
7334 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7335 s.move_heads_with(|map, head, goal| {
7336 movement::up(map, head, goal, false, text_layout_details)
7337 })
7338 })
7339 }
7340
7341 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7342 self.take_rename(true, cx);
7343
7344 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7345 cx.propagate();
7346 return;
7347 }
7348
7349 let text_layout_details = &self.text_layout_details(cx);
7350 let selection_count = self.selections.count();
7351 let first_selection = self.selections.first_anchor();
7352
7353 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7354 let line_mode = s.line_mode;
7355 s.move_with(|map, selection| {
7356 if !selection.is_empty() && !line_mode {
7357 selection.goal = SelectionGoal::None;
7358 }
7359 let (cursor, goal) = movement::down(
7360 map,
7361 selection.end,
7362 selection.goal,
7363 false,
7364 text_layout_details,
7365 );
7366 selection.collapse_to(cursor, goal);
7367 });
7368 });
7369
7370 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7371 {
7372 cx.propagate();
7373 }
7374 }
7375
7376 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7377 let Some(row_count) = self.visible_row_count() else {
7378 return;
7379 };
7380
7381 let text_layout_details = &self.text_layout_details(cx);
7382
7383 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7384 s.move_heads_with(|map, head, goal| {
7385 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7386 })
7387 })
7388 }
7389
7390 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7391 if self.take_rename(true, cx).is_some() {
7392 return;
7393 }
7394
7395 if self
7396 .context_menu
7397 .write()
7398 .as_mut()
7399 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7400 .unwrap_or(false)
7401 {
7402 return;
7403 }
7404
7405 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7406 cx.propagate();
7407 return;
7408 }
7409
7410 let Some(row_count) = self.visible_row_count() else {
7411 return;
7412 };
7413
7414 let autoscroll = if action.center_cursor {
7415 Autoscroll::center()
7416 } else {
7417 Autoscroll::fit()
7418 };
7419
7420 let text_layout_details = &self.text_layout_details(cx);
7421 self.change_selections(Some(autoscroll), cx, |s| {
7422 let line_mode = s.line_mode;
7423 s.move_with(|map, selection| {
7424 if !selection.is_empty() && !line_mode {
7425 selection.goal = SelectionGoal::None;
7426 }
7427 let (cursor, goal) = movement::down_by_rows(
7428 map,
7429 selection.end,
7430 row_count,
7431 selection.goal,
7432 false,
7433 text_layout_details,
7434 );
7435 selection.collapse_to(cursor, goal);
7436 });
7437 });
7438 }
7439
7440 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7441 let text_layout_details = &self.text_layout_details(cx);
7442 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7443 s.move_heads_with(|map, head, goal| {
7444 movement::down(map, head, goal, false, text_layout_details)
7445 })
7446 });
7447 }
7448
7449 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7450 if let Some(context_menu) = self.context_menu.write().as_mut() {
7451 context_menu.select_first(self.project.as_ref(), cx);
7452 }
7453 }
7454
7455 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7456 if let Some(context_menu) = self.context_menu.write().as_mut() {
7457 context_menu.select_prev(self.project.as_ref(), cx);
7458 }
7459 }
7460
7461 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7462 if let Some(context_menu) = self.context_menu.write().as_mut() {
7463 context_menu.select_next(self.project.as_ref(), cx);
7464 }
7465 }
7466
7467 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7468 if let Some(context_menu) = self.context_menu.write().as_mut() {
7469 context_menu.select_last(self.project.as_ref(), cx);
7470 }
7471 }
7472
7473 pub fn move_to_previous_word_start(
7474 &mut self,
7475 _: &MoveToPreviousWordStart,
7476 cx: &mut ViewContext<Self>,
7477 ) {
7478 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7479 s.move_cursors_with(|map, head, _| {
7480 (
7481 movement::previous_word_start(map, head),
7482 SelectionGoal::None,
7483 )
7484 });
7485 })
7486 }
7487
7488 pub fn move_to_previous_subword_start(
7489 &mut self,
7490 _: &MoveToPreviousSubwordStart,
7491 cx: &mut ViewContext<Self>,
7492 ) {
7493 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7494 s.move_cursors_with(|map, head, _| {
7495 (
7496 movement::previous_subword_start(map, head),
7497 SelectionGoal::None,
7498 )
7499 });
7500 })
7501 }
7502
7503 pub fn select_to_previous_word_start(
7504 &mut self,
7505 _: &SelectToPreviousWordStart,
7506 cx: &mut ViewContext<Self>,
7507 ) {
7508 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7509 s.move_heads_with(|map, head, _| {
7510 (
7511 movement::previous_word_start(map, head),
7512 SelectionGoal::None,
7513 )
7514 });
7515 })
7516 }
7517
7518 pub fn select_to_previous_subword_start(
7519 &mut self,
7520 _: &SelectToPreviousSubwordStart,
7521 cx: &mut ViewContext<Self>,
7522 ) {
7523 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7524 s.move_heads_with(|map, head, _| {
7525 (
7526 movement::previous_subword_start(map, head),
7527 SelectionGoal::None,
7528 )
7529 });
7530 })
7531 }
7532
7533 pub fn delete_to_previous_word_start(
7534 &mut self,
7535 action: &DeleteToPreviousWordStart,
7536 cx: &mut ViewContext<Self>,
7537 ) {
7538 self.transact(cx, |this, cx| {
7539 this.select_autoclose_pair(cx);
7540 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7541 let line_mode = s.line_mode;
7542 s.move_with(|map, selection| {
7543 if selection.is_empty() && !line_mode {
7544 let cursor = if action.ignore_newlines {
7545 movement::previous_word_start(map, selection.head())
7546 } else {
7547 movement::previous_word_start_or_newline(map, selection.head())
7548 };
7549 selection.set_head(cursor, SelectionGoal::None);
7550 }
7551 });
7552 });
7553 this.insert("", cx);
7554 });
7555 }
7556
7557 pub fn delete_to_previous_subword_start(
7558 &mut self,
7559 _: &DeleteToPreviousSubwordStart,
7560 cx: &mut ViewContext<Self>,
7561 ) {
7562 self.transact(cx, |this, cx| {
7563 this.select_autoclose_pair(cx);
7564 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7565 let line_mode = s.line_mode;
7566 s.move_with(|map, selection| {
7567 if selection.is_empty() && !line_mode {
7568 let cursor = movement::previous_subword_start(map, selection.head());
7569 selection.set_head(cursor, SelectionGoal::None);
7570 }
7571 });
7572 });
7573 this.insert("", cx);
7574 });
7575 }
7576
7577 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7578 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7579 s.move_cursors_with(|map, head, _| {
7580 (movement::next_word_end(map, head), SelectionGoal::None)
7581 });
7582 })
7583 }
7584
7585 pub fn move_to_next_subword_end(
7586 &mut self,
7587 _: &MoveToNextSubwordEnd,
7588 cx: &mut ViewContext<Self>,
7589 ) {
7590 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7591 s.move_cursors_with(|map, head, _| {
7592 (movement::next_subword_end(map, head), SelectionGoal::None)
7593 });
7594 })
7595 }
7596
7597 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7598 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7599 s.move_heads_with(|map, head, _| {
7600 (movement::next_word_end(map, head), SelectionGoal::None)
7601 });
7602 })
7603 }
7604
7605 pub fn select_to_next_subword_end(
7606 &mut self,
7607 _: &SelectToNextSubwordEnd,
7608 cx: &mut ViewContext<Self>,
7609 ) {
7610 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7611 s.move_heads_with(|map, head, _| {
7612 (movement::next_subword_end(map, head), SelectionGoal::None)
7613 });
7614 })
7615 }
7616
7617 pub fn delete_to_next_word_end(
7618 &mut self,
7619 action: &DeleteToNextWordEnd,
7620 cx: &mut ViewContext<Self>,
7621 ) {
7622 self.transact(cx, |this, cx| {
7623 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7624 let line_mode = s.line_mode;
7625 s.move_with(|map, selection| {
7626 if selection.is_empty() && !line_mode {
7627 let cursor = if action.ignore_newlines {
7628 movement::next_word_end(map, selection.head())
7629 } else {
7630 movement::next_word_end_or_newline(map, selection.head())
7631 };
7632 selection.set_head(cursor, SelectionGoal::None);
7633 }
7634 });
7635 });
7636 this.insert("", cx);
7637 });
7638 }
7639
7640 pub fn delete_to_next_subword_end(
7641 &mut self,
7642 _: &DeleteToNextSubwordEnd,
7643 cx: &mut ViewContext<Self>,
7644 ) {
7645 self.transact(cx, |this, cx| {
7646 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7647 s.move_with(|map, selection| {
7648 if selection.is_empty() {
7649 let cursor = movement::next_subword_end(map, selection.head());
7650 selection.set_head(cursor, SelectionGoal::None);
7651 }
7652 });
7653 });
7654 this.insert("", cx);
7655 });
7656 }
7657
7658 pub fn move_to_beginning_of_line(
7659 &mut self,
7660 action: &MoveToBeginningOfLine,
7661 cx: &mut ViewContext<Self>,
7662 ) {
7663 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7664 s.move_cursors_with(|map, head, _| {
7665 (
7666 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7667 SelectionGoal::None,
7668 )
7669 });
7670 })
7671 }
7672
7673 pub fn select_to_beginning_of_line(
7674 &mut self,
7675 action: &SelectToBeginningOfLine,
7676 cx: &mut ViewContext<Self>,
7677 ) {
7678 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7679 s.move_heads_with(|map, head, _| {
7680 (
7681 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7682 SelectionGoal::None,
7683 )
7684 });
7685 });
7686 }
7687
7688 pub fn delete_to_beginning_of_line(
7689 &mut self,
7690 _: &DeleteToBeginningOfLine,
7691 cx: &mut ViewContext<Self>,
7692 ) {
7693 self.transact(cx, |this, cx| {
7694 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7695 s.move_with(|_, selection| {
7696 selection.reversed = true;
7697 });
7698 });
7699
7700 this.select_to_beginning_of_line(
7701 &SelectToBeginningOfLine {
7702 stop_at_soft_wraps: false,
7703 },
7704 cx,
7705 );
7706 this.backspace(&Backspace, cx);
7707 });
7708 }
7709
7710 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7711 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7712 s.move_cursors_with(|map, head, _| {
7713 (
7714 movement::line_end(map, head, action.stop_at_soft_wraps),
7715 SelectionGoal::None,
7716 )
7717 });
7718 })
7719 }
7720
7721 pub fn select_to_end_of_line(
7722 &mut self,
7723 action: &SelectToEndOfLine,
7724 cx: &mut ViewContext<Self>,
7725 ) {
7726 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7727 s.move_heads_with(|map, head, _| {
7728 (
7729 movement::line_end(map, head, action.stop_at_soft_wraps),
7730 SelectionGoal::None,
7731 )
7732 });
7733 })
7734 }
7735
7736 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7737 self.transact(cx, |this, cx| {
7738 this.select_to_end_of_line(
7739 &SelectToEndOfLine {
7740 stop_at_soft_wraps: false,
7741 },
7742 cx,
7743 );
7744 this.delete(&Delete, cx);
7745 });
7746 }
7747
7748 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7749 self.transact(cx, |this, cx| {
7750 this.select_to_end_of_line(
7751 &SelectToEndOfLine {
7752 stop_at_soft_wraps: false,
7753 },
7754 cx,
7755 );
7756 this.cut(&Cut, cx);
7757 });
7758 }
7759
7760 pub fn move_to_start_of_paragraph(
7761 &mut self,
7762 _: &MoveToStartOfParagraph,
7763 cx: &mut ViewContext<Self>,
7764 ) {
7765 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7766 cx.propagate();
7767 return;
7768 }
7769
7770 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7771 s.move_with(|map, selection| {
7772 selection.collapse_to(
7773 movement::start_of_paragraph(map, selection.head(), 1),
7774 SelectionGoal::None,
7775 )
7776 });
7777 })
7778 }
7779
7780 pub fn move_to_end_of_paragraph(
7781 &mut self,
7782 _: &MoveToEndOfParagraph,
7783 cx: &mut ViewContext<Self>,
7784 ) {
7785 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7786 cx.propagate();
7787 return;
7788 }
7789
7790 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7791 s.move_with(|map, selection| {
7792 selection.collapse_to(
7793 movement::end_of_paragraph(map, selection.head(), 1),
7794 SelectionGoal::None,
7795 )
7796 });
7797 })
7798 }
7799
7800 pub fn select_to_start_of_paragraph(
7801 &mut self,
7802 _: &SelectToStartOfParagraph,
7803 cx: &mut ViewContext<Self>,
7804 ) {
7805 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7806 cx.propagate();
7807 return;
7808 }
7809
7810 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7811 s.move_heads_with(|map, head, _| {
7812 (
7813 movement::start_of_paragraph(map, head, 1),
7814 SelectionGoal::None,
7815 )
7816 });
7817 })
7818 }
7819
7820 pub fn select_to_end_of_paragraph(
7821 &mut self,
7822 _: &SelectToEndOfParagraph,
7823 cx: &mut ViewContext<Self>,
7824 ) {
7825 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7826 cx.propagate();
7827 return;
7828 }
7829
7830 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7831 s.move_heads_with(|map, head, _| {
7832 (
7833 movement::end_of_paragraph(map, head, 1),
7834 SelectionGoal::None,
7835 )
7836 });
7837 })
7838 }
7839
7840 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7841 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7842 cx.propagate();
7843 return;
7844 }
7845
7846 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7847 s.select_ranges(vec![0..0]);
7848 });
7849 }
7850
7851 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7852 let mut selection = self.selections.last::<Point>(cx);
7853 selection.set_head(Point::zero(), SelectionGoal::None);
7854
7855 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7856 s.select(vec![selection]);
7857 });
7858 }
7859
7860 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7861 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7862 cx.propagate();
7863 return;
7864 }
7865
7866 let cursor = self.buffer.read(cx).read(cx).len();
7867 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7868 s.select_ranges(vec![cursor..cursor])
7869 });
7870 }
7871
7872 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7873 self.nav_history = nav_history;
7874 }
7875
7876 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7877 self.nav_history.as_ref()
7878 }
7879
7880 fn push_to_nav_history(
7881 &mut self,
7882 cursor_anchor: Anchor,
7883 new_position: Option<Point>,
7884 cx: &mut ViewContext<Self>,
7885 ) {
7886 if let Some(nav_history) = self.nav_history.as_mut() {
7887 let buffer = self.buffer.read(cx).read(cx);
7888 let cursor_position = cursor_anchor.to_point(&buffer);
7889 let scroll_state = self.scroll_manager.anchor();
7890 let scroll_top_row = scroll_state.top_row(&buffer);
7891 drop(buffer);
7892
7893 if let Some(new_position) = new_position {
7894 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7895 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7896 return;
7897 }
7898 }
7899
7900 nav_history.push(
7901 Some(NavigationData {
7902 cursor_anchor,
7903 cursor_position,
7904 scroll_anchor: scroll_state,
7905 scroll_top_row,
7906 }),
7907 cx,
7908 );
7909 }
7910 }
7911
7912 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7913 let buffer = self.buffer.read(cx).snapshot(cx);
7914 let mut selection = self.selections.first::<usize>(cx);
7915 selection.set_head(buffer.len(), SelectionGoal::None);
7916 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7917 s.select(vec![selection]);
7918 });
7919 }
7920
7921 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7922 let end = self.buffer.read(cx).read(cx).len();
7923 self.change_selections(None, cx, |s| {
7924 s.select_ranges(vec![0..end]);
7925 });
7926 }
7927
7928 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7929 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7930 let mut selections = self.selections.all::<Point>(cx);
7931 let max_point = display_map.buffer_snapshot.max_point();
7932 for selection in &mut selections {
7933 let rows = selection.spanned_rows(true, &display_map);
7934 selection.start = Point::new(rows.start.0, 0);
7935 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7936 selection.reversed = false;
7937 }
7938 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7939 s.select(selections);
7940 });
7941 }
7942
7943 pub fn split_selection_into_lines(
7944 &mut self,
7945 _: &SplitSelectionIntoLines,
7946 cx: &mut ViewContext<Self>,
7947 ) {
7948 let mut to_unfold = Vec::new();
7949 let mut new_selection_ranges = Vec::new();
7950 {
7951 let selections = self.selections.all::<Point>(cx);
7952 let buffer = self.buffer.read(cx).read(cx);
7953 for selection in selections {
7954 for row in selection.start.row..selection.end.row {
7955 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7956 new_selection_ranges.push(cursor..cursor);
7957 }
7958 new_selection_ranges.push(selection.end..selection.end);
7959 to_unfold.push(selection.start..selection.end);
7960 }
7961 }
7962 self.unfold_ranges(to_unfold, true, true, cx);
7963 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7964 s.select_ranges(new_selection_ranges);
7965 });
7966 }
7967
7968 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
7969 self.add_selection(true, cx);
7970 }
7971
7972 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
7973 self.add_selection(false, cx);
7974 }
7975
7976 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
7977 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7978 let mut selections = self.selections.all::<Point>(cx);
7979 let text_layout_details = self.text_layout_details(cx);
7980 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
7981 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
7982 let range = oldest_selection.display_range(&display_map).sorted();
7983
7984 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
7985 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
7986 let positions = start_x.min(end_x)..start_x.max(end_x);
7987
7988 selections.clear();
7989 let mut stack = Vec::new();
7990 for row in range.start.row().0..=range.end.row().0 {
7991 if let Some(selection) = self.selections.build_columnar_selection(
7992 &display_map,
7993 DisplayRow(row),
7994 &positions,
7995 oldest_selection.reversed,
7996 &text_layout_details,
7997 ) {
7998 stack.push(selection.id);
7999 selections.push(selection);
8000 }
8001 }
8002
8003 if above {
8004 stack.reverse();
8005 }
8006
8007 AddSelectionsState { above, stack }
8008 });
8009
8010 let last_added_selection = *state.stack.last().unwrap();
8011 let mut new_selections = Vec::new();
8012 if above == state.above {
8013 let end_row = if above {
8014 DisplayRow(0)
8015 } else {
8016 display_map.max_point().row()
8017 };
8018
8019 'outer: for selection in selections {
8020 if selection.id == last_added_selection {
8021 let range = selection.display_range(&display_map).sorted();
8022 debug_assert_eq!(range.start.row(), range.end.row());
8023 let mut row = range.start.row();
8024 let positions =
8025 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8026 px(start)..px(end)
8027 } else {
8028 let start_x =
8029 display_map.x_for_display_point(range.start, &text_layout_details);
8030 let end_x =
8031 display_map.x_for_display_point(range.end, &text_layout_details);
8032 start_x.min(end_x)..start_x.max(end_x)
8033 };
8034
8035 while row != end_row {
8036 if above {
8037 row.0 -= 1;
8038 } else {
8039 row.0 += 1;
8040 }
8041
8042 if let Some(new_selection) = self.selections.build_columnar_selection(
8043 &display_map,
8044 row,
8045 &positions,
8046 selection.reversed,
8047 &text_layout_details,
8048 ) {
8049 state.stack.push(new_selection.id);
8050 if above {
8051 new_selections.push(new_selection);
8052 new_selections.push(selection);
8053 } else {
8054 new_selections.push(selection);
8055 new_selections.push(new_selection);
8056 }
8057
8058 continue 'outer;
8059 }
8060 }
8061 }
8062
8063 new_selections.push(selection);
8064 }
8065 } else {
8066 new_selections = selections;
8067 new_selections.retain(|s| s.id != last_added_selection);
8068 state.stack.pop();
8069 }
8070
8071 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8072 s.select(new_selections);
8073 });
8074 if state.stack.len() > 1 {
8075 self.add_selections_state = Some(state);
8076 }
8077 }
8078
8079 pub fn select_next_match_internal(
8080 &mut self,
8081 display_map: &DisplaySnapshot,
8082 replace_newest: bool,
8083 autoscroll: Option<Autoscroll>,
8084 cx: &mut ViewContext<Self>,
8085 ) -> Result<()> {
8086 fn select_next_match_ranges(
8087 this: &mut Editor,
8088 range: Range<usize>,
8089 replace_newest: bool,
8090 auto_scroll: Option<Autoscroll>,
8091 cx: &mut ViewContext<Editor>,
8092 ) {
8093 this.unfold_ranges([range.clone()], false, true, cx);
8094 this.change_selections(auto_scroll, cx, |s| {
8095 if replace_newest {
8096 s.delete(s.newest_anchor().id);
8097 }
8098 s.insert_range(range.clone());
8099 });
8100 }
8101
8102 let buffer = &display_map.buffer_snapshot;
8103 let mut selections = self.selections.all::<usize>(cx);
8104 if let Some(mut select_next_state) = self.select_next_state.take() {
8105 let query = &select_next_state.query;
8106 if !select_next_state.done {
8107 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8108 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8109 let mut next_selected_range = None;
8110
8111 let bytes_after_last_selection =
8112 buffer.bytes_in_range(last_selection.end..buffer.len());
8113 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8114 let query_matches = query
8115 .stream_find_iter(bytes_after_last_selection)
8116 .map(|result| (last_selection.end, result))
8117 .chain(
8118 query
8119 .stream_find_iter(bytes_before_first_selection)
8120 .map(|result| (0, result)),
8121 );
8122
8123 for (start_offset, query_match) in query_matches {
8124 let query_match = query_match.unwrap(); // can only fail due to I/O
8125 let offset_range =
8126 start_offset + query_match.start()..start_offset + query_match.end();
8127 let display_range = offset_range.start.to_display_point(display_map)
8128 ..offset_range.end.to_display_point(display_map);
8129
8130 if !select_next_state.wordwise
8131 || (!movement::is_inside_word(display_map, display_range.start)
8132 && !movement::is_inside_word(display_map, display_range.end))
8133 {
8134 // TODO: This is n^2, because we might check all the selections
8135 if !selections
8136 .iter()
8137 .any(|selection| selection.range().overlaps(&offset_range))
8138 {
8139 next_selected_range = Some(offset_range);
8140 break;
8141 }
8142 }
8143 }
8144
8145 if let Some(next_selected_range) = next_selected_range {
8146 select_next_match_ranges(
8147 self,
8148 next_selected_range,
8149 replace_newest,
8150 autoscroll,
8151 cx,
8152 );
8153 } else {
8154 select_next_state.done = true;
8155 }
8156 }
8157
8158 self.select_next_state = Some(select_next_state);
8159 } else {
8160 let mut only_carets = true;
8161 let mut same_text_selected = true;
8162 let mut selected_text = None;
8163
8164 let mut selections_iter = selections.iter().peekable();
8165 while let Some(selection) = selections_iter.next() {
8166 if selection.start != selection.end {
8167 only_carets = false;
8168 }
8169
8170 if same_text_selected {
8171 if selected_text.is_none() {
8172 selected_text =
8173 Some(buffer.text_for_range(selection.range()).collect::<String>());
8174 }
8175
8176 if let Some(next_selection) = selections_iter.peek() {
8177 if next_selection.range().len() == selection.range().len() {
8178 let next_selected_text = buffer
8179 .text_for_range(next_selection.range())
8180 .collect::<String>();
8181 if Some(next_selected_text) != selected_text {
8182 same_text_selected = false;
8183 selected_text = None;
8184 }
8185 } else {
8186 same_text_selected = false;
8187 selected_text = None;
8188 }
8189 }
8190 }
8191 }
8192
8193 if only_carets {
8194 for selection in &mut selections {
8195 let word_range = movement::surrounding_word(
8196 display_map,
8197 selection.start.to_display_point(display_map),
8198 );
8199 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8200 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8201 selection.goal = SelectionGoal::None;
8202 selection.reversed = false;
8203 select_next_match_ranges(
8204 self,
8205 selection.start..selection.end,
8206 replace_newest,
8207 autoscroll,
8208 cx,
8209 );
8210 }
8211
8212 if selections.len() == 1 {
8213 let selection = selections
8214 .last()
8215 .expect("ensured that there's only one selection");
8216 let query = buffer
8217 .text_for_range(selection.start..selection.end)
8218 .collect::<String>();
8219 let is_empty = query.is_empty();
8220 let select_state = SelectNextState {
8221 query: AhoCorasick::new(&[query])?,
8222 wordwise: true,
8223 done: is_empty,
8224 };
8225 self.select_next_state = Some(select_state);
8226 } else {
8227 self.select_next_state = None;
8228 }
8229 } else if let Some(selected_text) = selected_text {
8230 self.select_next_state = Some(SelectNextState {
8231 query: AhoCorasick::new(&[selected_text])?,
8232 wordwise: false,
8233 done: false,
8234 });
8235 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8236 }
8237 }
8238 Ok(())
8239 }
8240
8241 pub fn select_all_matches(
8242 &mut self,
8243 _action: &SelectAllMatches,
8244 cx: &mut ViewContext<Self>,
8245 ) -> Result<()> {
8246 self.push_to_selection_history();
8247 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8248
8249 self.select_next_match_internal(&display_map, false, None, cx)?;
8250 let Some(select_next_state) = self.select_next_state.as_mut() else {
8251 return Ok(());
8252 };
8253 if select_next_state.done {
8254 return Ok(());
8255 }
8256
8257 let mut new_selections = self.selections.all::<usize>(cx);
8258
8259 let buffer = &display_map.buffer_snapshot;
8260 let query_matches = select_next_state
8261 .query
8262 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8263
8264 for query_match in query_matches {
8265 let query_match = query_match.unwrap(); // can only fail due to I/O
8266 let offset_range = query_match.start()..query_match.end();
8267 let display_range = offset_range.start.to_display_point(&display_map)
8268 ..offset_range.end.to_display_point(&display_map);
8269
8270 if !select_next_state.wordwise
8271 || (!movement::is_inside_word(&display_map, display_range.start)
8272 && !movement::is_inside_word(&display_map, display_range.end))
8273 {
8274 self.selections.change_with(cx, |selections| {
8275 new_selections.push(Selection {
8276 id: selections.new_selection_id(),
8277 start: offset_range.start,
8278 end: offset_range.end,
8279 reversed: false,
8280 goal: SelectionGoal::None,
8281 });
8282 });
8283 }
8284 }
8285
8286 new_selections.sort_by_key(|selection| selection.start);
8287 let mut ix = 0;
8288 while ix + 1 < new_selections.len() {
8289 let current_selection = &new_selections[ix];
8290 let next_selection = &new_selections[ix + 1];
8291 if current_selection.range().overlaps(&next_selection.range()) {
8292 if current_selection.id < next_selection.id {
8293 new_selections.remove(ix + 1);
8294 } else {
8295 new_selections.remove(ix);
8296 }
8297 } else {
8298 ix += 1;
8299 }
8300 }
8301
8302 select_next_state.done = true;
8303 self.unfold_ranges(
8304 new_selections.iter().map(|selection| selection.range()),
8305 false,
8306 false,
8307 cx,
8308 );
8309 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8310 selections.select(new_selections)
8311 });
8312
8313 Ok(())
8314 }
8315
8316 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8317 self.push_to_selection_history();
8318 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8319 self.select_next_match_internal(
8320 &display_map,
8321 action.replace_newest,
8322 Some(Autoscroll::newest()),
8323 cx,
8324 )?;
8325 Ok(())
8326 }
8327
8328 pub fn select_previous(
8329 &mut self,
8330 action: &SelectPrevious,
8331 cx: &mut ViewContext<Self>,
8332 ) -> Result<()> {
8333 self.push_to_selection_history();
8334 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8335 let buffer = &display_map.buffer_snapshot;
8336 let mut selections = self.selections.all::<usize>(cx);
8337 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8338 let query = &select_prev_state.query;
8339 if !select_prev_state.done {
8340 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8341 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8342 let mut next_selected_range = None;
8343 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8344 let bytes_before_last_selection =
8345 buffer.reversed_bytes_in_range(0..last_selection.start);
8346 let bytes_after_first_selection =
8347 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8348 let query_matches = query
8349 .stream_find_iter(bytes_before_last_selection)
8350 .map(|result| (last_selection.start, result))
8351 .chain(
8352 query
8353 .stream_find_iter(bytes_after_first_selection)
8354 .map(|result| (buffer.len(), result)),
8355 );
8356 for (end_offset, query_match) in query_matches {
8357 let query_match = query_match.unwrap(); // can only fail due to I/O
8358 let offset_range =
8359 end_offset - query_match.end()..end_offset - query_match.start();
8360 let display_range = offset_range.start.to_display_point(&display_map)
8361 ..offset_range.end.to_display_point(&display_map);
8362
8363 if !select_prev_state.wordwise
8364 || (!movement::is_inside_word(&display_map, display_range.start)
8365 && !movement::is_inside_word(&display_map, display_range.end))
8366 {
8367 next_selected_range = Some(offset_range);
8368 break;
8369 }
8370 }
8371
8372 if let Some(next_selected_range) = next_selected_range {
8373 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8374 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8375 if action.replace_newest {
8376 s.delete(s.newest_anchor().id);
8377 }
8378 s.insert_range(next_selected_range);
8379 });
8380 } else {
8381 select_prev_state.done = true;
8382 }
8383 }
8384
8385 self.select_prev_state = Some(select_prev_state);
8386 } else {
8387 let mut only_carets = true;
8388 let mut same_text_selected = true;
8389 let mut selected_text = None;
8390
8391 let mut selections_iter = selections.iter().peekable();
8392 while let Some(selection) = selections_iter.next() {
8393 if selection.start != selection.end {
8394 only_carets = false;
8395 }
8396
8397 if same_text_selected {
8398 if selected_text.is_none() {
8399 selected_text =
8400 Some(buffer.text_for_range(selection.range()).collect::<String>());
8401 }
8402
8403 if let Some(next_selection) = selections_iter.peek() {
8404 if next_selection.range().len() == selection.range().len() {
8405 let next_selected_text = buffer
8406 .text_for_range(next_selection.range())
8407 .collect::<String>();
8408 if Some(next_selected_text) != selected_text {
8409 same_text_selected = false;
8410 selected_text = None;
8411 }
8412 } else {
8413 same_text_selected = false;
8414 selected_text = None;
8415 }
8416 }
8417 }
8418 }
8419
8420 if only_carets {
8421 for selection in &mut selections {
8422 let word_range = movement::surrounding_word(
8423 &display_map,
8424 selection.start.to_display_point(&display_map),
8425 );
8426 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8427 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8428 selection.goal = SelectionGoal::None;
8429 selection.reversed = false;
8430 }
8431 if selections.len() == 1 {
8432 let selection = selections
8433 .last()
8434 .expect("ensured that there's only one selection");
8435 let query = buffer
8436 .text_for_range(selection.start..selection.end)
8437 .collect::<String>();
8438 let is_empty = query.is_empty();
8439 let select_state = SelectNextState {
8440 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8441 wordwise: true,
8442 done: is_empty,
8443 };
8444 self.select_prev_state = Some(select_state);
8445 } else {
8446 self.select_prev_state = None;
8447 }
8448
8449 self.unfold_ranges(
8450 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8451 false,
8452 true,
8453 cx,
8454 );
8455 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8456 s.select(selections);
8457 });
8458 } else if let Some(selected_text) = selected_text {
8459 self.select_prev_state = Some(SelectNextState {
8460 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8461 wordwise: false,
8462 done: false,
8463 });
8464 self.select_previous(action, cx)?;
8465 }
8466 }
8467 Ok(())
8468 }
8469
8470 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8471 let text_layout_details = &self.text_layout_details(cx);
8472 self.transact(cx, |this, cx| {
8473 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8474 let mut edits = Vec::new();
8475 let mut selection_edit_ranges = Vec::new();
8476 let mut last_toggled_row = None;
8477 let snapshot = this.buffer.read(cx).read(cx);
8478 let empty_str: Arc<str> = Arc::default();
8479 let mut suffixes_inserted = Vec::new();
8480
8481 fn comment_prefix_range(
8482 snapshot: &MultiBufferSnapshot,
8483 row: MultiBufferRow,
8484 comment_prefix: &str,
8485 comment_prefix_whitespace: &str,
8486 ) -> Range<Point> {
8487 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8488
8489 let mut line_bytes = snapshot
8490 .bytes_in_range(start..snapshot.max_point())
8491 .flatten()
8492 .copied();
8493
8494 // If this line currently begins with the line comment prefix, then record
8495 // the range containing the prefix.
8496 if line_bytes
8497 .by_ref()
8498 .take(comment_prefix.len())
8499 .eq(comment_prefix.bytes())
8500 {
8501 // Include any whitespace that matches the comment prefix.
8502 let matching_whitespace_len = line_bytes
8503 .zip(comment_prefix_whitespace.bytes())
8504 .take_while(|(a, b)| a == b)
8505 .count() as u32;
8506 let end = Point::new(
8507 start.row,
8508 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8509 );
8510 start..end
8511 } else {
8512 start..start
8513 }
8514 }
8515
8516 fn comment_suffix_range(
8517 snapshot: &MultiBufferSnapshot,
8518 row: MultiBufferRow,
8519 comment_suffix: &str,
8520 comment_suffix_has_leading_space: bool,
8521 ) -> Range<Point> {
8522 let end = Point::new(row.0, snapshot.line_len(row));
8523 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8524
8525 let mut line_end_bytes = snapshot
8526 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8527 .flatten()
8528 .copied();
8529
8530 let leading_space_len = if suffix_start_column > 0
8531 && line_end_bytes.next() == Some(b' ')
8532 && comment_suffix_has_leading_space
8533 {
8534 1
8535 } else {
8536 0
8537 };
8538
8539 // If this line currently begins with the line comment prefix, then record
8540 // the range containing the prefix.
8541 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8542 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8543 start..end
8544 } else {
8545 end..end
8546 }
8547 }
8548
8549 // TODO: Handle selections that cross excerpts
8550 for selection in &mut selections {
8551 let start_column = snapshot
8552 .indent_size_for_line(MultiBufferRow(selection.start.row))
8553 .len;
8554 let language = if let Some(language) =
8555 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8556 {
8557 language
8558 } else {
8559 continue;
8560 };
8561
8562 selection_edit_ranges.clear();
8563
8564 // If multiple selections contain a given row, avoid processing that
8565 // row more than once.
8566 let mut start_row = MultiBufferRow(selection.start.row);
8567 if last_toggled_row == Some(start_row) {
8568 start_row = start_row.next_row();
8569 }
8570 let end_row =
8571 if selection.end.row > selection.start.row && selection.end.column == 0 {
8572 MultiBufferRow(selection.end.row - 1)
8573 } else {
8574 MultiBufferRow(selection.end.row)
8575 };
8576 last_toggled_row = Some(end_row);
8577
8578 if start_row > end_row {
8579 continue;
8580 }
8581
8582 // If the language has line comments, toggle those.
8583 let full_comment_prefixes = language.line_comment_prefixes();
8584 if !full_comment_prefixes.is_empty() {
8585 let first_prefix = full_comment_prefixes
8586 .first()
8587 .expect("prefixes is non-empty");
8588 let prefix_trimmed_lengths = full_comment_prefixes
8589 .iter()
8590 .map(|p| p.trim_end_matches(' ').len())
8591 .collect::<SmallVec<[usize; 4]>>();
8592
8593 let mut all_selection_lines_are_comments = true;
8594
8595 for row in start_row.0..=end_row.0 {
8596 let row = MultiBufferRow(row);
8597 if start_row < end_row && snapshot.is_line_blank(row) {
8598 continue;
8599 }
8600
8601 let prefix_range = full_comment_prefixes
8602 .iter()
8603 .zip(prefix_trimmed_lengths.iter().copied())
8604 .map(|(prefix, trimmed_prefix_len)| {
8605 comment_prefix_range(
8606 snapshot.deref(),
8607 row,
8608 &prefix[..trimmed_prefix_len],
8609 &prefix[trimmed_prefix_len..],
8610 )
8611 })
8612 .max_by_key(|range| range.end.column - range.start.column)
8613 .expect("prefixes is non-empty");
8614
8615 if prefix_range.is_empty() {
8616 all_selection_lines_are_comments = false;
8617 }
8618
8619 selection_edit_ranges.push(prefix_range);
8620 }
8621
8622 if all_selection_lines_are_comments {
8623 edits.extend(
8624 selection_edit_ranges
8625 .iter()
8626 .cloned()
8627 .map(|range| (range, empty_str.clone())),
8628 );
8629 } else {
8630 let min_column = selection_edit_ranges
8631 .iter()
8632 .map(|range| range.start.column)
8633 .min()
8634 .unwrap_or(0);
8635 edits.extend(selection_edit_ranges.iter().map(|range| {
8636 let position = Point::new(range.start.row, min_column);
8637 (position..position, first_prefix.clone())
8638 }));
8639 }
8640 } else if let Some((full_comment_prefix, comment_suffix)) =
8641 language.block_comment_delimiters()
8642 {
8643 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8644 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8645 let prefix_range = comment_prefix_range(
8646 snapshot.deref(),
8647 start_row,
8648 comment_prefix,
8649 comment_prefix_whitespace,
8650 );
8651 let suffix_range = comment_suffix_range(
8652 snapshot.deref(),
8653 end_row,
8654 comment_suffix.trim_start_matches(' '),
8655 comment_suffix.starts_with(' '),
8656 );
8657
8658 if prefix_range.is_empty() || suffix_range.is_empty() {
8659 edits.push((
8660 prefix_range.start..prefix_range.start,
8661 full_comment_prefix.clone(),
8662 ));
8663 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8664 suffixes_inserted.push((end_row, comment_suffix.len()));
8665 } else {
8666 edits.push((prefix_range, empty_str.clone()));
8667 edits.push((suffix_range, empty_str.clone()));
8668 }
8669 } else {
8670 continue;
8671 }
8672 }
8673
8674 drop(snapshot);
8675 this.buffer.update(cx, |buffer, cx| {
8676 buffer.edit(edits, None, cx);
8677 });
8678
8679 // Adjust selections so that they end before any comment suffixes that
8680 // were inserted.
8681 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8682 let mut selections = this.selections.all::<Point>(cx);
8683 let snapshot = this.buffer.read(cx).read(cx);
8684 for selection in &mut selections {
8685 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8686 match row.cmp(&MultiBufferRow(selection.end.row)) {
8687 Ordering::Less => {
8688 suffixes_inserted.next();
8689 continue;
8690 }
8691 Ordering::Greater => break,
8692 Ordering::Equal => {
8693 if selection.end.column == snapshot.line_len(row) {
8694 if selection.is_empty() {
8695 selection.start.column -= suffix_len as u32;
8696 }
8697 selection.end.column -= suffix_len as u32;
8698 }
8699 break;
8700 }
8701 }
8702 }
8703 }
8704
8705 drop(snapshot);
8706 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8707
8708 let selections = this.selections.all::<Point>(cx);
8709 let selections_on_single_row = selections.windows(2).all(|selections| {
8710 selections[0].start.row == selections[1].start.row
8711 && selections[0].end.row == selections[1].end.row
8712 && selections[0].start.row == selections[0].end.row
8713 });
8714 let selections_selecting = selections
8715 .iter()
8716 .any(|selection| selection.start != selection.end);
8717 let advance_downwards = action.advance_downwards
8718 && selections_on_single_row
8719 && !selections_selecting
8720 && !matches!(this.mode, EditorMode::SingleLine { .. });
8721
8722 if advance_downwards {
8723 let snapshot = this.buffer.read(cx).snapshot(cx);
8724
8725 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8726 s.move_cursors_with(|display_snapshot, display_point, _| {
8727 let mut point = display_point.to_point(display_snapshot);
8728 point.row += 1;
8729 point = snapshot.clip_point(point, Bias::Left);
8730 let display_point = point.to_display_point(display_snapshot);
8731 let goal = SelectionGoal::HorizontalPosition(
8732 display_snapshot
8733 .x_for_display_point(display_point, text_layout_details)
8734 .into(),
8735 );
8736 (display_point, goal)
8737 })
8738 });
8739 }
8740 });
8741 }
8742
8743 pub fn select_enclosing_symbol(
8744 &mut self,
8745 _: &SelectEnclosingSymbol,
8746 cx: &mut ViewContext<Self>,
8747 ) {
8748 let buffer = self.buffer.read(cx).snapshot(cx);
8749 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8750
8751 fn update_selection(
8752 selection: &Selection<usize>,
8753 buffer_snap: &MultiBufferSnapshot,
8754 ) -> Option<Selection<usize>> {
8755 let cursor = selection.head();
8756 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8757 for symbol in symbols.iter().rev() {
8758 let start = symbol.range.start.to_offset(buffer_snap);
8759 let end = symbol.range.end.to_offset(buffer_snap);
8760 let new_range = start..end;
8761 if start < selection.start || end > selection.end {
8762 return Some(Selection {
8763 id: selection.id,
8764 start: new_range.start,
8765 end: new_range.end,
8766 goal: SelectionGoal::None,
8767 reversed: selection.reversed,
8768 });
8769 }
8770 }
8771 None
8772 }
8773
8774 let mut selected_larger_symbol = false;
8775 let new_selections = old_selections
8776 .iter()
8777 .map(|selection| match update_selection(selection, &buffer) {
8778 Some(new_selection) => {
8779 if new_selection.range() != selection.range() {
8780 selected_larger_symbol = true;
8781 }
8782 new_selection
8783 }
8784 None => selection.clone(),
8785 })
8786 .collect::<Vec<_>>();
8787
8788 if selected_larger_symbol {
8789 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8790 s.select(new_selections);
8791 });
8792 }
8793 }
8794
8795 pub fn select_larger_syntax_node(
8796 &mut self,
8797 _: &SelectLargerSyntaxNode,
8798 cx: &mut ViewContext<Self>,
8799 ) {
8800 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8801 let buffer = self.buffer.read(cx).snapshot(cx);
8802 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8803
8804 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8805 let mut selected_larger_node = false;
8806 let new_selections = old_selections
8807 .iter()
8808 .map(|selection| {
8809 let old_range = selection.start..selection.end;
8810 let mut new_range = old_range.clone();
8811 while let Some(containing_range) =
8812 buffer.range_for_syntax_ancestor(new_range.clone())
8813 {
8814 new_range = containing_range;
8815 if !display_map.intersects_fold(new_range.start)
8816 && !display_map.intersects_fold(new_range.end)
8817 {
8818 break;
8819 }
8820 }
8821
8822 selected_larger_node |= new_range != old_range;
8823 Selection {
8824 id: selection.id,
8825 start: new_range.start,
8826 end: new_range.end,
8827 goal: SelectionGoal::None,
8828 reversed: selection.reversed,
8829 }
8830 })
8831 .collect::<Vec<_>>();
8832
8833 if selected_larger_node {
8834 stack.push(old_selections);
8835 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8836 s.select(new_selections);
8837 });
8838 }
8839 self.select_larger_syntax_node_stack = stack;
8840 }
8841
8842 pub fn select_smaller_syntax_node(
8843 &mut self,
8844 _: &SelectSmallerSyntaxNode,
8845 cx: &mut ViewContext<Self>,
8846 ) {
8847 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8848 if let Some(selections) = stack.pop() {
8849 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8850 s.select(selections.to_vec());
8851 });
8852 }
8853 self.select_larger_syntax_node_stack = stack;
8854 }
8855
8856 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8857 if !EditorSettings::get_global(cx).gutter.runnables {
8858 self.clear_tasks();
8859 return Task::ready(());
8860 }
8861 let project = self.project.clone();
8862 cx.spawn(|this, mut cx| async move {
8863 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8864 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8865 }) else {
8866 return;
8867 };
8868
8869 let Some(project) = project else {
8870 return;
8871 };
8872
8873 let hide_runnables = project
8874 .update(&mut cx, |project, cx| {
8875 // Do not display any test indicators in non-dev server remote projects.
8876 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8877 })
8878 .unwrap_or(true);
8879 if hide_runnables {
8880 return;
8881 }
8882 let new_rows =
8883 cx.background_executor()
8884 .spawn({
8885 let snapshot = display_snapshot.clone();
8886 async move {
8887 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8888 }
8889 })
8890 .await;
8891 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8892
8893 this.update(&mut cx, |this, _| {
8894 this.clear_tasks();
8895 for (key, value) in rows {
8896 this.insert_tasks(key, value);
8897 }
8898 })
8899 .ok();
8900 })
8901 }
8902 fn fetch_runnable_ranges(
8903 snapshot: &DisplaySnapshot,
8904 range: Range<Anchor>,
8905 ) -> Vec<language::RunnableRange> {
8906 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8907 }
8908
8909 fn runnable_rows(
8910 project: Model<Project>,
8911 snapshot: DisplaySnapshot,
8912 runnable_ranges: Vec<RunnableRange>,
8913 mut cx: AsyncWindowContext,
8914 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8915 runnable_ranges
8916 .into_iter()
8917 .filter_map(|mut runnable| {
8918 let tasks = cx
8919 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8920 .ok()?;
8921 if tasks.is_empty() {
8922 return None;
8923 }
8924
8925 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8926
8927 let row = snapshot
8928 .buffer_snapshot
8929 .buffer_line_for_row(MultiBufferRow(point.row))?
8930 .1
8931 .start
8932 .row;
8933
8934 let context_range =
8935 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8936 Some((
8937 (runnable.buffer_id, row),
8938 RunnableTasks {
8939 templates: tasks,
8940 offset: MultiBufferOffset(runnable.run_range.start),
8941 context_range,
8942 column: point.column,
8943 extra_variables: runnable.extra_captures,
8944 },
8945 ))
8946 })
8947 .collect()
8948 }
8949
8950 fn templates_with_tags(
8951 project: &Model<Project>,
8952 runnable: &mut Runnable,
8953 cx: &WindowContext<'_>,
8954 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8955 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8956 let (worktree_id, file) = project
8957 .buffer_for_id(runnable.buffer, cx)
8958 .and_then(|buffer| buffer.read(cx).file())
8959 .map(|file| (file.worktree_id(cx), file.clone()))
8960 .unzip();
8961
8962 (project.task_inventory().clone(), worktree_id, file)
8963 });
8964
8965 let inventory = inventory.read(cx);
8966 let tags = mem::take(&mut runnable.tags);
8967 let mut tags: Vec<_> = tags
8968 .into_iter()
8969 .flat_map(|tag| {
8970 let tag = tag.0.clone();
8971 inventory
8972 .list_tasks(
8973 file.clone(),
8974 Some(runnable.language.clone()),
8975 worktree_id,
8976 cx,
8977 )
8978 .into_iter()
8979 .filter(move |(_, template)| {
8980 template.tags.iter().any(|source_tag| source_tag == &tag)
8981 })
8982 })
8983 .sorted_by_key(|(kind, _)| kind.to_owned())
8984 .collect();
8985 if let Some((leading_tag_source, _)) = tags.first() {
8986 // Strongest source wins; if we have worktree tag binding, prefer that to
8987 // global and language bindings;
8988 // if we have a global binding, prefer that to language binding.
8989 let first_mismatch = tags
8990 .iter()
8991 .position(|(tag_source, _)| tag_source != leading_tag_source);
8992 if let Some(index) = first_mismatch {
8993 tags.truncate(index);
8994 }
8995 }
8996
8997 tags
8998 }
8999
9000 pub fn move_to_enclosing_bracket(
9001 &mut self,
9002 _: &MoveToEnclosingBracket,
9003 cx: &mut ViewContext<Self>,
9004 ) {
9005 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9006 s.move_offsets_with(|snapshot, selection| {
9007 let Some(enclosing_bracket_ranges) =
9008 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9009 else {
9010 return;
9011 };
9012
9013 let mut best_length = usize::MAX;
9014 let mut best_inside = false;
9015 let mut best_in_bracket_range = false;
9016 let mut best_destination = None;
9017 for (open, close) in enclosing_bracket_ranges {
9018 let close = close.to_inclusive();
9019 let length = close.end() - open.start;
9020 let inside = selection.start >= open.end && selection.end <= *close.start();
9021 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9022 || close.contains(&selection.head());
9023
9024 // If best is next to a bracket and current isn't, skip
9025 if !in_bracket_range && best_in_bracket_range {
9026 continue;
9027 }
9028
9029 // Prefer smaller lengths unless best is inside and current isn't
9030 if length > best_length && (best_inside || !inside) {
9031 continue;
9032 }
9033
9034 best_length = length;
9035 best_inside = inside;
9036 best_in_bracket_range = in_bracket_range;
9037 best_destination = Some(
9038 if close.contains(&selection.start) && close.contains(&selection.end) {
9039 if inside {
9040 open.end
9041 } else {
9042 open.start
9043 }
9044 } else if inside {
9045 *close.start()
9046 } else {
9047 *close.end()
9048 },
9049 );
9050 }
9051
9052 if let Some(destination) = best_destination {
9053 selection.collapse_to(destination, SelectionGoal::None);
9054 }
9055 })
9056 });
9057 }
9058
9059 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9060 self.end_selection(cx);
9061 self.selection_history.mode = SelectionHistoryMode::Undoing;
9062 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9063 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9064 self.select_next_state = entry.select_next_state;
9065 self.select_prev_state = entry.select_prev_state;
9066 self.add_selections_state = entry.add_selections_state;
9067 self.request_autoscroll(Autoscroll::newest(), cx);
9068 }
9069 self.selection_history.mode = SelectionHistoryMode::Normal;
9070 }
9071
9072 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9073 self.end_selection(cx);
9074 self.selection_history.mode = SelectionHistoryMode::Redoing;
9075 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9076 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9077 self.select_next_state = entry.select_next_state;
9078 self.select_prev_state = entry.select_prev_state;
9079 self.add_selections_state = entry.add_selections_state;
9080 self.request_autoscroll(Autoscroll::newest(), cx);
9081 }
9082 self.selection_history.mode = SelectionHistoryMode::Normal;
9083 }
9084
9085 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9086 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9087 }
9088
9089 pub fn expand_excerpts_down(
9090 &mut self,
9091 action: &ExpandExcerptsDown,
9092 cx: &mut ViewContext<Self>,
9093 ) {
9094 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9095 }
9096
9097 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9098 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9099 }
9100
9101 pub fn expand_excerpts_for_direction(
9102 &mut self,
9103 lines: u32,
9104 direction: ExpandExcerptDirection,
9105 cx: &mut ViewContext<Self>,
9106 ) {
9107 let selections = self.selections.disjoint_anchors();
9108
9109 let lines = if lines == 0 {
9110 EditorSettings::get_global(cx).expand_excerpt_lines
9111 } else {
9112 lines
9113 };
9114
9115 self.buffer.update(cx, |buffer, cx| {
9116 buffer.expand_excerpts(
9117 selections
9118 .iter()
9119 .map(|selection| selection.head().excerpt_id)
9120 .dedup(),
9121 lines,
9122 direction,
9123 cx,
9124 )
9125 })
9126 }
9127
9128 pub fn expand_excerpt(
9129 &mut self,
9130 excerpt: ExcerptId,
9131 direction: ExpandExcerptDirection,
9132 cx: &mut ViewContext<Self>,
9133 ) {
9134 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9135 self.buffer.update(cx, |buffer, cx| {
9136 buffer.expand_excerpts([excerpt], lines, direction, cx)
9137 })
9138 }
9139
9140 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9141 self.go_to_diagnostic_impl(Direction::Next, cx)
9142 }
9143
9144 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9145 self.go_to_diagnostic_impl(Direction::Prev, cx)
9146 }
9147
9148 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9149 let buffer = self.buffer.read(cx).snapshot(cx);
9150 let selection = self.selections.newest::<usize>(cx);
9151
9152 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9153 if direction == Direction::Next {
9154 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9155 let (group_id, jump_to) = popover.activation_info();
9156 if self.activate_diagnostics(group_id, cx) {
9157 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9158 let mut new_selection = s.newest_anchor().clone();
9159 new_selection.collapse_to(jump_to, SelectionGoal::None);
9160 s.select_anchors(vec![new_selection.clone()]);
9161 });
9162 }
9163 return;
9164 }
9165 }
9166
9167 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9168 active_diagnostics
9169 .primary_range
9170 .to_offset(&buffer)
9171 .to_inclusive()
9172 });
9173 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9174 if active_primary_range.contains(&selection.head()) {
9175 *active_primary_range.start()
9176 } else {
9177 selection.head()
9178 }
9179 } else {
9180 selection.head()
9181 };
9182 let snapshot = self.snapshot(cx);
9183 loop {
9184 let diagnostics = if direction == Direction::Prev {
9185 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9186 } else {
9187 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9188 }
9189 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9190 let group = diagnostics
9191 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9192 // be sorted in a stable way
9193 // skip until we are at current active diagnostic, if it exists
9194 .skip_while(|entry| {
9195 (match direction {
9196 Direction::Prev => entry.range.start >= search_start,
9197 Direction::Next => entry.range.start <= search_start,
9198 }) && self
9199 .active_diagnostics
9200 .as_ref()
9201 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9202 })
9203 .find_map(|entry| {
9204 if entry.diagnostic.is_primary
9205 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9206 && !entry.range.is_empty()
9207 // if we match with the active diagnostic, skip it
9208 && Some(entry.diagnostic.group_id)
9209 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9210 {
9211 Some((entry.range, entry.diagnostic.group_id))
9212 } else {
9213 None
9214 }
9215 });
9216
9217 if let Some((primary_range, group_id)) = group {
9218 if self.activate_diagnostics(group_id, cx) {
9219 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9220 s.select(vec![Selection {
9221 id: selection.id,
9222 start: primary_range.start,
9223 end: primary_range.start,
9224 reversed: false,
9225 goal: SelectionGoal::None,
9226 }]);
9227 });
9228 }
9229 break;
9230 } else {
9231 // Cycle around to the start of the buffer, potentially moving back to the start of
9232 // the currently active diagnostic.
9233 active_primary_range.take();
9234 if direction == Direction::Prev {
9235 if search_start == buffer.len() {
9236 break;
9237 } else {
9238 search_start = buffer.len();
9239 }
9240 } else if search_start == 0 {
9241 break;
9242 } else {
9243 search_start = 0;
9244 }
9245 }
9246 }
9247 }
9248
9249 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9250 let snapshot = self
9251 .display_map
9252 .update(cx, |display_map, cx| display_map.snapshot(cx));
9253 let selection = self.selections.newest::<Point>(cx);
9254
9255 if !self.seek_in_direction(
9256 &snapshot,
9257 selection.head(),
9258 false,
9259 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9260 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
9261 ),
9262 cx,
9263 ) {
9264 let wrapped_point = Point::zero();
9265 self.seek_in_direction(
9266 &snapshot,
9267 wrapped_point,
9268 true,
9269 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9270 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9271 ),
9272 cx,
9273 );
9274 }
9275 }
9276
9277 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9278 let snapshot = self
9279 .display_map
9280 .update(cx, |display_map, cx| display_map.snapshot(cx));
9281 let selection = self.selections.newest::<Point>(cx);
9282
9283 if !self.seek_in_direction(
9284 &snapshot,
9285 selection.head(),
9286 false,
9287 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9288 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
9289 ),
9290 cx,
9291 ) {
9292 let wrapped_point = snapshot.buffer_snapshot.max_point();
9293 self.seek_in_direction(
9294 &snapshot,
9295 wrapped_point,
9296 true,
9297 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9298 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9299 ),
9300 cx,
9301 );
9302 }
9303 }
9304
9305 fn seek_in_direction(
9306 &mut self,
9307 snapshot: &DisplaySnapshot,
9308 initial_point: Point,
9309 is_wrapped: bool,
9310 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
9311 cx: &mut ViewContext<Editor>,
9312 ) -> bool {
9313 let display_point = initial_point.to_display_point(snapshot);
9314 let mut hunks = hunks
9315 .map(|hunk| diff_hunk_to_display(&hunk, snapshot))
9316 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9317 .dedup();
9318
9319 if let Some(hunk) = hunks.next() {
9320 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9321 let row = hunk.start_display_row();
9322 let point = DisplayPoint::new(row, 0);
9323 s.select_display_ranges([point..point]);
9324 });
9325
9326 true
9327 } else {
9328 false
9329 }
9330 }
9331
9332 pub fn go_to_definition(
9333 &mut self,
9334 _: &GoToDefinition,
9335 cx: &mut ViewContext<Self>,
9336 ) -> Task<Result<Navigated>> {
9337 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9338 cx.spawn(|editor, mut cx| async move {
9339 if definition.await? == Navigated::Yes {
9340 return Ok(Navigated::Yes);
9341 }
9342 match editor.update(&mut cx, |editor, cx| {
9343 editor.find_all_references(&FindAllReferences, cx)
9344 })? {
9345 Some(references) => references.await,
9346 None => Ok(Navigated::No),
9347 }
9348 })
9349 }
9350
9351 pub fn go_to_declaration(
9352 &mut self,
9353 _: &GoToDeclaration,
9354 cx: &mut ViewContext<Self>,
9355 ) -> Task<Result<Navigated>> {
9356 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9357 }
9358
9359 pub fn go_to_declaration_split(
9360 &mut self,
9361 _: &GoToDeclaration,
9362 cx: &mut ViewContext<Self>,
9363 ) -> Task<Result<Navigated>> {
9364 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9365 }
9366
9367 pub fn go_to_implementation(
9368 &mut self,
9369 _: &GoToImplementation,
9370 cx: &mut ViewContext<Self>,
9371 ) -> Task<Result<Navigated>> {
9372 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9373 }
9374
9375 pub fn go_to_implementation_split(
9376 &mut self,
9377 _: &GoToImplementationSplit,
9378 cx: &mut ViewContext<Self>,
9379 ) -> Task<Result<Navigated>> {
9380 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9381 }
9382
9383 pub fn go_to_type_definition(
9384 &mut self,
9385 _: &GoToTypeDefinition,
9386 cx: &mut ViewContext<Self>,
9387 ) -> Task<Result<Navigated>> {
9388 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9389 }
9390
9391 pub fn go_to_definition_split(
9392 &mut self,
9393 _: &GoToDefinitionSplit,
9394 cx: &mut ViewContext<Self>,
9395 ) -> Task<Result<Navigated>> {
9396 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9397 }
9398
9399 pub fn go_to_type_definition_split(
9400 &mut self,
9401 _: &GoToTypeDefinitionSplit,
9402 cx: &mut ViewContext<Self>,
9403 ) -> Task<Result<Navigated>> {
9404 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9405 }
9406
9407 fn go_to_definition_of_kind(
9408 &mut self,
9409 kind: GotoDefinitionKind,
9410 split: bool,
9411 cx: &mut ViewContext<Self>,
9412 ) -> Task<Result<Navigated>> {
9413 let Some(workspace) = self.workspace() else {
9414 return Task::ready(Ok(Navigated::No));
9415 };
9416 let buffer = self.buffer.read(cx);
9417 let head = self.selections.newest::<usize>(cx).head();
9418 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9419 text_anchor
9420 } else {
9421 return Task::ready(Ok(Navigated::No));
9422 };
9423
9424 let project = workspace.read(cx).project().clone();
9425 let definitions = project.update(cx, |project, cx| match kind {
9426 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9427 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9428 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9429 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9430 });
9431
9432 cx.spawn(|editor, mut cx| async move {
9433 let definitions = definitions.await?;
9434 let navigated = editor
9435 .update(&mut cx, |editor, cx| {
9436 editor.navigate_to_hover_links(
9437 Some(kind),
9438 definitions
9439 .into_iter()
9440 .filter(|location| {
9441 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9442 })
9443 .map(HoverLink::Text)
9444 .collect::<Vec<_>>(),
9445 split,
9446 cx,
9447 )
9448 })?
9449 .await?;
9450 anyhow::Ok(navigated)
9451 })
9452 }
9453
9454 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9455 let position = self.selections.newest_anchor().head();
9456 let Some((buffer, buffer_position)) =
9457 self.buffer.read(cx).text_anchor_for_position(position, cx)
9458 else {
9459 return;
9460 };
9461
9462 cx.spawn(|editor, mut cx| async move {
9463 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9464 editor.update(&mut cx, |_, cx| {
9465 cx.open_url(&url);
9466 })
9467 } else {
9468 Ok(())
9469 }
9470 })
9471 .detach();
9472 }
9473
9474 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9475 let Some(workspace) = self.workspace() else {
9476 return;
9477 };
9478
9479 let position = self.selections.newest_anchor().head();
9480
9481 let Some((buffer, buffer_position)) =
9482 self.buffer.read(cx).text_anchor_for_position(position, cx)
9483 else {
9484 return;
9485 };
9486
9487 let Some(project) = self.project.clone() else {
9488 return;
9489 };
9490
9491 cx.spawn(|_, mut cx| async move {
9492 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9493
9494 if let Some((_, path)) = result {
9495 workspace
9496 .update(&mut cx, |workspace, cx| {
9497 workspace.open_resolved_path(path, cx)
9498 })?
9499 .await?;
9500 }
9501 anyhow::Ok(())
9502 })
9503 .detach();
9504 }
9505
9506 pub(crate) fn navigate_to_hover_links(
9507 &mut self,
9508 kind: Option<GotoDefinitionKind>,
9509 mut definitions: Vec<HoverLink>,
9510 split: bool,
9511 cx: &mut ViewContext<Editor>,
9512 ) -> Task<Result<Navigated>> {
9513 // If there is one definition, just open it directly
9514 if definitions.len() == 1 {
9515 let definition = definitions.pop().unwrap();
9516
9517 enum TargetTaskResult {
9518 Location(Option<Location>),
9519 AlreadyNavigated,
9520 }
9521
9522 let target_task = match definition {
9523 HoverLink::Text(link) => {
9524 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9525 }
9526 HoverLink::InlayHint(lsp_location, server_id) => {
9527 let computation = self.compute_target_location(lsp_location, server_id, cx);
9528 cx.background_executor().spawn(async move {
9529 let location = computation.await?;
9530 Ok(TargetTaskResult::Location(location))
9531 })
9532 }
9533 HoverLink::Url(url) => {
9534 cx.open_url(&url);
9535 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9536 }
9537 HoverLink::File(path) => {
9538 if let Some(workspace) = self.workspace() {
9539 cx.spawn(|_, mut cx| async move {
9540 workspace
9541 .update(&mut cx, |workspace, cx| {
9542 workspace.open_resolved_path(path, cx)
9543 })?
9544 .await
9545 .map(|_| TargetTaskResult::AlreadyNavigated)
9546 })
9547 } else {
9548 Task::ready(Ok(TargetTaskResult::Location(None)))
9549 }
9550 }
9551 };
9552 cx.spawn(|editor, mut cx| async move {
9553 let target = match target_task.await.context("target resolution task")? {
9554 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9555 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9556 TargetTaskResult::Location(Some(target)) => target,
9557 };
9558
9559 editor.update(&mut cx, |editor, cx| {
9560 let Some(workspace) = editor.workspace() else {
9561 return Navigated::No;
9562 };
9563 let pane = workspace.read(cx).active_pane().clone();
9564
9565 let range = target.range.to_offset(target.buffer.read(cx));
9566 let range = editor.range_for_match(&range);
9567
9568 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9569 let buffer = target.buffer.read(cx);
9570 let range = check_multiline_range(buffer, range);
9571 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9572 s.select_ranges([range]);
9573 });
9574 } else {
9575 cx.window_context().defer(move |cx| {
9576 let target_editor: View<Self> =
9577 workspace.update(cx, |workspace, cx| {
9578 let pane = if split {
9579 workspace.adjacent_pane(cx)
9580 } else {
9581 workspace.active_pane().clone()
9582 };
9583
9584 workspace.open_project_item(
9585 pane,
9586 target.buffer.clone(),
9587 true,
9588 true,
9589 cx,
9590 )
9591 });
9592 target_editor.update(cx, |target_editor, cx| {
9593 // When selecting a definition in a different buffer, disable the nav history
9594 // to avoid creating a history entry at the previous cursor location.
9595 pane.update(cx, |pane, _| pane.disable_history());
9596 let buffer = target.buffer.read(cx);
9597 let range = check_multiline_range(buffer, range);
9598 target_editor.change_selections(
9599 Some(Autoscroll::focused()),
9600 cx,
9601 |s| {
9602 s.select_ranges([range]);
9603 },
9604 );
9605 pane.update(cx, |pane, _| pane.enable_history());
9606 });
9607 });
9608 }
9609 Navigated::Yes
9610 })
9611 })
9612 } else if !definitions.is_empty() {
9613 let replica_id = self.replica_id(cx);
9614 cx.spawn(|editor, mut cx| async move {
9615 let (title, location_tasks, workspace) = editor
9616 .update(&mut cx, |editor, cx| {
9617 let tab_kind = match kind {
9618 Some(GotoDefinitionKind::Implementation) => "Implementations",
9619 _ => "Definitions",
9620 };
9621 let title = definitions
9622 .iter()
9623 .find_map(|definition| match definition {
9624 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9625 let buffer = origin.buffer.read(cx);
9626 format!(
9627 "{} for {}",
9628 tab_kind,
9629 buffer
9630 .text_for_range(origin.range.clone())
9631 .collect::<String>()
9632 )
9633 }),
9634 HoverLink::InlayHint(_, _) => None,
9635 HoverLink::Url(_) => None,
9636 HoverLink::File(_) => None,
9637 })
9638 .unwrap_or(tab_kind.to_string());
9639 let location_tasks = definitions
9640 .into_iter()
9641 .map(|definition| match definition {
9642 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9643 HoverLink::InlayHint(lsp_location, server_id) => {
9644 editor.compute_target_location(lsp_location, server_id, cx)
9645 }
9646 HoverLink::Url(_) => Task::ready(Ok(None)),
9647 HoverLink::File(_) => Task::ready(Ok(None)),
9648 })
9649 .collect::<Vec<_>>();
9650 (title, location_tasks, editor.workspace().clone())
9651 })
9652 .context("location tasks preparation")?;
9653
9654 let locations = futures::future::join_all(location_tasks)
9655 .await
9656 .into_iter()
9657 .filter_map(|location| location.transpose())
9658 .collect::<Result<_>>()
9659 .context("location tasks")?;
9660
9661 let Some(workspace) = workspace else {
9662 return Ok(Navigated::No);
9663 };
9664 let opened = workspace
9665 .update(&mut cx, |workspace, cx| {
9666 Self::open_locations_in_multibuffer(
9667 workspace, locations, replica_id, title, split, cx,
9668 )
9669 })
9670 .ok();
9671
9672 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9673 })
9674 } else {
9675 Task::ready(Ok(Navigated::No))
9676 }
9677 }
9678
9679 fn compute_target_location(
9680 &self,
9681 lsp_location: lsp::Location,
9682 server_id: LanguageServerId,
9683 cx: &mut ViewContext<Editor>,
9684 ) -> Task<anyhow::Result<Option<Location>>> {
9685 let Some(project) = self.project.clone() else {
9686 return Task::Ready(Some(Ok(None)));
9687 };
9688
9689 cx.spawn(move |editor, mut cx| async move {
9690 let location_task = editor.update(&mut cx, |editor, cx| {
9691 project.update(cx, |project, cx| {
9692 let language_server_name =
9693 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9694 project
9695 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9696 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9697 });
9698 language_server_name.map(|language_server_name| {
9699 project.open_local_buffer_via_lsp(
9700 lsp_location.uri.clone(),
9701 server_id,
9702 language_server_name,
9703 cx,
9704 )
9705 })
9706 })
9707 })?;
9708 let location = match location_task {
9709 Some(task) => Some({
9710 let target_buffer_handle = task.await.context("open local buffer")?;
9711 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9712 let target_start = target_buffer
9713 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9714 let target_end = target_buffer
9715 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9716 target_buffer.anchor_after(target_start)
9717 ..target_buffer.anchor_before(target_end)
9718 })?;
9719 Location {
9720 buffer: target_buffer_handle,
9721 range,
9722 }
9723 }),
9724 None => None,
9725 };
9726 Ok(location)
9727 })
9728 }
9729
9730 pub fn find_all_references(
9731 &mut self,
9732 _: &FindAllReferences,
9733 cx: &mut ViewContext<Self>,
9734 ) -> Option<Task<Result<Navigated>>> {
9735 let multi_buffer = self.buffer.read(cx);
9736 let selection = self.selections.newest::<usize>(cx);
9737 let head = selection.head();
9738
9739 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9740 let head_anchor = multi_buffer_snapshot.anchor_at(
9741 head,
9742 if head < selection.tail() {
9743 Bias::Right
9744 } else {
9745 Bias::Left
9746 },
9747 );
9748
9749 match self
9750 .find_all_references_task_sources
9751 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9752 {
9753 Ok(_) => {
9754 log::info!(
9755 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9756 );
9757 return None;
9758 }
9759 Err(i) => {
9760 self.find_all_references_task_sources.insert(i, head_anchor);
9761 }
9762 }
9763
9764 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9765 let replica_id = self.replica_id(cx);
9766 let workspace = self.workspace()?;
9767 let project = workspace.read(cx).project().clone();
9768 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9769 Some(cx.spawn(|editor, mut cx| async move {
9770 let _cleanup = defer({
9771 let mut cx = cx.clone();
9772 move || {
9773 let _ = editor.update(&mut cx, |editor, _| {
9774 if let Ok(i) =
9775 editor
9776 .find_all_references_task_sources
9777 .binary_search_by(|anchor| {
9778 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9779 })
9780 {
9781 editor.find_all_references_task_sources.remove(i);
9782 }
9783 });
9784 }
9785 });
9786
9787 let locations = references.await?;
9788 if locations.is_empty() {
9789 return anyhow::Ok(Navigated::No);
9790 }
9791
9792 workspace.update(&mut cx, |workspace, cx| {
9793 let title = locations
9794 .first()
9795 .as_ref()
9796 .map(|location| {
9797 let buffer = location.buffer.read(cx);
9798 format!(
9799 "References to `{}`",
9800 buffer
9801 .text_for_range(location.range.clone())
9802 .collect::<String>()
9803 )
9804 })
9805 .unwrap();
9806 Self::open_locations_in_multibuffer(
9807 workspace, locations, replica_id, title, false, cx,
9808 );
9809 Navigated::Yes
9810 })
9811 }))
9812 }
9813
9814 /// Opens a multibuffer with the given project locations in it
9815 pub fn open_locations_in_multibuffer(
9816 workspace: &mut Workspace,
9817 mut locations: Vec<Location>,
9818 replica_id: ReplicaId,
9819 title: String,
9820 split: bool,
9821 cx: &mut ViewContext<Workspace>,
9822 ) {
9823 // If there are multiple definitions, open them in a multibuffer
9824 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9825 let mut locations = locations.into_iter().peekable();
9826 let mut ranges_to_highlight = Vec::new();
9827 let capability = workspace.project().read(cx).capability();
9828
9829 let excerpt_buffer = cx.new_model(|cx| {
9830 let mut multibuffer = MultiBuffer::new(replica_id, capability);
9831 while let Some(location) = locations.next() {
9832 let buffer = location.buffer.read(cx);
9833 let mut ranges_for_buffer = Vec::new();
9834 let range = location.range.to_offset(buffer);
9835 ranges_for_buffer.push(range.clone());
9836
9837 while let Some(next_location) = locations.peek() {
9838 if next_location.buffer == location.buffer {
9839 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9840 locations.next();
9841 } else {
9842 break;
9843 }
9844 }
9845
9846 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9847 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9848 location.buffer.clone(),
9849 ranges_for_buffer,
9850 DEFAULT_MULTIBUFFER_CONTEXT,
9851 cx,
9852 ))
9853 }
9854
9855 multibuffer.with_title(title)
9856 });
9857
9858 let editor = cx.new_view(|cx| {
9859 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9860 });
9861 editor.update(cx, |editor, cx| {
9862 if let Some(first_range) = ranges_to_highlight.first() {
9863 editor.change_selections(None, cx, |selections| {
9864 selections.clear_disjoint();
9865 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9866 });
9867 }
9868 editor.highlight_background::<Self>(
9869 &ranges_to_highlight,
9870 |theme| theme.editor_highlighted_line_background,
9871 cx,
9872 );
9873 });
9874
9875 let item = Box::new(editor);
9876 let item_id = item.item_id();
9877
9878 if split {
9879 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9880 } else {
9881 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9882 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9883 pane.close_current_preview_item(cx)
9884 } else {
9885 None
9886 }
9887 });
9888 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9889 }
9890 workspace.active_pane().update(cx, |pane, cx| {
9891 pane.set_preview_item_id(Some(item_id), cx);
9892 });
9893 }
9894
9895 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9896 use language::ToOffset as _;
9897
9898 let project = self.project.clone()?;
9899 let selection = self.selections.newest_anchor().clone();
9900 let (cursor_buffer, cursor_buffer_position) = self
9901 .buffer
9902 .read(cx)
9903 .text_anchor_for_position(selection.head(), cx)?;
9904 let (tail_buffer, cursor_buffer_position_end) = self
9905 .buffer
9906 .read(cx)
9907 .text_anchor_for_position(selection.tail(), cx)?;
9908 if tail_buffer != cursor_buffer {
9909 return None;
9910 }
9911
9912 let snapshot = cursor_buffer.read(cx).snapshot();
9913 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9914 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9915 let prepare_rename = project.update(cx, |project, cx| {
9916 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9917 });
9918 drop(snapshot);
9919
9920 Some(cx.spawn(|this, mut cx| async move {
9921 let rename_range = if let Some(range) = prepare_rename.await? {
9922 Some(range)
9923 } else {
9924 this.update(&mut cx, |this, cx| {
9925 let buffer = this.buffer.read(cx).snapshot(cx);
9926 let mut buffer_highlights = this
9927 .document_highlights_for_position(selection.head(), &buffer)
9928 .filter(|highlight| {
9929 highlight.start.excerpt_id == selection.head().excerpt_id
9930 && highlight.end.excerpt_id == selection.head().excerpt_id
9931 });
9932 buffer_highlights
9933 .next()
9934 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9935 })?
9936 };
9937 if let Some(rename_range) = rename_range {
9938 this.update(&mut cx, |this, cx| {
9939 let snapshot = cursor_buffer.read(cx).snapshot();
9940 let rename_buffer_range = rename_range.to_offset(&snapshot);
9941 let cursor_offset_in_rename_range =
9942 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9943 let cursor_offset_in_rename_range_end =
9944 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9945
9946 this.take_rename(false, cx);
9947 let buffer = this.buffer.read(cx).read(cx);
9948 let cursor_offset = selection.head().to_offset(&buffer);
9949 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9950 let rename_end = rename_start + rename_buffer_range.len();
9951 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9952 let mut old_highlight_id = None;
9953 let old_name: Arc<str> = buffer
9954 .chunks(rename_start..rename_end, true)
9955 .map(|chunk| {
9956 if old_highlight_id.is_none() {
9957 old_highlight_id = chunk.syntax_highlight_id;
9958 }
9959 chunk.text
9960 })
9961 .collect::<String>()
9962 .into();
9963
9964 drop(buffer);
9965
9966 // Position the selection in the rename editor so that it matches the current selection.
9967 this.show_local_selections = false;
9968 let rename_editor = cx.new_view(|cx| {
9969 let mut editor = Editor::single_line(cx);
9970 editor.buffer.update(cx, |buffer, cx| {
9971 buffer.edit([(0..0, old_name.clone())], None, cx)
9972 });
9973 let rename_selection_range = match cursor_offset_in_rename_range
9974 .cmp(&cursor_offset_in_rename_range_end)
9975 {
9976 Ordering::Equal => {
9977 editor.select_all(&SelectAll, cx);
9978 return editor;
9979 }
9980 Ordering::Less => {
9981 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
9982 }
9983 Ordering::Greater => {
9984 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
9985 }
9986 };
9987 if rename_selection_range.end > old_name.len() {
9988 editor.select_all(&SelectAll, cx);
9989 } else {
9990 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9991 s.select_ranges([rename_selection_range]);
9992 });
9993 }
9994 editor
9995 });
9996 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
9997 if e == &EditorEvent::Focused {
9998 cx.emit(EditorEvent::FocusedIn)
9999 }
10000 })
10001 .detach();
10002
10003 let write_highlights =
10004 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10005 let read_highlights =
10006 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10007 let ranges = write_highlights
10008 .iter()
10009 .flat_map(|(_, ranges)| ranges.iter())
10010 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10011 .cloned()
10012 .collect();
10013
10014 this.highlight_text::<Rename>(
10015 ranges,
10016 HighlightStyle {
10017 fade_out: Some(0.6),
10018 ..Default::default()
10019 },
10020 cx,
10021 );
10022 let rename_focus_handle = rename_editor.focus_handle(cx);
10023 cx.focus(&rename_focus_handle);
10024 let block_id = this.insert_blocks(
10025 [BlockProperties {
10026 style: BlockStyle::Flex,
10027 position: range.start,
10028 height: 1,
10029 render: Box::new({
10030 let rename_editor = rename_editor.clone();
10031 move |cx: &mut BlockContext| {
10032 let mut text_style = cx.editor_style.text.clone();
10033 if let Some(highlight_style) = old_highlight_id
10034 .and_then(|h| h.style(&cx.editor_style.syntax))
10035 {
10036 text_style = text_style.highlight(highlight_style);
10037 }
10038 div()
10039 .pl(cx.anchor_x)
10040 .child(EditorElement::new(
10041 &rename_editor,
10042 EditorStyle {
10043 background: cx.theme().system().transparent,
10044 local_player: cx.editor_style.local_player,
10045 text: text_style,
10046 scrollbar_width: cx.editor_style.scrollbar_width,
10047 syntax: cx.editor_style.syntax.clone(),
10048 status: cx.editor_style.status.clone(),
10049 inlay_hints_style: HighlightStyle {
10050 font_weight: Some(FontWeight::BOLD),
10051 ..make_inlay_hints_style(cx)
10052 },
10053 suggestions_style: HighlightStyle {
10054 color: Some(cx.theme().status().predictive),
10055 ..HighlightStyle::default()
10056 },
10057 ..EditorStyle::default()
10058 },
10059 ))
10060 .into_any_element()
10061 }
10062 }),
10063 disposition: BlockDisposition::Below,
10064 priority: 0,
10065 }],
10066 Some(Autoscroll::fit()),
10067 cx,
10068 )[0];
10069 this.pending_rename = Some(RenameState {
10070 range,
10071 old_name,
10072 editor: rename_editor,
10073 block_id,
10074 });
10075 })?;
10076 }
10077
10078 Ok(())
10079 }))
10080 }
10081
10082 pub fn confirm_rename(
10083 &mut self,
10084 _: &ConfirmRename,
10085 cx: &mut ViewContext<Self>,
10086 ) -> Option<Task<Result<()>>> {
10087 let rename = self.take_rename(false, cx)?;
10088 let workspace = self.workspace()?;
10089 let (start_buffer, start) = self
10090 .buffer
10091 .read(cx)
10092 .text_anchor_for_position(rename.range.start, cx)?;
10093 let (end_buffer, end) = self
10094 .buffer
10095 .read(cx)
10096 .text_anchor_for_position(rename.range.end, cx)?;
10097 if start_buffer != end_buffer {
10098 return None;
10099 }
10100
10101 let buffer = start_buffer;
10102 let range = start..end;
10103 let old_name = rename.old_name;
10104 let new_name = rename.editor.read(cx).text(cx);
10105
10106 let rename = workspace
10107 .read(cx)
10108 .project()
10109 .clone()
10110 .update(cx, |project, cx| {
10111 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10112 });
10113 let workspace = workspace.downgrade();
10114
10115 Some(cx.spawn(|editor, mut cx| async move {
10116 let project_transaction = rename.await?;
10117 Self::open_project_transaction(
10118 &editor,
10119 workspace,
10120 project_transaction,
10121 format!("Rename: {} → {}", old_name, new_name),
10122 cx.clone(),
10123 )
10124 .await?;
10125
10126 editor.update(&mut cx, |editor, cx| {
10127 editor.refresh_document_highlights(cx);
10128 })?;
10129 Ok(())
10130 }))
10131 }
10132
10133 fn take_rename(
10134 &mut self,
10135 moving_cursor: bool,
10136 cx: &mut ViewContext<Self>,
10137 ) -> Option<RenameState> {
10138 let rename = self.pending_rename.take()?;
10139 if rename.editor.focus_handle(cx).is_focused(cx) {
10140 cx.focus(&self.focus_handle);
10141 }
10142
10143 self.remove_blocks(
10144 [rename.block_id].into_iter().collect(),
10145 Some(Autoscroll::fit()),
10146 cx,
10147 );
10148 self.clear_highlights::<Rename>(cx);
10149 self.show_local_selections = true;
10150
10151 if moving_cursor {
10152 let rename_editor = rename.editor.read(cx);
10153 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10154
10155 // Update the selection to match the position of the selection inside
10156 // the rename editor.
10157 let snapshot = self.buffer.read(cx).read(cx);
10158 let rename_range = rename.range.to_offset(&snapshot);
10159 let cursor_in_editor = snapshot
10160 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10161 .min(rename_range.end);
10162 drop(snapshot);
10163
10164 self.change_selections(None, cx, |s| {
10165 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10166 });
10167 } else {
10168 self.refresh_document_highlights(cx);
10169 }
10170
10171 Some(rename)
10172 }
10173
10174 pub fn pending_rename(&self) -> Option<&RenameState> {
10175 self.pending_rename.as_ref()
10176 }
10177
10178 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10179 let project = match &self.project {
10180 Some(project) => project.clone(),
10181 None => return None,
10182 };
10183
10184 Some(self.perform_format(project, FormatTrigger::Manual, cx))
10185 }
10186
10187 fn perform_format(
10188 &mut self,
10189 project: Model<Project>,
10190 trigger: FormatTrigger,
10191 cx: &mut ViewContext<Self>,
10192 ) -> Task<Result<()>> {
10193 let buffer = self.buffer().clone();
10194 let mut buffers = buffer.read(cx).all_buffers();
10195 if trigger == FormatTrigger::Save {
10196 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10197 }
10198
10199 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10200 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10201
10202 cx.spawn(|_, mut cx| async move {
10203 let transaction = futures::select_biased! {
10204 () = timeout => {
10205 log::warn!("timed out waiting for formatting");
10206 None
10207 }
10208 transaction = format.log_err().fuse() => transaction,
10209 };
10210
10211 buffer
10212 .update(&mut cx, |buffer, cx| {
10213 if let Some(transaction) = transaction {
10214 if !buffer.is_singleton() {
10215 buffer.push_transaction(&transaction.0, cx);
10216 }
10217 }
10218
10219 cx.notify();
10220 })
10221 .ok();
10222
10223 Ok(())
10224 })
10225 }
10226
10227 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10228 if let Some(project) = self.project.clone() {
10229 self.buffer.update(cx, |multi_buffer, cx| {
10230 project.update(cx, |project, cx| {
10231 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10232 });
10233 })
10234 }
10235 }
10236
10237 fn cancel_language_server_work(
10238 &mut self,
10239 _: &CancelLanguageServerWork,
10240 cx: &mut ViewContext<Self>,
10241 ) {
10242 if let Some(project) = self.project.clone() {
10243 self.buffer.update(cx, |multi_buffer, cx| {
10244 project.update(cx, |project, cx| {
10245 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10246 });
10247 })
10248 }
10249 }
10250
10251 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10252 cx.show_character_palette();
10253 }
10254
10255 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10256 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10257 let buffer = self.buffer.read(cx).snapshot(cx);
10258 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10259 let is_valid = buffer
10260 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10261 .any(|entry| {
10262 entry.diagnostic.is_primary
10263 && !entry.range.is_empty()
10264 && entry.range.start == primary_range_start
10265 && entry.diagnostic.message == active_diagnostics.primary_message
10266 });
10267
10268 if is_valid != active_diagnostics.is_valid {
10269 active_diagnostics.is_valid = is_valid;
10270 let mut new_styles = HashMap::default();
10271 for (block_id, diagnostic) in &active_diagnostics.blocks {
10272 new_styles.insert(
10273 *block_id,
10274 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10275 );
10276 }
10277 self.display_map.update(cx, |display_map, _cx| {
10278 display_map.replace_blocks(new_styles)
10279 });
10280 }
10281 }
10282 }
10283
10284 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10285 self.dismiss_diagnostics(cx);
10286 let snapshot = self.snapshot(cx);
10287 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10288 let buffer = self.buffer.read(cx).snapshot(cx);
10289
10290 let mut primary_range = None;
10291 let mut primary_message = None;
10292 let mut group_end = Point::zero();
10293 let diagnostic_group = buffer
10294 .diagnostic_group::<MultiBufferPoint>(group_id)
10295 .filter_map(|entry| {
10296 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10297 && (entry.range.start.row == entry.range.end.row
10298 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10299 {
10300 return None;
10301 }
10302 if entry.range.end > group_end {
10303 group_end = entry.range.end;
10304 }
10305 if entry.diagnostic.is_primary {
10306 primary_range = Some(entry.range.clone());
10307 primary_message = Some(entry.diagnostic.message.clone());
10308 }
10309 Some(entry)
10310 })
10311 .collect::<Vec<_>>();
10312 let primary_range = primary_range?;
10313 let primary_message = primary_message?;
10314 let primary_range =
10315 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10316
10317 let blocks = display_map
10318 .insert_blocks(
10319 diagnostic_group.iter().map(|entry| {
10320 let diagnostic = entry.diagnostic.clone();
10321 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10322 BlockProperties {
10323 style: BlockStyle::Fixed,
10324 position: buffer.anchor_after(entry.range.start),
10325 height: message_height,
10326 render: diagnostic_block_renderer(diagnostic, None, true, true),
10327 disposition: BlockDisposition::Below,
10328 priority: 0,
10329 }
10330 }),
10331 cx,
10332 )
10333 .into_iter()
10334 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10335 .collect();
10336
10337 Some(ActiveDiagnosticGroup {
10338 primary_range,
10339 primary_message,
10340 group_id,
10341 blocks,
10342 is_valid: true,
10343 })
10344 });
10345 self.active_diagnostics.is_some()
10346 }
10347
10348 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10349 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10350 self.display_map.update(cx, |display_map, cx| {
10351 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10352 });
10353 cx.notify();
10354 }
10355 }
10356
10357 pub fn set_selections_from_remote(
10358 &mut self,
10359 selections: Vec<Selection<Anchor>>,
10360 pending_selection: Option<Selection<Anchor>>,
10361 cx: &mut ViewContext<Self>,
10362 ) {
10363 let old_cursor_position = self.selections.newest_anchor().head();
10364 self.selections.change_with(cx, |s| {
10365 s.select_anchors(selections);
10366 if let Some(pending_selection) = pending_selection {
10367 s.set_pending(pending_selection, SelectMode::Character);
10368 } else {
10369 s.clear_pending();
10370 }
10371 });
10372 self.selections_did_change(false, &old_cursor_position, true, cx);
10373 }
10374
10375 fn push_to_selection_history(&mut self) {
10376 self.selection_history.push(SelectionHistoryEntry {
10377 selections: self.selections.disjoint_anchors(),
10378 select_next_state: self.select_next_state.clone(),
10379 select_prev_state: self.select_prev_state.clone(),
10380 add_selections_state: self.add_selections_state.clone(),
10381 });
10382 }
10383
10384 pub fn transact(
10385 &mut self,
10386 cx: &mut ViewContext<Self>,
10387 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10388 ) -> Option<TransactionId> {
10389 self.start_transaction_at(Instant::now(), cx);
10390 update(self, cx);
10391 self.end_transaction_at(Instant::now(), cx)
10392 }
10393
10394 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10395 self.end_selection(cx);
10396 if let Some(tx_id) = self
10397 .buffer
10398 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10399 {
10400 self.selection_history
10401 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10402 cx.emit(EditorEvent::TransactionBegun {
10403 transaction_id: tx_id,
10404 })
10405 }
10406 }
10407
10408 fn end_transaction_at(
10409 &mut self,
10410 now: Instant,
10411 cx: &mut ViewContext<Self>,
10412 ) -> Option<TransactionId> {
10413 if let Some(transaction_id) = self
10414 .buffer
10415 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10416 {
10417 if let Some((_, end_selections)) =
10418 self.selection_history.transaction_mut(transaction_id)
10419 {
10420 *end_selections = Some(self.selections.disjoint_anchors());
10421 } else {
10422 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10423 }
10424
10425 cx.emit(EditorEvent::Edited { transaction_id });
10426 Some(transaction_id)
10427 } else {
10428 None
10429 }
10430 }
10431
10432 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10433 let mut fold_ranges = Vec::new();
10434
10435 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10436
10437 let selections = self.selections.all_adjusted(cx);
10438 for selection in selections {
10439 let range = selection.range().sorted();
10440 let buffer_start_row = range.start.row;
10441
10442 for row in (0..=range.end.row).rev() {
10443 if let Some((foldable_range, fold_text)) =
10444 display_map.foldable_range(MultiBufferRow(row))
10445 {
10446 if foldable_range.end.row >= buffer_start_row {
10447 fold_ranges.push((foldable_range, fold_text));
10448 if row <= range.start.row {
10449 break;
10450 }
10451 }
10452 }
10453 }
10454 }
10455
10456 self.fold_ranges(fold_ranges, true, cx);
10457 }
10458
10459 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10460 let buffer_row = fold_at.buffer_row;
10461 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10462
10463 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10464 let autoscroll = self
10465 .selections
10466 .all::<Point>(cx)
10467 .iter()
10468 .any(|selection| fold_range.overlaps(&selection.range()));
10469
10470 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10471 }
10472 }
10473
10474 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10475 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10476 let buffer = &display_map.buffer_snapshot;
10477 let selections = self.selections.all::<Point>(cx);
10478 let ranges = selections
10479 .iter()
10480 .map(|s| {
10481 let range = s.display_range(&display_map).sorted();
10482 let mut start = range.start.to_point(&display_map);
10483 let mut end = range.end.to_point(&display_map);
10484 start.column = 0;
10485 end.column = buffer.line_len(MultiBufferRow(end.row));
10486 start..end
10487 })
10488 .collect::<Vec<_>>();
10489
10490 self.unfold_ranges(ranges, true, true, cx);
10491 }
10492
10493 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10494 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10495
10496 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10497 ..Point::new(
10498 unfold_at.buffer_row.0,
10499 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10500 );
10501
10502 let autoscroll = self
10503 .selections
10504 .all::<Point>(cx)
10505 .iter()
10506 .any(|selection| selection.range().overlaps(&intersection_range));
10507
10508 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10509 }
10510
10511 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10512 let selections = self.selections.all::<Point>(cx);
10513 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10514 let line_mode = self.selections.line_mode;
10515 let ranges = selections.into_iter().map(|s| {
10516 if line_mode {
10517 let start = Point::new(s.start.row, 0);
10518 let end = Point::new(
10519 s.end.row,
10520 display_map
10521 .buffer_snapshot
10522 .line_len(MultiBufferRow(s.end.row)),
10523 );
10524 (start..end, display_map.fold_placeholder.clone())
10525 } else {
10526 (s.start..s.end, display_map.fold_placeholder.clone())
10527 }
10528 });
10529 self.fold_ranges(ranges, true, cx);
10530 }
10531
10532 pub fn fold_ranges<T: ToOffset + Clone>(
10533 &mut self,
10534 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10535 auto_scroll: bool,
10536 cx: &mut ViewContext<Self>,
10537 ) {
10538 let mut fold_ranges = Vec::new();
10539 let mut buffers_affected = HashMap::default();
10540 let multi_buffer = self.buffer().read(cx);
10541 for (fold_range, fold_text) in ranges {
10542 if let Some((_, buffer, _)) =
10543 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10544 {
10545 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10546 };
10547 fold_ranges.push((fold_range, fold_text));
10548 }
10549
10550 let mut ranges = fold_ranges.into_iter().peekable();
10551 if ranges.peek().is_some() {
10552 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10553
10554 if auto_scroll {
10555 self.request_autoscroll(Autoscroll::fit(), cx);
10556 }
10557
10558 for buffer in buffers_affected.into_values() {
10559 self.sync_expanded_diff_hunks(buffer, cx);
10560 }
10561
10562 cx.notify();
10563
10564 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10565 // Clear diagnostics block when folding a range that contains it.
10566 let snapshot = self.snapshot(cx);
10567 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10568 drop(snapshot);
10569 self.active_diagnostics = Some(active_diagnostics);
10570 self.dismiss_diagnostics(cx);
10571 } else {
10572 self.active_diagnostics = Some(active_diagnostics);
10573 }
10574 }
10575
10576 self.scrollbar_marker_state.dirty = true;
10577 }
10578 }
10579
10580 pub fn unfold_ranges<T: ToOffset + Clone>(
10581 &mut self,
10582 ranges: impl IntoIterator<Item = Range<T>>,
10583 inclusive: bool,
10584 auto_scroll: bool,
10585 cx: &mut ViewContext<Self>,
10586 ) {
10587 let mut unfold_ranges = Vec::new();
10588 let mut buffers_affected = HashMap::default();
10589 let multi_buffer = self.buffer().read(cx);
10590 for range in ranges {
10591 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10592 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10593 };
10594 unfold_ranges.push(range);
10595 }
10596
10597 let mut ranges = unfold_ranges.into_iter().peekable();
10598 if ranges.peek().is_some() {
10599 self.display_map
10600 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10601 if auto_scroll {
10602 self.request_autoscroll(Autoscroll::fit(), cx);
10603 }
10604
10605 for buffer in buffers_affected.into_values() {
10606 self.sync_expanded_diff_hunks(buffer, cx);
10607 }
10608
10609 cx.notify();
10610 self.scrollbar_marker_state.dirty = true;
10611 self.active_indent_guides_state.dirty = true;
10612 }
10613 }
10614
10615 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10616 self.display_map.read(cx).fold_placeholder.clone()
10617 }
10618
10619 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10620 if hovered != self.gutter_hovered {
10621 self.gutter_hovered = hovered;
10622 cx.notify();
10623 }
10624 }
10625
10626 pub fn insert_blocks(
10627 &mut self,
10628 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10629 autoscroll: Option<Autoscroll>,
10630 cx: &mut ViewContext<Self>,
10631 ) -> Vec<CustomBlockId> {
10632 let blocks = self
10633 .display_map
10634 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10635 if let Some(autoscroll) = autoscroll {
10636 self.request_autoscroll(autoscroll, cx);
10637 }
10638 cx.notify();
10639 blocks
10640 }
10641
10642 pub fn resize_blocks(
10643 &mut self,
10644 heights: HashMap<CustomBlockId, u32>,
10645 autoscroll: Option<Autoscroll>,
10646 cx: &mut ViewContext<Self>,
10647 ) {
10648 self.display_map
10649 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10650 if let Some(autoscroll) = autoscroll {
10651 self.request_autoscroll(autoscroll, cx);
10652 }
10653 cx.notify();
10654 }
10655
10656 pub fn replace_blocks(
10657 &mut self,
10658 renderers: HashMap<CustomBlockId, RenderBlock>,
10659 autoscroll: Option<Autoscroll>,
10660 cx: &mut ViewContext<Self>,
10661 ) {
10662 self.display_map
10663 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10664 if let Some(autoscroll) = autoscroll {
10665 self.request_autoscroll(autoscroll, cx);
10666 }
10667 cx.notify();
10668 }
10669
10670 pub fn remove_blocks(
10671 &mut self,
10672 block_ids: HashSet<CustomBlockId>,
10673 autoscroll: Option<Autoscroll>,
10674 cx: &mut ViewContext<Self>,
10675 ) {
10676 self.display_map.update(cx, |display_map, cx| {
10677 display_map.remove_blocks(block_ids, cx)
10678 });
10679 if let Some(autoscroll) = autoscroll {
10680 self.request_autoscroll(autoscroll, cx);
10681 }
10682 cx.notify();
10683 }
10684
10685 pub fn row_for_block(
10686 &self,
10687 block_id: CustomBlockId,
10688 cx: &mut ViewContext<Self>,
10689 ) -> Option<DisplayRow> {
10690 self.display_map
10691 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10692 }
10693
10694 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10695 self.focused_block = Some(focused_block);
10696 }
10697
10698 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10699 self.focused_block.take()
10700 }
10701
10702 pub fn insert_creases(
10703 &mut self,
10704 creases: impl IntoIterator<Item = Crease>,
10705 cx: &mut ViewContext<Self>,
10706 ) -> Vec<CreaseId> {
10707 self.display_map
10708 .update(cx, |map, cx| map.insert_creases(creases, cx))
10709 }
10710
10711 pub fn remove_creases(
10712 &mut self,
10713 ids: impl IntoIterator<Item = CreaseId>,
10714 cx: &mut ViewContext<Self>,
10715 ) {
10716 self.display_map
10717 .update(cx, |map, cx| map.remove_creases(ids, cx));
10718 }
10719
10720 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10721 self.display_map
10722 .update(cx, |map, cx| map.snapshot(cx))
10723 .longest_row()
10724 }
10725
10726 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10727 self.display_map
10728 .update(cx, |map, cx| map.snapshot(cx))
10729 .max_point()
10730 }
10731
10732 pub fn text(&self, cx: &AppContext) -> String {
10733 self.buffer.read(cx).read(cx).text()
10734 }
10735
10736 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10737 let text = self.text(cx);
10738 let text = text.trim();
10739
10740 if text.is_empty() {
10741 return None;
10742 }
10743
10744 Some(text.to_string())
10745 }
10746
10747 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10748 self.transact(cx, |this, cx| {
10749 this.buffer
10750 .read(cx)
10751 .as_singleton()
10752 .expect("you can only call set_text on editors for singleton buffers")
10753 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10754 });
10755 }
10756
10757 pub fn display_text(&self, cx: &mut AppContext) -> String {
10758 self.display_map
10759 .update(cx, |map, cx| map.snapshot(cx))
10760 .text()
10761 }
10762
10763 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10764 let mut wrap_guides = smallvec::smallvec![];
10765
10766 if self.show_wrap_guides == Some(false) {
10767 return wrap_guides;
10768 }
10769
10770 let settings = self.buffer.read(cx).settings_at(0, cx);
10771 if settings.show_wrap_guides {
10772 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10773 wrap_guides.push((soft_wrap as usize, true));
10774 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10775 wrap_guides.push((soft_wrap as usize, true));
10776 }
10777 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10778 }
10779
10780 wrap_guides
10781 }
10782
10783 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10784 let settings = self.buffer.read(cx).settings_at(0, cx);
10785 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10786 match mode {
10787 language_settings::SoftWrap::None => SoftWrap::None,
10788 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10789 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10790 language_settings::SoftWrap::PreferredLineLength => {
10791 SoftWrap::Column(settings.preferred_line_length)
10792 }
10793 language_settings::SoftWrap::Bounded => {
10794 SoftWrap::Bounded(settings.preferred_line_length)
10795 }
10796 }
10797 }
10798
10799 pub fn set_soft_wrap_mode(
10800 &mut self,
10801 mode: language_settings::SoftWrap,
10802 cx: &mut ViewContext<Self>,
10803 ) {
10804 self.soft_wrap_mode_override = Some(mode);
10805 cx.notify();
10806 }
10807
10808 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10809 let rem_size = cx.rem_size();
10810 self.display_map.update(cx, |map, cx| {
10811 map.set_font(
10812 style.text.font(),
10813 style.text.font_size.to_pixels(rem_size),
10814 cx,
10815 )
10816 });
10817 self.style = Some(style);
10818 }
10819
10820 pub fn style(&self) -> Option<&EditorStyle> {
10821 self.style.as_ref()
10822 }
10823
10824 // Called by the element. This method is not designed to be called outside of the editor
10825 // element's layout code because it does not notify when rewrapping is computed synchronously.
10826 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10827 self.display_map
10828 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10829 }
10830
10831 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10832 if self.soft_wrap_mode_override.is_some() {
10833 self.soft_wrap_mode_override.take();
10834 } else {
10835 let soft_wrap = match self.soft_wrap_mode(cx) {
10836 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10837 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10838 language_settings::SoftWrap::PreferLine
10839 }
10840 };
10841 self.soft_wrap_mode_override = Some(soft_wrap);
10842 }
10843 cx.notify();
10844 }
10845
10846 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10847 let Some(workspace) = self.workspace() else {
10848 return;
10849 };
10850 let fs = workspace.read(cx).app_state().fs.clone();
10851 let current_show = TabBarSettings::get_global(cx).show;
10852 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10853 setting.show = Some(!current_show);
10854 });
10855 }
10856
10857 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10858 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10859 self.buffer
10860 .read(cx)
10861 .settings_at(0, cx)
10862 .indent_guides
10863 .enabled
10864 });
10865 self.show_indent_guides = Some(!currently_enabled);
10866 cx.notify();
10867 }
10868
10869 fn should_show_indent_guides(&self) -> Option<bool> {
10870 self.show_indent_guides
10871 }
10872
10873 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10874 let mut editor_settings = EditorSettings::get_global(cx).clone();
10875 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10876 EditorSettings::override_global(editor_settings, cx);
10877 }
10878
10879 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10880 self.use_relative_line_numbers
10881 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10882 }
10883
10884 pub fn toggle_relative_line_numbers(
10885 &mut self,
10886 _: &ToggleRelativeLineNumbers,
10887 cx: &mut ViewContext<Self>,
10888 ) {
10889 let is_relative = self.should_use_relative_line_numbers(cx);
10890 self.set_relative_line_number(Some(!is_relative), cx)
10891 }
10892
10893 pub fn set_relative_line_number(
10894 &mut self,
10895 is_relative: Option<bool>,
10896 cx: &mut ViewContext<Self>,
10897 ) {
10898 self.use_relative_line_numbers = is_relative;
10899 cx.notify();
10900 }
10901
10902 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10903 self.show_gutter = show_gutter;
10904 cx.notify();
10905 }
10906
10907 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10908 self.show_line_numbers = Some(show_line_numbers);
10909 cx.notify();
10910 }
10911
10912 pub fn set_show_git_diff_gutter(
10913 &mut self,
10914 show_git_diff_gutter: bool,
10915 cx: &mut ViewContext<Self>,
10916 ) {
10917 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10918 cx.notify();
10919 }
10920
10921 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10922 self.show_code_actions = Some(show_code_actions);
10923 cx.notify();
10924 }
10925
10926 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10927 self.show_runnables = Some(show_runnables);
10928 cx.notify();
10929 }
10930
10931 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10932 if self.display_map.read(cx).masked != masked {
10933 self.display_map.update(cx, |map, _| map.masked = masked);
10934 }
10935 cx.notify()
10936 }
10937
10938 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10939 self.show_wrap_guides = Some(show_wrap_guides);
10940 cx.notify();
10941 }
10942
10943 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10944 self.show_indent_guides = Some(show_indent_guides);
10945 cx.notify();
10946 }
10947
10948 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10949 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10950 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10951 if let Some(dir) = file.abs_path(cx).parent() {
10952 return Some(dir.to_owned());
10953 }
10954 }
10955
10956 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10957 return Some(project_path.path.to_path_buf());
10958 }
10959 }
10960
10961 None
10962 }
10963
10964 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10965 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10966 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10967 cx.reveal_path(&file.abs_path(cx));
10968 }
10969 }
10970 }
10971
10972 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10973 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10974 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10975 if let Some(path) = file.abs_path(cx).to_str() {
10976 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10977 }
10978 }
10979 }
10980 }
10981
10982 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
10983 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10984 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10985 if let Some(path) = file.path().to_str() {
10986 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
10987 }
10988 }
10989 }
10990 }
10991
10992 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
10993 self.show_git_blame_gutter = !self.show_git_blame_gutter;
10994
10995 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
10996 self.start_git_blame(true, cx);
10997 }
10998
10999 cx.notify();
11000 }
11001
11002 pub fn toggle_git_blame_inline(
11003 &mut self,
11004 _: &ToggleGitBlameInline,
11005 cx: &mut ViewContext<Self>,
11006 ) {
11007 self.toggle_git_blame_inline_internal(true, cx);
11008 cx.notify();
11009 }
11010
11011 pub fn git_blame_inline_enabled(&self) -> bool {
11012 self.git_blame_inline_enabled
11013 }
11014
11015 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11016 self.show_selection_menu = self
11017 .show_selection_menu
11018 .map(|show_selections_menu| !show_selections_menu)
11019 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11020
11021 cx.notify();
11022 }
11023
11024 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11025 self.show_selection_menu
11026 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11027 }
11028
11029 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11030 if let Some(project) = self.project.as_ref() {
11031 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11032 return;
11033 };
11034
11035 if buffer.read(cx).file().is_none() {
11036 return;
11037 }
11038
11039 let focused = self.focus_handle(cx).contains_focused(cx);
11040
11041 let project = project.clone();
11042 let blame =
11043 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11044 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11045 self.blame = Some(blame);
11046 }
11047 }
11048
11049 fn toggle_git_blame_inline_internal(
11050 &mut self,
11051 user_triggered: bool,
11052 cx: &mut ViewContext<Self>,
11053 ) {
11054 if self.git_blame_inline_enabled {
11055 self.git_blame_inline_enabled = false;
11056 self.show_git_blame_inline = false;
11057 self.show_git_blame_inline_delay_task.take();
11058 } else {
11059 self.git_blame_inline_enabled = true;
11060 self.start_git_blame_inline(user_triggered, cx);
11061 }
11062
11063 cx.notify();
11064 }
11065
11066 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11067 self.start_git_blame(user_triggered, cx);
11068
11069 if ProjectSettings::get_global(cx)
11070 .git
11071 .inline_blame_delay()
11072 .is_some()
11073 {
11074 self.start_inline_blame_timer(cx);
11075 } else {
11076 self.show_git_blame_inline = true
11077 }
11078 }
11079
11080 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11081 self.blame.as_ref()
11082 }
11083
11084 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11085 self.show_git_blame_gutter && self.has_blame_entries(cx)
11086 }
11087
11088 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11089 self.show_git_blame_inline
11090 && self.focus_handle.is_focused(cx)
11091 && !self.newest_selection_head_on_empty_line(cx)
11092 && self.has_blame_entries(cx)
11093 }
11094
11095 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11096 self.blame()
11097 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11098 }
11099
11100 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11101 let cursor_anchor = self.selections.newest_anchor().head();
11102
11103 let snapshot = self.buffer.read(cx).snapshot(cx);
11104 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11105
11106 snapshot.line_len(buffer_row) == 0
11107 }
11108
11109 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11110 let (path, selection, repo) = maybe!({
11111 let project_handle = self.project.as_ref()?.clone();
11112 let project = project_handle.read(cx);
11113
11114 let selection = self.selections.newest::<Point>(cx);
11115 let selection_range = selection.range();
11116
11117 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11118 (buffer, selection_range.start.row..selection_range.end.row)
11119 } else {
11120 let buffer_ranges = self
11121 .buffer()
11122 .read(cx)
11123 .range_to_buffer_ranges(selection_range, cx);
11124
11125 let (buffer, range, _) = if selection.reversed {
11126 buffer_ranges.first()
11127 } else {
11128 buffer_ranges.last()
11129 }?;
11130
11131 let snapshot = buffer.read(cx).snapshot();
11132 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11133 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11134 (buffer.clone(), selection)
11135 };
11136
11137 let path = buffer
11138 .read(cx)
11139 .file()?
11140 .as_local()?
11141 .path()
11142 .to_str()?
11143 .to_string();
11144 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11145 Some((path, selection, repo))
11146 })
11147 .ok_or_else(|| anyhow!("unable to open git repository"))?;
11148
11149 const REMOTE_NAME: &str = "origin";
11150 let origin_url = repo
11151 .remote_url(REMOTE_NAME)
11152 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11153 let sha = repo
11154 .head_sha()
11155 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11156
11157 let (provider, remote) =
11158 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11159 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11160
11161 Ok(provider.build_permalink(
11162 remote,
11163 BuildPermalinkParams {
11164 sha: &sha,
11165 path: &path,
11166 selection: Some(selection),
11167 },
11168 ))
11169 }
11170
11171 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11172 let permalink = self.get_permalink_to_line(cx);
11173
11174 match permalink {
11175 Ok(permalink) => {
11176 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11177 }
11178 Err(err) => {
11179 let message = format!("Failed to copy permalink: {err}");
11180
11181 Err::<(), anyhow::Error>(err).log_err();
11182
11183 if let Some(workspace) = self.workspace() {
11184 workspace.update(cx, |workspace, cx| {
11185 struct CopyPermalinkToLine;
11186
11187 workspace.show_toast(
11188 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11189 cx,
11190 )
11191 })
11192 }
11193 }
11194 }
11195 }
11196
11197 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11198 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11199 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11200 if let Some(path) = file.path().to_str() {
11201 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11202 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11203 }
11204 }
11205 }
11206 }
11207
11208 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11209 let permalink = self.get_permalink_to_line(cx);
11210
11211 match permalink {
11212 Ok(permalink) => {
11213 cx.open_url(permalink.as_ref());
11214 }
11215 Err(err) => {
11216 let message = format!("Failed to open permalink: {err}");
11217
11218 Err::<(), anyhow::Error>(err).log_err();
11219
11220 if let Some(workspace) = self.workspace() {
11221 workspace.update(cx, |workspace, cx| {
11222 struct OpenPermalinkToLine;
11223
11224 workspace.show_toast(
11225 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11226 cx,
11227 )
11228 })
11229 }
11230 }
11231 }
11232 }
11233
11234 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11235 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11236 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11237 pub fn highlight_rows<T: 'static>(
11238 &mut self,
11239 rows: RangeInclusive<Anchor>,
11240 color: Option<Hsla>,
11241 should_autoscroll: bool,
11242 cx: &mut ViewContext<Self>,
11243 ) {
11244 let snapshot = self.buffer().read(cx).snapshot(cx);
11245 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11246 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11247 highlight
11248 .range
11249 .start()
11250 .cmp(rows.start(), &snapshot)
11251 .then(highlight.range.end().cmp(rows.end(), &snapshot))
11252 });
11253 match (color, existing_highlight_index) {
11254 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11255 ix,
11256 RowHighlight {
11257 index: post_inc(&mut self.highlight_order),
11258 range: rows,
11259 should_autoscroll,
11260 color,
11261 },
11262 ),
11263 (None, Ok(i)) => {
11264 row_highlights.remove(i);
11265 }
11266 }
11267 }
11268
11269 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11270 pub fn clear_row_highlights<T: 'static>(&mut self) {
11271 self.highlighted_rows.remove(&TypeId::of::<T>());
11272 }
11273
11274 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11275 pub fn highlighted_rows<T: 'static>(
11276 &self,
11277 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11278 Some(
11279 self.highlighted_rows
11280 .get(&TypeId::of::<T>())?
11281 .iter()
11282 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11283 )
11284 }
11285
11286 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11287 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11288 /// Allows to ignore certain kinds of highlights.
11289 pub fn highlighted_display_rows(
11290 &mut self,
11291 cx: &mut WindowContext,
11292 ) -> BTreeMap<DisplayRow, Hsla> {
11293 let snapshot = self.snapshot(cx);
11294 let mut used_highlight_orders = HashMap::default();
11295 self.highlighted_rows
11296 .iter()
11297 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11298 .fold(
11299 BTreeMap::<DisplayRow, Hsla>::new(),
11300 |mut unique_rows, highlight| {
11301 let start_row = highlight.range.start().to_display_point(&snapshot).row();
11302 let end_row = highlight.range.end().to_display_point(&snapshot).row();
11303 for row in start_row.0..=end_row.0 {
11304 let used_index =
11305 used_highlight_orders.entry(row).or_insert(highlight.index);
11306 if highlight.index >= *used_index {
11307 *used_index = highlight.index;
11308 match highlight.color {
11309 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11310 None => unique_rows.remove(&DisplayRow(row)),
11311 };
11312 }
11313 }
11314 unique_rows
11315 },
11316 )
11317 }
11318
11319 pub fn highlighted_display_row_for_autoscroll(
11320 &self,
11321 snapshot: &DisplaySnapshot,
11322 ) -> Option<DisplayRow> {
11323 self.highlighted_rows
11324 .values()
11325 .flat_map(|highlighted_rows| highlighted_rows.iter())
11326 .filter_map(|highlight| {
11327 if highlight.color.is_none() || !highlight.should_autoscroll {
11328 return None;
11329 }
11330 Some(highlight.range.start().to_display_point(snapshot).row())
11331 })
11332 .min()
11333 }
11334
11335 pub fn set_search_within_ranges(
11336 &mut self,
11337 ranges: &[Range<Anchor>],
11338 cx: &mut ViewContext<Self>,
11339 ) {
11340 self.highlight_background::<SearchWithinRange>(
11341 ranges,
11342 |colors| colors.editor_document_highlight_read_background,
11343 cx,
11344 )
11345 }
11346
11347 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11348 self.breadcrumb_header = Some(new_header);
11349 }
11350
11351 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11352 self.clear_background_highlights::<SearchWithinRange>(cx);
11353 }
11354
11355 pub fn highlight_background<T: 'static>(
11356 &mut self,
11357 ranges: &[Range<Anchor>],
11358 color_fetcher: fn(&ThemeColors) -> Hsla,
11359 cx: &mut ViewContext<Self>,
11360 ) {
11361 self.background_highlights
11362 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11363 self.scrollbar_marker_state.dirty = true;
11364 cx.notify();
11365 }
11366
11367 pub fn clear_background_highlights<T: 'static>(
11368 &mut self,
11369 cx: &mut ViewContext<Self>,
11370 ) -> Option<BackgroundHighlight> {
11371 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11372 if !text_highlights.1.is_empty() {
11373 self.scrollbar_marker_state.dirty = true;
11374 cx.notify();
11375 }
11376 Some(text_highlights)
11377 }
11378
11379 pub fn highlight_gutter<T: 'static>(
11380 &mut self,
11381 ranges: &[Range<Anchor>],
11382 color_fetcher: fn(&AppContext) -> Hsla,
11383 cx: &mut ViewContext<Self>,
11384 ) {
11385 self.gutter_highlights
11386 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11387 cx.notify();
11388 }
11389
11390 pub fn clear_gutter_highlights<T: 'static>(
11391 &mut self,
11392 cx: &mut ViewContext<Self>,
11393 ) -> Option<GutterHighlight> {
11394 cx.notify();
11395 self.gutter_highlights.remove(&TypeId::of::<T>())
11396 }
11397
11398 #[cfg(feature = "test-support")]
11399 pub fn all_text_background_highlights(
11400 &mut self,
11401 cx: &mut ViewContext<Self>,
11402 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11403 let snapshot = self.snapshot(cx);
11404 let buffer = &snapshot.buffer_snapshot;
11405 let start = buffer.anchor_before(0);
11406 let end = buffer.anchor_after(buffer.len());
11407 let theme = cx.theme().colors();
11408 self.background_highlights_in_range(start..end, &snapshot, theme)
11409 }
11410
11411 #[cfg(feature = "test-support")]
11412 pub fn search_background_highlights(
11413 &mut self,
11414 cx: &mut ViewContext<Self>,
11415 ) -> Vec<Range<Point>> {
11416 let snapshot = self.buffer().read(cx).snapshot(cx);
11417
11418 let highlights = self
11419 .background_highlights
11420 .get(&TypeId::of::<items::BufferSearchHighlights>());
11421
11422 if let Some((_color, ranges)) = highlights {
11423 ranges
11424 .iter()
11425 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11426 .collect_vec()
11427 } else {
11428 vec![]
11429 }
11430 }
11431
11432 fn document_highlights_for_position<'a>(
11433 &'a self,
11434 position: Anchor,
11435 buffer: &'a MultiBufferSnapshot,
11436 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11437 let read_highlights = self
11438 .background_highlights
11439 .get(&TypeId::of::<DocumentHighlightRead>())
11440 .map(|h| &h.1);
11441 let write_highlights = self
11442 .background_highlights
11443 .get(&TypeId::of::<DocumentHighlightWrite>())
11444 .map(|h| &h.1);
11445 let left_position = position.bias_left(buffer);
11446 let right_position = position.bias_right(buffer);
11447 read_highlights
11448 .into_iter()
11449 .chain(write_highlights)
11450 .flat_map(move |ranges| {
11451 let start_ix = match ranges.binary_search_by(|probe| {
11452 let cmp = probe.end.cmp(&left_position, buffer);
11453 if cmp.is_ge() {
11454 Ordering::Greater
11455 } else {
11456 Ordering::Less
11457 }
11458 }) {
11459 Ok(i) | Err(i) => i,
11460 };
11461
11462 ranges[start_ix..]
11463 .iter()
11464 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11465 })
11466 }
11467
11468 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11469 self.background_highlights
11470 .get(&TypeId::of::<T>())
11471 .map_or(false, |(_, highlights)| !highlights.is_empty())
11472 }
11473
11474 pub fn background_highlights_in_range(
11475 &self,
11476 search_range: Range<Anchor>,
11477 display_snapshot: &DisplaySnapshot,
11478 theme: &ThemeColors,
11479 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11480 let mut results = Vec::new();
11481 for (color_fetcher, ranges) in self.background_highlights.values() {
11482 let color = color_fetcher(theme);
11483 let start_ix = match ranges.binary_search_by(|probe| {
11484 let cmp = probe
11485 .end
11486 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11487 if cmp.is_gt() {
11488 Ordering::Greater
11489 } else {
11490 Ordering::Less
11491 }
11492 }) {
11493 Ok(i) | Err(i) => i,
11494 };
11495 for range in &ranges[start_ix..] {
11496 if range
11497 .start
11498 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11499 .is_ge()
11500 {
11501 break;
11502 }
11503
11504 let start = range.start.to_display_point(display_snapshot);
11505 let end = range.end.to_display_point(display_snapshot);
11506 results.push((start..end, color))
11507 }
11508 }
11509 results
11510 }
11511
11512 pub fn background_highlight_row_ranges<T: 'static>(
11513 &self,
11514 search_range: Range<Anchor>,
11515 display_snapshot: &DisplaySnapshot,
11516 count: usize,
11517 ) -> Vec<RangeInclusive<DisplayPoint>> {
11518 let mut results = Vec::new();
11519 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11520 return vec![];
11521 };
11522
11523 let start_ix = match ranges.binary_search_by(|probe| {
11524 let cmp = probe
11525 .end
11526 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11527 if cmp.is_gt() {
11528 Ordering::Greater
11529 } else {
11530 Ordering::Less
11531 }
11532 }) {
11533 Ok(i) | Err(i) => i,
11534 };
11535 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11536 if let (Some(start_display), Some(end_display)) = (start, end) {
11537 results.push(
11538 start_display.to_display_point(display_snapshot)
11539 ..=end_display.to_display_point(display_snapshot),
11540 );
11541 }
11542 };
11543 let mut start_row: Option<Point> = None;
11544 let mut end_row: Option<Point> = None;
11545 if ranges.len() > count {
11546 return Vec::new();
11547 }
11548 for range in &ranges[start_ix..] {
11549 if range
11550 .start
11551 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11552 .is_ge()
11553 {
11554 break;
11555 }
11556 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11557 if let Some(current_row) = &end_row {
11558 if end.row == current_row.row {
11559 continue;
11560 }
11561 }
11562 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11563 if start_row.is_none() {
11564 assert_eq!(end_row, None);
11565 start_row = Some(start);
11566 end_row = Some(end);
11567 continue;
11568 }
11569 if let Some(current_end) = end_row.as_mut() {
11570 if start.row > current_end.row + 1 {
11571 push_region(start_row, end_row);
11572 start_row = Some(start);
11573 end_row = Some(end);
11574 } else {
11575 // Merge two hunks.
11576 *current_end = end;
11577 }
11578 } else {
11579 unreachable!();
11580 }
11581 }
11582 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11583 push_region(start_row, end_row);
11584 results
11585 }
11586
11587 pub fn gutter_highlights_in_range(
11588 &self,
11589 search_range: Range<Anchor>,
11590 display_snapshot: &DisplaySnapshot,
11591 cx: &AppContext,
11592 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11593 let mut results = Vec::new();
11594 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11595 let color = color_fetcher(cx);
11596 let start_ix = match ranges.binary_search_by(|probe| {
11597 let cmp = probe
11598 .end
11599 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11600 if cmp.is_gt() {
11601 Ordering::Greater
11602 } else {
11603 Ordering::Less
11604 }
11605 }) {
11606 Ok(i) | Err(i) => i,
11607 };
11608 for range in &ranges[start_ix..] {
11609 if range
11610 .start
11611 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11612 .is_ge()
11613 {
11614 break;
11615 }
11616
11617 let start = range.start.to_display_point(display_snapshot);
11618 let end = range.end.to_display_point(display_snapshot);
11619 results.push((start..end, color))
11620 }
11621 }
11622 results
11623 }
11624
11625 /// Get the text ranges corresponding to the redaction query
11626 pub fn redacted_ranges(
11627 &self,
11628 search_range: Range<Anchor>,
11629 display_snapshot: &DisplaySnapshot,
11630 cx: &WindowContext,
11631 ) -> Vec<Range<DisplayPoint>> {
11632 display_snapshot
11633 .buffer_snapshot
11634 .redacted_ranges(search_range, |file| {
11635 if let Some(file) = file {
11636 file.is_private()
11637 && EditorSettings::get(
11638 Some(SettingsLocation {
11639 worktree_id: file.worktree_id(cx),
11640 path: file.path().as_ref(),
11641 }),
11642 cx,
11643 )
11644 .redact_private_values
11645 } else {
11646 false
11647 }
11648 })
11649 .map(|range| {
11650 range.start.to_display_point(display_snapshot)
11651 ..range.end.to_display_point(display_snapshot)
11652 })
11653 .collect()
11654 }
11655
11656 pub fn highlight_text<T: 'static>(
11657 &mut self,
11658 ranges: Vec<Range<Anchor>>,
11659 style: HighlightStyle,
11660 cx: &mut ViewContext<Self>,
11661 ) {
11662 self.display_map.update(cx, |map, _| {
11663 map.highlight_text(TypeId::of::<T>(), ranges, style)
11664 });
11665 cx.notify();
11666 }
11667
11668 pub(crate) fn highlight_inlays<T: 'static>(
11669 &mut self,
11670 highlights: Vec<InlayHighlight>,
11671 style: HighlightStyle,
11672 cx: &mut ViewContext<Self>,
11673 ) {
11674 self.display_map.update(cx, |map, _| {
11675 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11676 });
11677 cx.notify();
11678 }
11679
11680 pub fn text_highlights<'a, T: 'static>(
11681 &'a self,
11682 cx: &'a AppContext,
11683 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11684 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11685 }
11686
11687 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11688 let cleared = self
11689 .display_map
11690 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11691 if cleared {
11692 cx.notify();
11693 }
11694 }
11695
11696 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11697 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11698 && self.focus_handle.is_focused(cx)
11699 }
11700
11701 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11702 self.show_cursor_when_unfocused = is_enabled;
11703 cx.notify();
11704 }
11705
11706 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11707 cx.notify();
11708 }
11709
11710 fn on_buffer_event(
11711 &mut self,
11712 multibuffer: Model<MultiBuffer>,
11713 event: &multi_buffer::Event,
11714 cx: &mut ViewContext<Self>,
11715 ) {
11716 match event {
11717 multi_buffer::Event::Edited {
11718 singleton_buffer_edited,
11719 } => {
11720 self.scrollbar_marker_state.dirty = true;
11721 self.active_indent_guides_state.dirty = true;
11722 self.refresh_active_diagnostics(cx);
11723 self.refresh_code_actions(cx);
11724 if self.has_active_inline_completion(cx) {
11725 self.update_visible_inline_completion(cx);
11726 }
11727 cx.emit(EditorEvent::BufferEdited);
11728 cx.emit(SearchEvent::MatchesInvalidated);
11729 if *singleton_buffer_edited {
11730 if let Some(project) = &self.project {
11731 let project = project.read(cx);
11732 #[allow(clippy::mutable_key_type)]
11733 let languages_affected = multibuffer
11734 .read(cx)
11735 .all_buffers()
11736 .into_iter()
11737 .filter_map(|buffer| {
11738 let buffer = buffer.read(cx);
11739 let language = buffer.language()?;
11740 if project.is_local_or_ssh()
11741 && project.language_servers_for_buffer(buffer, cx).count() == 0
11742 {
11743 None
11744 } else {
11745 Some(language)
11746 }
11747 })
11748 .cloned()
11749 .collect::<HashSet<_>>();
11750 if !languages_affected.is_empty() {
11751 self.refresh_inlay_hints(
11752 InlayHintRefreshReason::BufferEdited(languages_affected),
11753 cx,
11754 );
11755 }
11756 }
11757 }
11758
11759 let Some(project) = &self.project else { return };
11760 let telemetry = project.read(cx).client().telemetry().clone();
11761 refresh_linked_ranges(self, cx);
11762 telemetry.log_edit_event("editor");
11763 }
11764 multi_buffer::Event::ExcerptsAdded {
11765 buffer,
11766 predecessor,
11767 excerpts,
11768 } => {
11769 self.tasks_update_task = Some(self.refresh_runnables(cx));
11770 cx.emit(EditorEvent::ExcerptsAdded {
11771 buffer: buffer.clone(),
11772 predecessor: *predecessor,
11773 excerpts: excerpts.clone(),
11774 });
11775 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11776 }
11777 multi_buffer::Event::ExcerptsRemoved { ids } => {
11778 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11779 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11780 }
11781 multi_buffer::Event::ExcerptsEdited { ids } => {
11782 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11783 }
11784 multi_buffer::Event::ExcerptsExpanded { ids } => {
11785 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11786 }
11787 multi_buffer::Event::Reparsed(buffer_id) => {
11788 self.tasks_update_task = Some(self.refresh_runnables(cx));
11789
11790 cx.emit(EditorEvent::Reparsed(*buffer_id));
11791 }
11792 multi_buffer::Event::LanguageChanged(buffer_id) => {
11793 linked_editing_ranges::refresh_linked_ranges(self, cx);
11794 cx.emit(EditorEvent::Reparsed(*buffer_id));
11795 cx.notify();
11796 }
11797 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11798 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11799 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11800 cx.emit(EditorEvent::TitleChanged)
11801 }
11802 multi_buffer::Event::DiffBaseChanged => {
11803 self.scrollbar_marker_state.dirty = true;
11804 cx.emit(EditorEvent::DiffBaseChanged);
11805 cx.notify();
11806 }
11807 multi_buffer::Event::DiffUpdated { buffer } => {
11808 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11809 cx.notify();
11810 }
11811 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11812 multi_buffer::Event::DiagnosticsUpdated => {
11813 self.refresh_active_diagnostics(cx);
11814 self.scrollbar_marker_state.dirty = true;
11815 cx.notify();
11816 }
11817 _ => {}
11818 };
11819 }
11820
11821 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11822 cx.notify();
11823 }
11824
11825 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11826 self.tasks_update_task = Some(self.refresh_runnables(cx));
11827 self.refresh_inline_completion(true, false, cx);
11828 self.refresh_inlay_hints(
11829 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11830 self.selections.newest_anchor().head(),
11831 &self.buffer.read(cx).snapshot(cx),
11832 cx,
11833 )),
11834 cx,
11835 );
11836 let editor_settings = EditorSettings::get_global(cx);
11837 if let Some(cursor_shape) = editor_settings.cursor_shape {
11838 self.cursor_shape = cursor_shape;
11839 }
11840 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11841 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11842
11843 let project_settings = ProjectSettings::get_global(cx);
11844 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11845
11846 if self.mode == EditorMode::Full {
11847 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11848 if self.git_blame_inline_enabled != inline_blame_enabled {
11849 self.toggle_git_blame_inline_internal(false, cx);
11850 }
11851 }
11852
11853 cx.notify();
11854 }
11855
11856 pub fn set_searchable(&mut self, searchable: bool) {
11857 self.searchable = searchable;
11858 }
11859
11860 pub fn searchable(&self) -> bool {
11861 self.searchable
11862 }
11863
11864 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11865 self.open_excerpts_common(true, cx)
11866 }
11867
11868 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11869 self.open_excerpts_common(false, cx)
11870 }
11871
11872 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11873 let buffer = self.buffer.read(cx);
11874 if buffer.is_singleton() {
11875 cx.propagate();
11876 return;
11877 }
11878
11879 let Some(workspace) = self.workspace() else {
11880 cx.propagate();
11881 return;
11882 };
11883
11884 let mut new_selections_by_buffer = HashMap::default();
11885 for selection in self.selections.all::<usize>(cx) {
11886 for (buffer, mut range, _) in
11887 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11888 {
11889 if selection.reversed {
11890 mem::swap(&mut range.start, &mut range.end);
11891 }
11892 new_selections_by_buffer
11893 .entry(buffer)
11894 .or_insert(Vec::new())
11895 .push(range)
11896 }
11897 }
11898
11899 // We defer the pane interaction because we ourselves are a workspace item
11900 // and activating a new item causes the pane to call a method on us reentrantly,
11901 // which panics if we're on the stack.
11902 cx.window_context().defer(move |cx| {
11903 workspace.update(cx, |workspace, cx| {
11904 let pane = if split {
11905 workspace.adjacent_pane(cx)
11906 } else {
11907 workspace.active_pane().clone()
11908 };
11909
11910 for (buffer, ranges) in new_selections_by_buffer {
11911 let editor =
11912 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11913 editor.update(cx, |editor, cx| {
11914 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11915 s.select_ranges(ranges);
11916 });
11917 });
11918 }
11919 })
11920 });
11921 }
11922
11923 fn jump(
11924 &mut self,
11925 path: ProjectPath,
11926 position: Point,
11927 anchor: language::Anchor,
11928 offset_from_top: u32,
11929 cx: &mut ViewContext<Self>,
11930 ) {
11931 let workspace = self.workspace();
11932 cx.spawn(|_, mut cx| async move {
11933 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11934 let editor = workspace.update(&mut cx, |workspace, cx| {
11935 // Reset the preview item id before opening the new item
11936 workspace.active_pane().update(cx, |pane, cx| {
11937 pane.set_preview_item_id(None, cx);
11938 });
11939 workspace.open_path_preview(path, None, true, true, cx)
11940 })?;
11941 let editor = editor
11942 .await?
11943 .downcast::<Editor>()
11944 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11945 .downgrade();
11946 editor.update(&mut cx, |editor, cx| {
11947 let buffer = editor
11948 .buffer()
11949 .read(cx)
11950 .as_singleton()
11951 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11952 let buffer = buffer.read(cx);
11953 let cursor = if buffer.can_resolve(&anchor) {
11954 language::ToPoint::to_point(&anchor, buffer)
11955 } else {
11956 buffer.clip_point(position, Bias::Left)
11957 };
11958
11959 let nav_history = editor.nav_history.take();
11960 editor.change_selections(
11961 Some(Autoscroll::top_relative(offset_from_top as usize)),
11962 cx,
11963 |s| {
11964 s.select_ranges([cursor..cursor]);
11965 },
11966 );
11967 editor.nav_history = nav_history;
11968
11969 anyhow::Ok(())
11970 })??;
11971
11972 anyhow::Ok(())
11973 })
11974 .detach_and_log_err(cx);
11975 }
11976
11977 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
11978 let snapshot = self.buffer.read(cx).read(cx);
11979 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
11980 Some(
11981 ranges
11982 .iter()
11983 .map(move |range| {
11984 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
11985 })
11986 .collect(),
11987 )
11988 }
11989
11990 fn selection_replacement_ranges(
11991 &self,
11992 range: Range<OffsetUtf16>,
11993 cx: &AppContext,
11994 ) -> Vec<Range<OffsetUtf16>> {
11995 let selections = self.selections.all::<OffsetUtf16>(cx);
11996 let newest_selection = selections
11997 .iter()
11998 .max_by_key(|selection| selection.id)
11999 .unwrap();
12000 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12001 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12002 let snapshot = self.buffer.read(cx).read(cx);
12003 selections
12004 .into_iter()
12005 .map(|mut selection| {
12006 selection.start.0 =
12007 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12008 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12009 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12010 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12011 })
12012 .collect()
12013 }
12014
12015 fn report_editor_event(
12016 &self,
12017 operation: &'static str,
12018 file_extension: Option<String>,
12019 cx: &AppContext,
12020 ) {
12021 if cfg!(any(test, feature = "test-support")) {
12022 return;
12023 }
12024
12025 let Some(project) = &self.project else { return };
12026
12027 // If None, we are in a file without an extension
12028 let file = self
12029 .buffer
12030 .read(cx)
12031 .as_singleton()
12032 .and_then(|b| b.read(cx).file());
12033 let file_extension = file_extension.or(file
12034 .as_ref()
12035 .and_then(|file| Path::new(file.file_name(cx)).extension())
12036 .and_then(|e| e.to_str())
12037 .map(|a| a.to_string()));
12038
12039 let vim_mode = cx
12040 .global::<SettingsStore>()
12041 .raw_user_settings()
12042 .get("vim_mode")
12043 == Some(&serde_json::Value::Bool(true));
12044
12045 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12046 == language::language_settings::InlineCompletionProvider::Copilot;
12047 let copilot_enabled_for_language = self
12048 .buffer
12049 .read(cx)
12050 .settings_at(0, cx)
12051 .show_inline_completions;
12052
12053 let telemetry = project.read(cx).client().telemetry().clone();
12054 telemetry.report_editor_event(
12055 file_extension,
12056 vim_mode,
12057 operation,
12058 copilot_enabled,
12059 copilot_enabled_for_language,
12060 )
12061 }
12062
12063 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12064 /// with each line being an array of {text, highlight} objects.
12065 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12066 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12067 return;
12068 };
12069
12070 #[derive(Serialize)]
12071 struct Chunk<'a> {
12072 text: String,
12073 highlight: Option<&'a str>,
12074 }
12075
12076 let snapshot = buffer.read(cx).snapshot();
12077 let range = self
12078 .selected_text_range(false, cx)
12079 .and_then(|selection| {
12080 if selection.range.is_empty() {
12081 None
12082 } else {
12083 Some(selection.range)
12084 }
12085 })
12086 .unwrap_or_else(|| 0..snapshot.len());
12087
12088 let chunks = snapshot.chunks(range, true);
12089 let mut lines = Vec::new();
12090 let mut line: VecDeque<Chunk> = VecDeque::new();
12091
12092 let Some(style) = self.style.as_ref() else {
12093 return;
12094 };
12095
12096 for chunk in chunks {
12097 let highlight = chunk
12098 .syntax_highlight_id
12099 .and_then(|id| id.name(&style.syntax));
12100 let mut chunk_lines = chunk.text.split('\n').peekable();
12101 while let Some(text) = chunk_lines.next() {
12102 let mut merged_with_last_token = false;
12103 if let Some(last_token) = line.back_mut() {
12104 if last_token.highlight == highlight {
12105 last_token.text.push_str(text);
12106 merged_with_last_token = true;
12107 }
12108 }
12109
12110 if !merged_with_last_token {
12111 line.push_back(Chunk {
12112 text: text.into(),
12113 highlight,
12114 });
12115 }
12116
12117 if chunk_lines.peek().is_some() {
12118 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12119 line.pop_front();
12120 }
12121 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12122 line.pop_back();
12123 }
12124
12125 lines.push(mem::take(&mut line));
12126 }
12127 }
12128 }
12129
12130 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12131 return;
12132 };
12133 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12134 }
12135
12136 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12137 &self.inlay_hint_cache
12138 }
12139
12140 pub fn replay_insert_event(
12141 &mut self,
12142 text: &str,
12143 relative_utf16_range: Option<Range<isize>>,
12144 cx: &mut ViewContext<Self>,
12145 ) {
12146 if !self.input_enabled {
12147 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12148 return;
12149 }
12150 if let Some(relative_utf16_range) = relative_utf16_range {
12151 let selections = self.selections.all::<OffsetUtf16>(cx);
12152 self.change_selections(None, cx, |s| {
12153 let new_ranges = selections.into_iter().map(|range| {
12154 let start = OffsetUtf16(
12155 range
12156 .head()
12157 .0
12158 .saturating_add_signed(relative_utf16_range.start),
12159 );
12160 let end = OffsetUtf16(
12161 range
12162 .head()
12163 .0
12164 .saturating_add_signed(relative_utf16_range.end),
12165 );
12166 start..end
12167 });
12168 s.select_ranges(new_ranges);
12169 });
12170 }
12171
12172 self.handle_input(text, cx);
12173 }
12174
12175 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12176 let Some(project) = self.project.as_ref() else {
12177 return false;
12178 };
12179 let project = project.read(cx);
12180
12181 let mut supports = false;
12182 self.buffer().read(cx).for_each_buffer(|buffer| {
12183 if !supports {
12184 supports = project
12185 .language_servers_for_buffer(buffer.read(cx), cx)
12186 .any(
12187 |(_, server)| match server.capabilities().inlay_hint_provider {
12188 Some(lsp::OneOf::Left(enabled)) => enabled,
12189 Some(lsp::OneOf::Right(_)) => true,
12190 None => false,
12191 },
12192 )
12193 }
12194 });
12195 supports
12196 }
12197
12198 pub fn focus(&self, cx: &mut WindowContext) {
12199 cx.focus(&self.focus_handle)
12200 }
12201
12202 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12203 self.focus_handle.is_focused(cx)
12204 }
12205
12206 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12207 cx.emit(EditorEvent::Focused);
12208
12209 if let Some(descendant) = self
12210 .last_focused_descendant
12211 .take()
12212 .and_then(|descendant| descendant.upgrade())
12213 {
12214 cx.focus(&descendant);
12215 } else {
12216 if let Some(blame) = self.blame.as_ref() {
12217 blame.update(cx, GitBlame::focus)
12218 }
12219
12220 self.blink_manager.update(cx, BlinkManager::enable);
12221 self.show_cursor_names(cx);
12222 self.buffer.update(cx, |buffer, cx| {
12223 buffer.finalize_last_transaction(cx);
12224 if self.leader_peer_id.is_none() {
12225 buffer.set_active_selections(
12226 &self.selections.disjoint_anchors(),
12227 self.selections.line_mode,
12228 self.cursor_shape,
12229 cx,
12230 );
12231 }
12232 });
12233 }
12234 }
12235
12236 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12237 cx.emit(EditorEvent::FocusedIn)
12238 }
12239
12240 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12241 if event.blurred != self.focus_handle {
12242 self.last_focused_descendant = Some(event.blurred);
12243 }
12244 }
12245
12246 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12247 self.blink_manager.update(cx, BlinkManager::disable);
12248 self.buffer
12249 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12250
12251 if let Some(blame) = self.blame.as_ref() {
12252 blame.update(cx, GitBlame::blur)
12253 }
12254 if !self.hover_state.focused(cx) {
12255 hide_hover(self, cx);
12256 }
12257
12258 self.hide_context_menu(cx);
12259 cx.emit(EditorEvent::Blurred);
12260 cx.notify();
12261 }
12262
12263 pub fn register_action<A: Action>(
12264 &mut self,
12265 listener: impl Fn(&A, &mut WindowContext) + 'static,
12266 ) -> Subscription {
12267 let id = self.next_editor_action_id.post_inc();
12268 let listener = Arc::new(listener);
12269 self.editor_actions.borrow_mut().insert(
12270 id,
12271 Box::new(move |cx| {
12272 let cx = cx.window_context();
12273 let listener = listener.clone();
12274 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12275 let action = action.downcast_ref().unwrap();
12276 if phase == DispatchPhase::Bubble {
12277 listener(action, cx)
12278 }
12279 })
12280 }),
12281 );
12282
12283 let editor_actions = self.editor_actions.clone();
12284 Subscription::new(move || {
12285 editor_actions.borrow_mut().remove(&id);
12286 })
12287 }
12288
12289 pub fn file_header_size(&self) -> u32 {
12290 self.file_header_size
12291 }
12292
12293 pub fn revert(
12294 &mut self,
12295 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12296 cx: &mut ViewContext<Self>,
12297 ) {
12298 self.buffer().update(cx, |multi_buffer, cx| {
12299 for (buffer_id, changes) in revert_changes {
12300 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12301 buffer.update(cx, |buffer, cx| {
12302 buffer.edit(
12303 changes.into_iter().map(|(range, text)| {
12304 (range, text.to_string().map(Arc::<str>::from))
12305 }),
12306 None,
12307 cx,
12308 );
12309 });
12310 }
12311 }
12312 });
12313 self.change_selections(None, cx, |selections| selections.refresh());
12314 }
12315
12316 pub fn to_pixel_point(
12317 &mut self,
12318 source: multi_buffer::Anchor,
12319 editor_snapshot: &EditorSnapshot,
12320 cx: &mut ViewContext<Self>,
12321 ) -> Option<gpui::Point<Pixels>> {
12322 let source_point = source.to_display_point(editor_snapshot);
12323 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12324 }
12325
12326 pub fn display_to_pixel_point(
12327 &mut self,
12328 source: DisplayPoint,
12329 editor_snapshot: &EditorSnapshot,
12330 cx: &mut ViewContext<Self>,
12331 ) -> Option<gpui::Point<Pixels>> {
12332 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12333 let text_layout_details = self.text_layout_details(cx);
12334 let scroll_top = text_layout_details
12335 .scroll_anchor
12336 .scroll_position(editor_snapshot)
12337 .y;
12338
12339 if source.row().as_f32() < scroll_top.floor() {
12340 return None;
12341 }
12342 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12343 let source_y = line_height * (source.row().as_f32() - scroll_top);
12344 Some(gpui::Point::new(source_x, source_y))
12345 }
12346
12347 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12348 let bounds = self.last_bounds?;
12349 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12350 }
12351
12352 pub fn has_active_completions_menu(&self) -> bool {
12353 self.context_menu.read().as_ref().map_or(false, |menu| {
12354 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12355 })
12356 }
12357
12358 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12359 self.addons
12360 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12361 }
12362
12363 pub fn unregister_addon<T: Addon>(&mut self) {
12364 self.addons.remove(&std::any::TypeId::of::<T>());
12365 }
12366
12367 pub fn addon<T: Addon>(&self) -> Option<&T> {
12368 let type_id = std::any::TypeId::of::<T>();
12369 self.addons
12370 .get(&type_id)
12371 .and_then(|item| item.to_any().downcast_ref::<T>())
12372 }
12373}
12374
12375fn hunks_for_selections(
12376 multi_buffer_snapshot: &MultiBufferSnapshot,
12377 selections: &[Selection<Anchor>],
12378) -> Vec<DiffHunk<MultiBufferRow>> {
12379 let buffer_rows_for_selections = selections.iter().map(|selection| {
12380 let head = selection.head();
12381 let tail = selection.tail();
12382 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12383 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12384 if start > end {
12385 end..start
12386 } else {
12387 start..end
12388 }
12389 });
12390
12391 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12392}
12393
12394pub fn hunks_for_rows(
12395 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12396 multi_buffer_snapshot: &MultiBufferSnapshot,
12397) -> Vec<DiffHunk<MultiBufferRow>> {
12398 let mut hunks = Vec::new();
12399 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12400 HashMap::default();
12401 for selected_multi_buffer_rows in rows {
12402 let query_rows =
12403 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12404 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12405 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12406 // when the caret is just above or just below the deleted hunk.
12407 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12408 let related_to_selection = if allow_adjacent {
12409 hunk.associated_range.overlaps(&query_rows)
12410 || hunk.associated_range.start == query_rows.end
12411 || hunk.associated_range.end == query_rows.start
12412 } else {
12413 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12414 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12415 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12416 || selected_multi_buffer_rows.end == hunk.associated_range.start
12417 };
12418 if related_to_selection {
12419 if !processed_buffer_rows
12420 .entry(hunk.buffer_id)
12421 .or_default()
12422 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12423 {
12424 continue;
12425 }
12426 hunks.push(hunk);
12427 }
12428 }
12429 }
12430
12431 hunks
12432}
12433
12434pub trait CollaborationHub {
12435 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12436 fn user_participant_indices<'a>(
12437 &self,
12438 cx: &'a AppContext,
12439 ) -> &'a HashMap<u64, ParticipantIndex>;
12440 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12441}
12442
12443impl CollaborationHub for Model<Project> {
12444 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12445 self.read(cx).collaborators()
12446 }
12447
12448 fn user_participant_indices<'a>(
12449 &self,
12450 cx: &'a AppContext,
12451 ) -> &'a HashMap<u64, ParticipantIndex> {
12452 self.read(cx).user_store().read(cx).participant_indices()
12453 }
12454
12455 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12456 let this = self.read(cx);
12457 let user_ids = this.collaborators().values().map(|c| c.user_id);
12458 this.user_store().read_with(cx, |user_store, cx| {
12459 user_store.participant_names(user_ids, cx)
12460 })
12461 }
12462}
12463
12464pub trait CompletionProvider {
12465 fn completions(
12466 &self,
12467 buffer: &Model<Buffer>,
12468 buffer_position: text::Anchor,
12469 trigger: CompletionContext,
12470 cx: &mut ViewContext<Editor>,
12471 ) -> Task<Result<Vec<Completion>>>;
12472
12473 fn resolve_completions(
12474 &self,
12475 buffer: Model<Buffer>,
12476 completion_indices: Vec<usize>,
12477 completions: Arc<RwLock<Box<[Completion]>>>,
12478 cx: &mut ViewContext<Editor>,
12479 ) -> Task<Result<bool>>;
12480
12481 fn apply_additional_edits_for_completion(
12482 &self,
12483 buffer: Model<Buffer>,
12484 completion: Completion,
12485 push_to_history: bool,
12486 cx: &mut ViewContext<Editor>,
12487 ) -> Task<Result<Option<language::Transaction>>>;
12488
12489 fn is_completion_trigger(
12490 &self,
12491 buffer: &Model<Buffer>,
12492 position: language::Anchor,
12493 text: &str,
12494 trigger_in_words: bool,
12495 cx: &mut ViewContext<Editor>,
12496 ) -> bool;
12497
12498 fn sort_completions(&self) -> bool {
12499 true
12500 }
12501}
12502
12503fn snippet_completions(
12504 project: &Project,
12505 buffer: &Model<Buffer>,
12506 buffer_position: text::Anchor,
12507 cx: &mut AppContext,
12508) -> Vec<Completion> {
12509 let language = buffer.read(cx).language_at(buffer_position);
12510 let language_name = language.as_ref().map(|language| language.lsp_id());
12511 let snippet_store = project.snippets().read(cx);
12512 let snippets = snippet_store.snippets_for(language_name, cx);
12513
12514 if snippets.is_empty() {
12515 return vec![];
12516 }
12517 let snapshot = buffer.read(cx).text_snapshot();
12518 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12519
12520 let mut lines = chunks.lines();
12521 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12522 return vec![];
12523 };
12524
12525 let scope = language.map(|language| language.default_scope());
12526 let classifier = CharClassifier::new(scope).for_completion(true);
12527 let mut last_word = line_at
12528 .chars()
12529 .rev()
12530 .take_while(|c| classifier.is_word(*c))
12531 .collect::<String>();
12532 last_word = last_word.chars().rev().collect();
12533 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12534 let to_lsp = |point: &text::Anchor| {
12535 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12536 point_to_lsp(end)
12537 };
12538 let lsp_end = to_lsp(&buffer_position);
12539 snippets
12540 .into_iter()
12541 .filter_map(|snippet| {
12542 let matching_prefix = snippet
12543 .prefix
12544 .iter()
12545 .find(|prefix| prefix.starts_with(&last_word))?;
12546 let start = as_offset - last_word.len();
12547 let start = snapshot.anchor_before(start);
12548 let range = start..buffer_position;
12549 let lsp_start = to_lsp(&start);
12550 let lsp_range = lsp::Range {
12551 start: lsp_start,
12552 end: lsp_end,
12553 };
12554 Some(Completion {
12555 old_range: range,
12556 new_text: snippet.body.clone(),
12557 label: CodeLabel {
12558 text: matching_prefix.clone(),
12559 runs: vec![],
12560 filter_range: 0..matching_prefix.len(),
12561 },
12562 server_id: LanguageServerId(usize::MAX),
12563 documentation: snippet.description.clone().map(Documentation::SingleLine),
12564 lsp_completion: lsp::CompletionItem {
12565 label: snippet.prefix.first().unwrap().clone(),
12566 kind: Some(CompletionItemKind::SNIPPET),
12567 label_details: snippet.description.as_ref().map(|description| {
12568 lsp::CompletionItemLabelDetails {
12569 detail: Some(description.clone()),
12570 description: None,
12571 }
12572 }),
12573 insert_text_format: Some(InsertTextFormat::SNIPPET),
12574 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12575 lsp::InsertReplaceEdit {
12576 new_text: snippet.body.clone(),
12577 insert: lsp_range,
12578 replace: lsp_range,
12579 },
12580 )),
12581 filter_text: Some(snippet.body.clone()),
12582 sort_text: Some(char::MAX.to_string()),
12583 ..Default::default()
12584 },
12585 confirm: None,
12586 })
12587 })
12588 .collect()
12589}
12590
12591impl CompletionProvider for Model<Project> {
12592 fn completions(
12593 &self,
12594 buffer: &Model<Buffer>,
12595 buffer_position: text::Anchor,
12596 options: CompletionContext,
12597 cx: &mut ViewContext<Editor>,
12598 ) -> Task<Result<Vec<Completion>>> {
12599 self.update(cx, |project, cx| {
12600 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12601 let project_completions = project.completions(buffer, buffer_position, options, cx);
12602 cx.background_executor().spawn(async move {
12603 let mut completions = project_completions.await?;
12604 //let snippets = snippets.into_iter().;
12605 completions.extend(snippets);
12606 Ok(completions)
12607 })
12608 })
12609 }
12610
12611 fn resolve_completions(
12612 &self,
12613 buffer: Model<Buffer>,
12614 completion_indices: Vec<usize>,
12615 completions: Arc<RwLock<Box<[Completion]>>>,
12616 cx: &mut ViewContext<Editor>,
12617 ) -> Task<Result<bool>> {
12618 self.update(cx, |project, cx| {
12619 project.resolve_completions(buffer, completion_indices, completions, cx)
12620 })
12621 }
12622
12623 fn apply_additional_edits_for_completion(
12624 &self,
12625 buffer: Model<Buffer>,
12626 completion: Completion,
12627 push_to_history: bool,
12628 cx: &mut ViewContext<Editor>,
12629 ) -> Task<Result<Option<language::Transaction>>> {
12630 self.update(cx, |project, cx| {
12631 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12632 })
12633 }
12634
12635 fn is_completion_trigger(
12636 &self,
12637 buffer: &Model<Buffer>,
12638 position: language::Anchor,
12639 text: &str,
12640 trigger_in_words: bool,
12641 cx: &mut ViewContext<Editor>,
12642 ) -> bool {
12643 if !EditorSettings::get_global(cx).show_completions_on_input {
12644 return false;
12645 }
12646
12647 let mut chars = text.chars();
12648 let char = if let Some(char) = chars.next() {
12649 char
12650 } else {
12651 return false;
12652 };
12653 if chars.next().is_some() {
12654 return false;
12655 }
12656
12657 let buffer = buffer.read(cx);
12658 let classifier = buffer
12659 .snapshot()
12660 .char_classifier_at(position)
12661 .for_completion(true);
12662 if trigger_in_words && classifier.is_word(char) {
12663 return true;
12664 }
12665
12666 buffer
12667 .completion_triggers()
12668 .iter()
12669 .any(|string| string == text)
12670 }
12671}
12672
12673fn inlay_hint_settings(
12674 location: Anchor,
12675 snapshot: &MultiBufferSnapshot,
12676 cx: &mut ViewContext<'_, Editor>,
12677) -> InlayHintSettings {
12678 let file = snapshot.file_at(location);
12679 let language = snapshot.language_at(location);
12680 let settings = all_language_settings(file, cx);
12681 settings
12682 .language(language.map(|l| l.name()).as_ref())
12683 .inlay_hints
12684}
12685
12686fn consume_contiguous_rows(
12687 contiguous_row_selections: &mut Vec<Selection<Point>>,
12688 selection: &Selection<Point>,
12689 display_map: &DisplaySnapshot,
12690 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12691) -> (MultiBufferRow, MultiBufferRow) {
12692 contiguous_row_selections.push(selection.clone());
12693 let start_row = MultiBufferRow(selection.start.row);
12694 let mut end_row = ending_row(selection, display_map);
12695
12696 while let Some(next_selection) = selections.peek() {
12697 if next_selection.start.row <= end_row.0 {
12698 end_row = ending_row(next_selection, display_map);
12699 contiguous_row_selections.push(selections.next().unwrap().clone());
12700 } else {
12701 break;
12702 }
12703 }
12704 (start_row, end_row)
12705}
12706
12707fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12708 if next_selection.end.column > 0 || next_selection.is_empty() {
12709 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12710 } else {
12711 MultiBufferRow(next_selection.end.row)
12712 }
12713}
12714
12715impl EditorSnapshot {
12716 pub fn remote_selections_in_range<'a>(
12717 &'a self,
12718 range: &'a Range<Anchor>,
12719 collaboration_hub: &dyn CollaborationHub,
12720 cx: &'a AppContext,
12721 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12722 let participant_names = collaboration_hub.user_names(cx);
12723 let participant_indices = collaboration_hub.user_participant_indices(cx);
12724 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12725 let collaborators_by_replica_id = collaborators_by_peer_id
12726 .iter()
12727 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12728 .collect::<HashMap<_, _>>();
12729 self.buffer_snapshot
12730 .selections_in_range(range, false)
12731 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12732 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12733 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12734 let user_name = participant_names.get(&collaborator.user_id).cloned();
12735 Some(RemoteSelection {
12736 replica_id,
12737 selection,
12738 cursor_shape,
12739 line_mode,
12740 participant_index,
12741 peer_id: collaborator.peer_id,
12742 user_name,
12743 })
12744 })
12745 }
12746
12747 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12748 self.display_snapshot.buffer_snapshot.language_at(position)
12749 }
12750
12751 pub fn is_focused(&self) -> bool {
12752 self.is_focused
12753 }
12754
12755 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12756 self.placeholder_text.as_ref()
12757 }
12758
12759 pub fn scroll_position(&self) -> gpui::Point<f32> {
12760 self.scroll_anchor.scroll_position(&self.display_snapshot)
12761 }
12762
12763 fn gutter_dimensions(
12764 &self,
12765 font_id: FontId,
12766 font_size: Pixels,
12767 em_width: Pixels,
12768 max_line_number_width: Pixels,
12769 cx: &AppContext,
12770 ) -> GutterDimensions {
12771 if !self.show_gutter {
12772 return GutterDimensions::default();
12773 }
12774 let descent = cx.text_system().descent(font_id, font_size);
12775
12776 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12777 matches!(
12778 ProjectSettings::get_global(cx).git.git_gutter,
12779 Some(GitGutterSetting::TrackedFiles)
12780 )
12781 });
12782 let gutter_settings = EditorSettings::get_global(cx).gutter;
12783 let show_line_numbers = self
12784 .show_line_numbers
12785 .unwrap_or(gutter_settings.line_numbers);
12786 let line_gutter_width = if show_line_numbers {
12787 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12788 let min_width_for_number_on_gutter = em_width * 4.0;
12789 max_line_number_width.max(min_width_for_number_on_gutter)
12790 } else {
12791 0.0.into()
12792 };
12793
12794 let show_code_actions = self
12795 .show_code_actions
12796 .unwrap_or(gutter_settings.code_actions);
12797
12798 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12799
12800 let git_blame_entries_width = self
12801 .render_git_blame_gutter
12802 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12803
12804 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12805 left_padding += if show_code_actions || show_runnables {
12806 em_width * 3.0
12807 } else if show_git_gutter && show_line_numbers {
12808 em_width * 2.0
12809 } else if show_git_gutter || show_line_numbers {
12810 em_width
12811 } else {
12812 px(0.)
12813 };
12814
12815 let right_padding = if gutter_settings.folds && show_line_numbers {
12816 em_width * 4.0
12817 } else if gutter_settings.folds {
12818 em_width * 3.0
12819 } else if show_line_numbers {
12820 em_width
12821 } else {
12822 px(0.)
12823 };
12824
12825 GutterDimensions {
12826 left_padding,
12827 right_padding,
12828 width: line_gutter_width + left_padding + right_padding,
12829 margin: -descent,
12830 git_blame_entries_width,
12831 }
12832 }
12833
12834 pub fn render_fold_toggle(
12835 &self,
12836 buffer_row: MultiBufferRow,
12837 row_contains_cursor: bool,
12838 editor: View<Editor>,
12839 cx: &mut WindowContext,
12840 ) -> Option<AnyElement> {
12841 let folded = self.is_line_folded(buffer_row);
12842
12843 if let Some(crease) = self
12844 .crease_snapshot
12845 .query_row(buffer_row, &self.buffer_snapshot)
12846 {
12847 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12848 if folded {
12849 editor.update(cx, |editor, cx| {
12850 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12851 });
12852 } else {
12853 editor.update(cx, |editor, cx| {
12854 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12855 });
12856 }
12857 });
12858
12859 Some((crease.render_toggle)(
12860 buffer_row,
12861 folded,
12862 toggle_callback,
12863 cx,
12864 ))
12865 } else if folded
12866 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12867 {
12868 Some(
12869 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12870 .selected(folded)
12871 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12872 if folded {
12873 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12874 } else {
12875 this.fold_at(&FoldAt { buffer_row }, cx);
12876 }
12877 }))
12878 .into_any_element(),
12879 )
12880 } else {
12881 None
12882 }
12883 }
12884
12885 pub fn render_crease_trailer(
12886 &self,
12887 buffer_row: MultiBufferRow,
12888 cx: &mut WindowContext,
12889 ) -> Option<AnyElement> {
12890 let folded = self.is_line_folded(buffer_row);
12891 let crease = self
12892 .crease_snapshot
12893 .query_row(buffer_row, &self.buffer_snapshot)?;
12894 Some((crease.render_trailer)(buffer_row, folded, cx))
12895 }
12896}
12897
12898impl Deref for EditorSnapshot {
12899 type Target = DisplaySnapshot;
12900
12901 fn deref(&self) -> &Self::Target {
12902 &self.display_snapshot
12903 }
12904}
12905
12906#[derive(Clone, Debug, PartialEq, Eq)]
12907pub enum EditorEvent {
12908 InputIgnored {
12909 text: Arc<str>,
12910 },
12911 InputHandled {
12912 utf16_range_to_replace: Option<Range<isize>>,
12913 text: Arc<str>,
12914 },
12915 ExcerptsAdded {
12916 buffer: Model<Buffer>,
12917 predecessor: ExcerptId,
12918 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12919 },
12920 ExcerptsRemoved {
12921 ids: Vec<ExcerptId>,
12922 },
12923 ExcerptsEdited {
12924 ids: Vec<ExcerptId>,
12925 },
12926 ExcerptsExpanded {
12927 ids: Vec<ExcerptId>,
12928 },
12929 BufferEdited,
12930 Edited {
12931 transaction_id: clock::Lamport,
12932 },
12933 Reparsed(BufferId),
12934 Focused,
12935 FocusedIn,
12936 Blurred,
12937 DirtyChanged,
12938 Saved,
12939 TitleChanged,
12940 DiffBaseChanged,
12941 SelectionsChanged {
12942 local: bool,
12943 },
12944 ScrollPositionChanged {
12945 local: bool,
12946 autoscroll: bool,
12947 },
12948 Closed,
12949 TransactionUndone {
12950 transaction_id: clock::Lamport,
12951 },
12952 TransactionBegun {
12953 transaction_id: clock::Lamport,
12954 },
12955}
12956
12957impl EventEmitter<EditorEvent> for Editor {}
12958
12959impl FocusableView for Editor {
12960 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12961 self.focus_handle.clone()
12962 }
12963}
12964
12965impl Render for Editor {
12966 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12967 let settings = ThemeSettings::get_global(cx);
12968
12969 let text_style = match self.mode {
12970 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12971 color: cx.theme().colors().editor_foreground,
12972 font_family: settings.ui_font.family.clone(),
12973 font_features: settings.ui_font.features.clone(),
12974 font_fallbacks: settings.ui_font.fallbacks.clone(),
12975 font_size: rems(0.875).into(),
12976 font_weight: settings.ui_font.weight,
12977 line_height: relative(settings.buffer_line_height.value()),
12978 ..Default::default()
12979 },
12980 EditorMode::Full => TextStyle {
12981 color: cx.theme().colors().editor_foreground,
12982 font_family: settings.buffer_font.family.clone(),
12983 font_features: settings.buffer_font.features.clone(),
12984 font_fallbacks: settings.buffer_font.fallbacks.clone(),
12985 font_size: settings.buffer_font_size(cx).into(),
12986 font_weight: settings.buffer_font.weight,
12987 line_height: relative(settings.buffer_line_height.value()),
12988 ..Default::default()
12989 },
12990 };
12991
12992 let background = match self.mode {
12993 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
12994 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
12995 EditorMode::Full => cx.theme().colors().editor_background,
12996 };
12997
12998 EditorElement::new(
12999 cx.view(),
13000 EditorStyle {
13001 background,
13002 local_player: cx.theme().players().local(),
13003 text: text_style,
13004 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13005 syntax: cx.theme().syntax().clone(),
13006 status: cx.theme().status().clone(),
13007 inlay_hints_style: make_inlay_hints_style(cx),
13008 suggestions_style: HighlightStyle {
13009 color: Some(cx.theme().status().predictive),
13010 ..HighlightStyle::default()
13011 },
13012 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13013 },
13014 )
13015 }
13016}
13017
13018impl ViewInputHandler for Editor {
13019 fn text_for_range(
13020 &mut self,
13021 range_utf16: Range<usize>,
13022 cx: &mut ViewContext<Self>,
13023 ) -> Option<String> {
13024 Some(
13025 self.buffer
13026 .read(cx)
13027 .read(cx)
13028 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13029 .collect(),
13030 )
13031 }
13032
13033 fn selected_text_range(
13034 &mut self,
13035 ignore_disabled_input: bool,
13036 cx: &mut ViewContext<Self>,
13037 ) -> Option<UTF16Selection> {
13038 // Prevent the IME menu from appearing when holding down an alphabetic key
13039 // while input is disabled.
13040 if !ignore_disabled_input && !self.input_enabled {
13041 return None;
13042 }
13043
13044 let selection = self.selections.newest::<OffsetUtf16>(cx);
13045 let range = selection.range();
13046
13047 Some(UTF16Selection {
13048 range: range.start.0..range.end.0,
13049 reversed: selection.reversed,
13050 })
13051 }
13052
13053 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13054 let snapshot = self.buffer.read(cx).read(cx);
13055 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13056 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13057 }
13058
13059 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13060 self.clear_highlights::<InputComposition>(cx);
13061 self.ime_transaction.take();
13062 }
13063
13064 fn replace_text_in_range(
13065 &mut self,
13066 range_utf16: Option<Range<usize>>,
13067 text: &str,
13068 cx: &mut ViewContext<Self>,
13069 ) {
13070 if !self.input_enabled {
13071 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13072 return;
13073 }
13074
13075 self.transact(cx, |this, cx| {
13076 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13077 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13078 Some(this.selection_replacement_ranges(range_utf16, cx))
13079 } else {
13080 this.marked_text_ranges(cx)
13081 };
13082
13083 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13084 let newest_selection_id = this.selections.newest_anchor().id;
13085 this.selections
13086 .all::<OffsetUtf16>(cx)
13087 .iter()
13088 .zip(ranges_to_replace.iter())
13089 .find_map(|(selection, range)| {
13090 if selection.id == newest_selection_id {
13091 Some(
13092 (range.start.0 as isize - selection.head().0 as isize)
13093 ..(range.end.0 as isize - selection.head().0 as isize),
13094 )
13095 } else {
13096 None
13097 }
13098 })
13099 });
13100
13101 cx.emit(EditorEvent::InputHandled {
13102 utf16_range_to_replace: range_to_replace,
13103 text: text.into(),
13104 });
13105
13106 if let Some(new_selected_ranges) = new_selected_ranges {
13107 this.change_selections(None, cx, |selections| {
13108 selections.select_ranges(new_selected_ranges)
13109 });
13110 this.backspace(&Default::default(), cx);
13111 }
13112
13113 this.handle_input(text, cx);
13114 });
13115
13116 if let Some(transaction) = self.ime_transaction {
13117 self.buffer.update(cx, |buffer, cx| {
13118 buffer.group_until_transaction(transaction, cx);
13119 });
13120 }
13121
13122 self.unmark_text(cx);
13123 }
13124
13125 fn replace_and_mark_text_in_range(
13126 &mut self,
13127 range_utf16: Option<Range<usize>>,
13128 text: &str,
13129 new_selected_range_utf16: Option<Range<usize>>,
13130 cx: &mut ViewContext<Self>,
13131 ) {
13132 if !self.input_enabled {
13133 return;
13134 }
13135
13136 let transaction = self.transact(cx, |this, cx| {
13137 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13138 let snapshot = this.buffer.read(cx).read(cx);
13139 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13140 for marked_range in &mut marked_ranges {
13141 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13142 marked_range.start.0 += relative_range_utf16.start;
13143 marked_range.start =
13144 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13145 marked_range.end =
13146 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13147 }
13148 }
13149 Some(marked_ranges)
13150 } else if let Some(range_utf16) = range_utf16 {
13151 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13152 Some(this.selection_replacement_ranges(range_utf16, cx))
13153 } else {
13154 None
13155 };
13156
13157 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13158 let newest_selection_id = this.selections.newest_anchor().id;
13159 this.selections
13160 .all::<OffsetUtf16>(cx)
13161 .iter()
13162 .zip(ranges_to_replace.iter())
13163 .find_map(|(selection, range)| {
13164 if selection.id == newest_selection_id {
13165 Some(
13166 (range.start.0 as isize - selection.head().0 as isize)
13167 ..(range.end.0 as isize - selection.head().0 as isize),
13168 )
13169 } else {
13170 None
13171 }
13172 })
13173 });
13174
13175 cx.emit(EditorEvent::InputHandled {
13176 utf16_range_to_replace: range_to_replace,
13177 text: text.into(),
13178 });
13179
13180 if let Some(ranges) = ranges_to_replace {
13181 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13182 }
13183
13184 let marked_ranges = {
13185 let snapshot = this.buffer.read(cx).read(cx);
13186 this.selections
13187 .disjoint_anchors()
13188 .iter()
13189 .map(|selection| {
13190 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13191 })
13192 .collect::<Vec<_>>()
13193 };
13194
13195 if text.is_empty() {
13196 this.unmark_text(cx);
13197 } else {
13198 this.highlight_text::<InputComposition>(
13199 marked_ranges.clone(),
13200 HighlightStyle {
13201 underline: Some(UnderlineStyle {
13202 thickness: px(1.),
13203 color: None,
13204 wavy: false,
13205 }),
13206 ..Default::default()
13207 },
13208 cx,
13209 );
13210 }
13211
13212 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13213 let use_autoclose = this.use_autoclose;
13214 let use_auto_surround = this.use_auto_surround;
13215 this.set_use_autoclose(false);
13216 this.set_use_auto_surround(false);
13217 this.handle_input(text, cx);
13218 this.set_use_autoclose(use_autoclose);
13219 this.set_use_auto_surround(use_auto_surround);
13220
13221 if let Some(new_selected_range) = new_selected_range_utf16 {
13222 let snapshot = this.buffer.read(cx).read(cx);
13223 let new_selected_ranges = marked_ranges
13224 .into_iter()
13225 .map(|marked_range| {
13226 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13227 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13228 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13229 snapshot.clip_offset_utf16(new_start, Bias::Left)
13230 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13231 })
13232 .collect::<Vec<_>>();
13233
13234 drop(snapshot);
13235 this.change_selections(None, cx, |selections| {
13236 selections.select_ranges(new_selected_ranges)
13237 });
13238 }
13239 });
13240
13241 self.ime_transaction = self.ime_transaction.or(transaction);
13242 if let Some(transaction) = self.ime_transaction {
13243 self.buffer.update(cx, |buffer, cx| {
13244 buffer.group_until_transaction(transaction, cx);
13245 });
13246 }
13247
13248 if self.text_highlights::<InputComposition>(cx).is_none() {
13249 self.ime_transaction.take();
13250 }
13251 }
13252
13253 fn bounds_for_range(
13254 &mut self,
13255 range_utf16: Range<usize>,
13256 element_bounds: gpui::Bounds<Pixels>,
13257 cx: &mut ViewContext<Self>,
13258 ) -> Option<gpui::Bounds<Pixels>> {
13259 let text_layout_details = self.text_layout_details(cx);
13260 let style = &text_layout_details.editor_style;
13261 let font_id = cx.text_system().resolve_font(&style.text.font());
13262 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13263 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13264
13265 let em_width = cx
13266 .text_system()
13267 .typographic_bounds(font_id, font_size, 'm')
13268 .unwrap()
13269 .size
13270 .width;
13271
13272 let snapshot = self.snapshot(cx);
13273 let scroll_position = snapshot.scroll_position();
13274 let scroll_left = scroll_position.x * em_width;
13275
13276 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13277 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13278 + self.gutter_dimensions.width;
13279 let y = line_height * (start.row().as_f32() - scroll_position.y);
13280
13281 Some(Bounds {
13282 origin: element_bounds.origin + point(x, y),
13283 size: size(em_width, line_height),
13284 })
13285 }
13286}
13287
13288trait SelectionExt {
13289 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13290 fn spanned_rows(
13291 &self,
13292 include_end_if_at_line_start: bool,
13293 map: &DisplaySnapshot,
13294 ) -> Range<MultiBufferRow>;
13295}
13296
13297impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13298 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13299 let start = self
13300 .start
13301 .to_point(&map.buffer_snapshot)
13302 .to_display_point(map);
13303 let end = self
13304 .end
13305 .to_point(&map.buffer_snapshot)
13306 .to_display_point(map);
13307 if self.reversed {
13308 end..start
13309 } else {
13310 start..end
13311 }
13312 }
13313
13314 fn spanned_rows(
13315 &self,
13316 include_end_if_at_line_start: bool,
13317 map: &DisplaySnapshot,
13318 ) -> Range<MultiBufferRow> {
13319 let start = self.start.to_point(&map.buffer_snapshot);
13320 let mut end = self.end.to_point(&map.buffer_snapshot);
13321 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13322 end.row -= 1;
13323 }
13324
13325 let buffer_start = map.prev_line_boundary(start).0;
13326 let buffer_end = map.next_line_boundary(end).0;
13327 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13328 }
13329}
13330
13331impl<T: InvalidationRegion> InvalidationStack<T> {
13332 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13333 where
13334 S: Clone + ToOffset,
13335 {
13336 while let Some(region) = self.last() {
13337 let all_selections_inside_invalidation_ranges =
13338 if selections.len() == region.ranges().len() {
13339 selections
13340 .iter()
13341 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13342 .all(|(selection, invalidation_range)| {
13343 let head = selection.head().to_offset(buffer);
13344 invalidation_range.start <= head && invalidation_range.end >= head
13345 })
13346 } else {
13347 false
13348 };
13349
13350 if all_selections_inside_invalidation_ranges {
13351 break;
13352 } else {
13353 self.pop();
13354 }
13355 }
13356 }
13357}
13358
13359impl<T> Default for InvalidationStack<T> {
13360 fn default() -> Self {
13361 Self(Default::default())
13362 }
13363}
13364
13365impl<T> Deref for InvalidationStack<T> {
13366 type Target = Vec<T>;
13367
13368 fn deref(&self) -> &Self::Target {
13369 &self.0
13370 }
13371}
13372
13373impl<T> DerefMut for InvalidationStack<T> {
13374 fn deref_mut(&mut self) -> &mut Self::Target {
13375 &mut self.0
13376 }
13377}
13378
13379impl InvalidationRegion for SnippetState {
13380 fn ranges(&self) -> &[Range<Anchor>] {
13381 &self.ranges[self.active_index]
13382 }
13383}
13384
13385pub fn diagnostic_block_renderer(
13386 diagnostic: Diagnostic,
13387 max_message_rows: Option<u8>,
13388 allow_closing: bool,
13389 _is_valid: bool,
13390) -> RenderBlock {
13391 let (text_without_backticks, code_ranges) =
13392 highlight_diagnostic_message(&diagnostic, max_message_rows);
13393
13394 Box::new(move |cx: &mut BlockContext| {
13395 let group_id: SharedString = cx.block_id.to_string().into();
13396
13397 let mut text_style = cx.text_style().clone();
13398 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13399 let theme_settings = ThemeSettings::get_global(cx);
13400 text_style.font_family = theme_settings.buffer_font.family.clone();
13401 text_style.font_style = theme_settings.buffer_font.style;
13402 text_style.font_features = theme_settings.buffer_font.features.clone();
13403 text_style.font_weight = theme_settings.buffer_font.weight;
13404
13405 let multi_line_diagnostic = diagnostic.message.contains('\n');
13406
13407 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13408 if multi_line_diagnostic {
13409 v_flex()
13410 } else {
13411 h_flex()
13412 }
13413 .when(allow_closing, |div| {
13414 div.children(diagnostic.is_primary.then(|| {
13415 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13416 .icon_color(Color::Muted)
13417 .size(ButtonSize::Compact)
13418 .style(ButtonStyle::Transparent)
13419 .visible_on_hover(group_id.clone())
13420 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13421 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13422 }))
13423 })
13424 .child(
13425 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13426 .icon_color(Color::Muted)
13427 .size(ButtonSize::Compact)
13428 .style(ButtonStyle::Transparent)
13429 .visible_on_hover(group_id.clone())
13430 .on_click({
13431 let message = diagnostic.message.clone();
13432 move |_click, cx| {
13433 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13434 }
13435 })
13436 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13437 )
13438 };
13439
13440 let icon_size = buttons(&diagnostic, cx.block_id)
13441 .into_any_element()
13442 .layout_as_root(AvailableSpace::min_size(), cx);
13443
13444 h_flex()
13445 .id(cx.block_id)
13446 .group(group_id.clone())
13447 .relative()
13448 .size_full()
13449 .pl(cx.gutter_dimensions.width)
13450 .w(cx.max_width + cx.gutter_dimensions.width)
13451 .child(
13452 div()
13453 .flex()
13454 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13455 .flex_shrink(),
13456 )
13457 .child(buttons(&diagnostic, cx.block_id))
13458 .child(div().flex().flex_shrink_0().child(
13459 StyledText::new(text_without_backticks.clone()).with_highlights(
13460 &text_style,
13461 code_ranges.iter().map(|range| {
13462 (
13463 range.clone(),
13464 HighlightStyle {
13465 font_weight: Some(FontWeight::BOLD),
13466 ..Default::default()
13467 },
13468 )
13469 }),
13470 ),
13471 ))
13472 .into_any_element()
13473 })
13474}
13475
13476pub fn highlight_diagnostic_message(
13477 diagnostic: &Diagnostic,
13478 mut max_message_rows: Option<u8>,
13479) -> (SharedString, Vec<Range<usize>>) {
13480 let mut text_without_backticks = String::new();
13481 let mut code_ranges = Vec::new();
13482
13483 if let Some(source) = &diagnostic.source {
13484 text_without_backticks.push_str(source);
13485 code_ranges.push(0..source.len());
13486 text_without_backticks.push_str(": ");
13487 }
13488
13489 let mut prev_offset = 0;
13490 let mut in_code_block = false;
13491 let has_row_limit = max_message_rows.is_some();
13492 let mut newline_indices = diagnostic
13493 .message
13494 .match_indices('\n')
13495 .filter(|_| has_row_limit)
13496 .map(|(ix, _)| ix)
13497 .fuse()
13498 .peekable();
13499
13500 for (quote_ix, _) in diagnostic
13501 .message
13502 .match_indices('`')
13503 .chain([(diagnostic.message.len(), "")])
13504 {
13505 let mut first_newline_ix = None;
13506 let mut last_newline_ix = None;
13507 while let Some(newline_ix) = newline_indices.peek() {
13508 if *newline_ix < quote_ix {
13509 if first_newline_ix.is_none() {
13510 first_newline_ix = Some(*newline_ix);
13511 }
13512 last_newline_ix = Some(*newline_ix);
13513
13514 if let Some(rows_left) = &mut max_message_rows {
13515 if *rows_left == 0 {
13516 break;
13517 } else {
13518 *rows_left -= 1;
13519 }
13520 }
13521 let _ = newline_indices.next();
13522 } else {
13523 break;
13524 }
13525 }
13526 let prev_len = text_without_backticks.len();
13527 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13528 text_without_backticks.push_str(new_text);
13529 if in_code_block {
13530 code_ranges.push(prev_len..text_without_backticks.len());
13531 }
13532 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13533 in_code_block = !in_code_block;
13534 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13535 text_without_backticks.push_str("...");
13536 break;
13537 }
13538 }
13539
13540 (text_without_backticks.into(), code_ranges)
13541}
13542
13543fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13544 match severity {
13545 DiagnosticSeverity::ERROR => colors.error,
13546 DiagnosticSeverity::WARNING => colors.warning,
13547 DiagnosticSeverity::INFORMATION => colors.info,
13548 DiagnosticSeverity::HINT => colors.info,
13549 _ => colors.ignored,
13550 }
13551}
13552
13553pub fn styled_runs_for_code_label<'a>(
13554 label: &'a CodeLabel,
13555 syntax_theme: &'a theme::SyntaxTheme,
13556) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13557 let fade_out = HighlightStyle {
13558 fade_out: Some(0.35),
13559 ..Default::default()
13560 };
13561
13562 let mut prev_end = label.filter_range.end;
13563 label
13564 .runs
13565 .iter()
13566 .enumerate()
13567 .flat_map(move |(ix, (range, highlight_id))| {
13568 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13569 style
13570 } else {
13571 return Default::default();
13572 };
13573 let mut muted_style = style;
13574 muted_style.highlight(fade_out);
13575
13576 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13577 if range.start >= label.filter_range.end {
13578 if range.start > prev_end {
13579 runs.push((prev_end..range.start, fade_out));
13580 }
13581 runs.push((range.clone(), muted_style));
13582 } else if range.end <= label.filter_range.end {
13583 runs.push((range.clone(), style));
13584 } else {
13585 runs.push((range.start..label.filter_range.end, style));
13586 runs.push((label.filter_range.end..range.end, muted_style));
13587 }
13588 prev_end = cmp::max(prev_end, range.end);
13589
13590 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13591 runs.push((prev_end..label.text.len(), fade_out));
13592 }
13593
13594 runs
13595 })
13596}
13597
13598pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13599 let mut prev_index = 0;
13600 let mut prev_codepoint: Option<char> = None;
13601 text.char_indices()
13602 .chain([(text.len(), '\0')])
13603 .filter_map(move |(index, codepoint)| {
13604 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13605 let is_boundary = index == text.len()
13606 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13607 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13608 if is_boundary {
13609 let chunk = &text[prev_index..index];
13610 prev_index = index;
13611 Some(chunk)
13612 } else {
13613 None
13614 }
13615 })
13616}
13617
13618pub trait RangeToAnchorExt: Sized {
13619 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13620
13621 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13622 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13623 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
13624 }
13625}
13626
13627impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13628 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13629 let start_offset = self.start.to_offset(snapshot);
13630 let end_offset = self.end.to_offset(snapshot);
13631 if start_offset == end_offset {
13632 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13633 } else {
13634 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13635 }
13636 }
13637}
13638
13639pub trait RowExt {
13640 fn as_f32(&self) -> f32;
13641
13642 fn next_row(&self) -> Self;
13643
13644 fn previous_row(&self) -> Self;
13645
13646 fn minus(&self, other: Self) -> u32;
13647}
13648
13649impl RowExt for DisplayRow {
13650 fn as_f32(&self) -> f32 {
13651 self.0 as f32
13652 }
13653
13654 fn next_row(&self) -> Self {
13655 Self(self.0 + 1)
13656 }
13657
13658 fn previous_row(&self) -> Self {
13659 Self(self.0.saturating_sub(1))
13660 }
13661
13662 fn minus(&self, other: Self) -> u32 {
13663 self.0 - other.0
13664 }
13665}
13666
13667impl RowExt for MultiBufferRow {
13668 fn as_f32(&self) -> f32 {
13669 self.0 as f32
13670 }
13671
13672 fn next_row(&self) -> Self {
13673 Self(self.0 + 1)
13674 }
13675
13676 fn previous_row(&self) -> Self {
13677 Self(self.0.saturating_sub(1))
13678 }
13679
13680 fn minus(&self, other: Self) -> u32 {
13681 self.0 - other.0
13682 }
13683}
13684
13685trait RowRangeExt {
13686 type Row;
13687
13688 fn len(&self) -> usize;
13689
13690 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13691}
13692
13693impl RowRangeExt for Range<MultiBufferRow> {
13694 type Row = MultiBufferRow;
13695
13696 fn len(&self) -> usize {
13697 (self.end.0 - self.start.0) as usize
13698 }
13699
13700 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13701 (self.start.0..self.end.0).map(MultiBufferRow)
13702 }
13703}
13704
13705impl RowRangeExt for Range<DisplayRow> {
13706 type Row = DisplayRow;
13707
13708 fn len(&self) -> usize {
13709 (self.end.0 - self.start.0) as usize
13710 }
13711
13712 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13713 (self.start.0..self.end.0).map(DisplayRow)
13714 }
13715}
13716
13717fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13718 if hunk.diff_base_byte_range.is_empty() {
13719 DiffHunkStatus::Added
13720 } else if hunk.associated_range.is_empty() {
13721 DiffHunkStatus::Removed
13722 } else {
13723 DiffHunkStatus::Modified
13724 }
13725}
13726
13727/// If select range has more than one line, we
13728/// just point the cursor to range.start.
13729fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13730 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13731 range
13732 } else {
13733 range.start..range.start
13734 }
13735}