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 proposed_changes_editor;
39mod rust_analyzer_ext;
40pub mod scroll;
41mod selections_collection;
42pub mod tasks;
43
44#[cfg(test)]
45mod editor_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50use ::git::diff::DiffHunkStatus;
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, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::LineWithInvisibles;
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{future, FutureExt};
71use fuzzy::{StringMatch, StringMatchCandidate};
72use git::blame::GitBlame;
73use gpui::{
74 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
75 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
76 ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
77 FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
78 ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString,
79 Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
80 TextStyleRefinement, UTF16Selection, UnderlineStyle, UniformListScrollHandle, View,
81 ViewContext, ViewInputHandler, VisualContext, WeakFocusHandle, WeakView, WindowContext,
82};
83use highlight_matching_bracket::refresh_matching_bracket_highlights;
84use hover_popover::{hide_hover, HoverState};
85pub(crate) use hunk_diff::HoveredHunk;
86use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
87use indent_guides::ActiveIndentGuidesState;
88use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
89pub use inline_completion_provider::*;
90pub use items::MAX_TAB_TITLE_LEN;
91use itertools::Itertools;
92use language::{
93 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
94 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
95 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
96 Point, Selection, SelectionGoal, TransactionId,
97};
98use language::{
99 point_to_lsp, BufferRow, CharClassifier, LanguageServerName, Runnable, RunnableRange,
100};
101use linked_editing_ranges::refresh_linked_ranges;
102pub use proposed_changes_editor::{
103 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
104};
105use similar::{ChangeTag, TextDiff};
106use task::{ResolvedTask, TaskTemplate, TaskVariables};
107
108use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
109pub use lsp::CompletionContext;
110use lsp::{
111 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
112 LanguageServerId,
113};
114use mouse_context_menu::MouseContextMenu;
115use movement::TextLayoutDetails;
116pub use multi_buffer::{
117 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
118 ToPoint,
119};
120use multi_buffer::{
121 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
122};
123use ordered_float::OrderedFloat;
124use parking_lot::{Mutex, RwLock};
125use project::{
126 lsp_store::{FormatTarget, FormatTrigger},
127 project_settings::{GitGutterSetting, ProjectSettings},
128 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
129 LocationLink, Project, ProjectPath, ProjectTransaction, TaskSourceKind,
130};
131use rand::prelude::*;
132use rpc::{proto::*, ErrorExt};
133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
134use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
135use serde::{Deserialize, Serialize};
136use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
137use smallvec::SmallVec;
138use snippet::Snippet;
139use std::{
140 any::TypeId,
141 borrow::Cow,
142 cell::RefCell,
143 cmp::{self, Ordering, Reverse},
144 mem,
145 num::NonZeroU32,
146 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
147 path::{Path, PathBuf},
148 rc::Rc,
149 sync::Arc,
150 time::{Duration, Instant},
151};
152pub use sum_tree::Bias;
153use sum_tree::TreeMap;
154use text::{BufferId, OffsetUtf16, Rope};
155use theme::{
156 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
157 ThemeColors, ThemeSettings,
158};
159use ui::{
160 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
161 ListItem, Popover, PopoverMenuHandle, Tooltip,
162};
163use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
164use workspace::item::{ItemHandle, PreviewTabsSettings};
165use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
166use workspace::{
167 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
168};
169use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
170
171use crate::hover_links::find_url;
172use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
173
174pub const FILE_HEADER_HEIGHT: u32 = 2;
175pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
176pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
177pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
178const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
179const MAX_LINE_LEN: usize = 1024;
180const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
181const MAX_SELECTION_HISTORY_LEN: usize = 1024;
182pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
183#[doc(hidden)]
184pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
185#[doc(hidden)]
186pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
187
188pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
189pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
190
191pub fn render_parsed_markdown(
192 element_id: impl Into<ElementId>,
193 parsed: &language::ParsedMarkdown,
194 editor_style: &EditorStyle,
195 workspace: Option<WeakView<Workspace>>,
196 cx: &mut WindowContext,
197) -> InteractiveText {
198 let code_span_background_color = cx
199 .theme()
200 .colors()
201 .editor_document_highlight_read_background;
202
203 let highlights = gpui::combine_highlights(
204 parsed.highlights.iter().filter_map(|(range, highlight)| {
205 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
206 Some((range.clone(), highlight))
207 }),
208 parsed
209 .regions
210 .iter()
211 .zip(&parsed.region_ranges)
212 .filter_map(|(region, range)| {
213 if region.code {
214 Some((
215 range.clone(),
216 HighlightStyle {
217 background_color: Some(code_span_background_color),
218 ..Default::default()
219 },
220 ))
221 } else {
222 None
223 }
224 }),
225 );
226
227 let mut links = Vec::new();
228 let mut link_ranges = Vec::new();
229 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
230 if let Some(link) = region.link.clone() {
231 links.push(link);
232 link_ranges.push(range.clone());
233 }
234 }
235
236 InteractiveText::new(
237 element_id,
238 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
239 )
240 .on_click(link_ranges, move |clicked_range_ix, cx| {
241 match &links[clicked_range_ix] {
242 markdown::Link::Web { url } => cx.open_url(url),
243 markdown::Link::Path { path } => {
244 if let Some(workspace) = &workspace {
245 _ = workspace.update(cx, |workspace, cx| {
246 workspace.open_abs_path(path.clone(), false, cx).detach();
247 });
248 }
249 }
250 }
251 })
252}
253
254#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
255pub(crate) enum InlayId {
256 Suggestion(usize),
257 Hint(usize),
258}
259
260impl InlayId {
261 fn id(&self) -> usize {
262 match self {
263 Self::Suggestion(id) => *id,
264 Self::Hint(id) => *id,
265 }
266 }
267}
268
269enum DiffRowHighlight {}
270enum DocumentHighlightRead {}
271enum DocumentHighlightWrite {}
272enum InputComposition {}
273
274#[derive(Copy, Clone, PartialEq, Eq)]
275pub enum Direction {
276 Prev,
277 Next,
278}
279
280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
281pub enum Navigated {
282 Yes,
283 No,
284}
285
286impl Navigated {
287 pub fn from_bool(yes: bool) -> Navigated {
288 if yes {
289 Navigated::Yes
290 } else {
291 Navigated::No
292 }
293 }
294}
295
296pub fn init_settings(cx: &mut AppContext) {
297 EditorSettings::register(cx);
298}
299
300pub fn init(cx: &mut AppContext) {
301 init_settings(cx);
302
303 workspace::register_project_item::<Editor>(cx);
304 workspace::FollowableViewRegistry::register::<Editor>(cx);
305 workspace::register_serializable_item::<Editor>(cx);
306
307 cx.observe_new_views(
308 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
309 workspace.register_action(Editor::new_file);
310 workspace.register_action(Editor::new_file_vertical);
311 workspace.register_action(Editor::new_file_horizontal);
312 },
313 )
314 .detach();
315
316 cx.on_action(move |_: &workspace::NewFile, cx| {
317 let app_state = workspace::AppState::global(cx);
318 if let Some(app_state) = app_state.upgrade() {
319 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
320 Editor::new_file(workspace, &Default::default(), cx)
321 })
322 .detach();
323 }
324 });
325 cx.on_action(move |_: &workspace::NewWindow, cx| {
326 let app_state = workspace::AppState::global(cx);
327 if let Some(app_state) = app_state.upgrade() {
328 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
329 Editor::new_file(workspace, &Default::default(), cx)
330 })
331 .detach();
332 }
333 });
334}
335
336pub struct SearchWithinRange;
337
338trait InvalidationRegion {
339 fn ranges(&self) -> &[Range<Anchor>];
340}
341
342#[derive(Clone, Debug, PartialEq)]
343pub enum SelectPhase {
344 Begin {
345 position: DisplayPoint,
346 add: bool,
347 click_count: usize,
348 },
349 BeginColumnar {
350 position: DisplayPoint,
351 reset: bool,
352 goal_column: u32,
353 },
354 Extend {
355 position: DisplayPoint,
356 click_count: usize,
357 },
358 Update {
359 position: DisplayPoint,
360 goal_column: u32,
361 scroll_delta: gpui::Point<f32>,
362 },
363 End,
364}
365
366#[derive(Clone, Debug)]
367pub enum SelectMode {
368 Character,
369 Word(Range<Anchor>),
370 Line(Range<Anchor>),
371 All,
372}
373
374#[derive(Copy, Clone, PartialEq, Eq, Debug)]
375pub enum EditorMode {
376 SingleLine { auto_width: bool },
377 AutoHeight { max_lines: usize },
378 Full,
379}
380
381#[derive(Copy, Clone, Debug)]
382pub enum SoftWrap {
383 /// Prefer not to wrap at all.
384 ///
385 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
386 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
387 GitDiff,
388 /// Prefer a single line generally, unless an overly long line is encountered.
389 None,
390 /// Soft wrap lines that exceed the editor width.
391 EditorWidth,
392 /// Soft wrap lines at the preferred line length.
393 Column(u32),
394 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
395 Bounded(u32),
396}
397
398#[derive(Clone)]
399pub struct EditorStyle {
400 pub background: Hsla,
401 pub local_player: PlayerColor,
402 pub text: TextStyle,
403 pub scrollbar_width: Pixels,
404 pub syntax: Arc<SyntaxTheme>,
405 pub status: StatusColors,
406 pub inlay_hints_style: HighlightStyle,
407 pub suggestions_style: HighlightStyle,
408 pub unnecessary_code_fade: f32,
409}
410
411impl Default for EditorStyle {
412 fn default() -> Self {
413 Self {
414 background: Hsla::default(),
415 local_player: PlayerColor::default(),
416 text: TextStyle::default(),
417 scrollbar_width: Pixels::default(),
418 syntax: Default::default(),
419 // HACK: Status colors don't have a real default.
420 // We should look into removing the status colors from the editor
421 // style and retrieve them directly from the theme.
422 status: StatusColors::dark(),
423 inlay_hints_style: HighlightStyle::default(),
424 suggestions_style: HighlightStyle::default(),
425 unnecessary_code_fade: Default::default(),
426 }
427 }
428}
429
430pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
431 let show_background = language_settings::language_settings(None, None, cx)
432 .inlay_hints
433 .show_background;
434
435 HighlightStyle {
436 color: Some(cx.theme().status().hint),
437 background_color: show_background.then(|| cx.theme().status().hint_background),
438 ..HighlightStyle::default()
439 }
440}
441
442type CompletionId = usize;
443
444#[derive(Clone, Debug)]
445struct CompletionState {
446 // render_inlay_ids represents the inlay hints that are inserted
447 // for rendering the inline completions. They may be discontinuous
448 // in the event that the completion provider returns some intersection
449 // with the existing content.
450 render_inlay_ids: Vec<InlayId>,
451 // text is the resulting rope that is inserted when the user accepts a completion.
452 text: Rope,
453 // position is the position of the cursor when the completion was triggered.
454 position: multi_buffer::Anchor,
455 // delete_range is the range of text that this completion state covers.
456 // if the completion is accepted, this range should be deleted.
457 delete_range: Option<Range<multi_buffer::Anchor>>,
458}
459
460#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
461struct EditorActionId(usize);
462
463impl EditorActionId {
464 pub fn post_inc(&mut self) -> Self {
465 let answer = self.0;
466
467 *self = Self(answer + 1);
468
469 Self(answer)
470 }
471}
472
473// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
474// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
475
476type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
477type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
478
479#[derive(Default)]
480struct ScrollbarMarkerState {
481 scrollbar_size: Size<Pixels>,
482 dirty: bool,
483 markers: Arc<[PaintQuad]>,
484 pending_refresh: Option<Task<Result<()>>>,
485}
486
487impl ScrollbarMarkerState {
488 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
489 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
490 }
491}
492
493#[derive(Clone, Debug)]
494struct RunnableTasks {
495 templates: Vec<(TaskSourceKind, TaskTemplate)>,
496 offset: MultiBufferOffset,
497 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
498 column: u32,
499 // Values of all named captures, including those starting with '_'
500 extra_variables: HashMap<String, String>,
501 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
502 context_range: Range<BufferOffset>,
503}
504
505#[derive(Clone)]
506struct ResolvedTasks {
507 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
508 position: Anchor,
509}
510#[derive(Copy, Clone, Debug)]
511struct MultiBufferOffset(usize);
512#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
513struct BufferOffset(usize);
514
515// Addons allow storing per-editor state in other crates (e.g. Vim)
516pub trait Addon: 'static {
517 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
518
519 fn to_any(&self) -> &dyn std::any::Any;
520}
521
522/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
523///
524/// See the [module level documentation](self) for more information.
525pub struct Editor {
526 focus_handle: FocusHandle,
527 last_focused_descendant: Option<WeakFocusHandle>,
528 /// The text buffer being edited
529 buffer: Model<MultiBuffer>,
530 /// Map of how text in the buffer should be displayed.
531 /// Handles soft wraps, folds, fake inlay text insertions, etc.
532 pub display_map: Model<DisplayMap>,
533 pub selections: SelectionsCollection,
534 pub scroll_manager: ScrollManager,
535 /// When inline assist editors are linked, they all render cursors because
536 /// typing enters text into each of them, even the ones that aren't focused.
537 pub(crate) show_cursor_when_unfocused: bool,
538 columnar_selection_tail: Option<Anchor>,
539 add_selections_state: Option<AddSelectionsState>,
540 select_next_state: Option<SelectNextState>,
541 select_prev_state: Option<SelectNextState>,
542 selection_history: SelectionHistory,
543 autoclose_regions: Vec<AutocloseRegion>,
544 snippet_stack: InvalidationStack<SnippetState>,
545 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
546 ime_transaction: Option<TransactionId>,
547 active_diagnostics: Option<ActiveDiagnosticGroup>,
548 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
549
550 project: Option<Model<Project>>,
551 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
552 completion_provider: Option<Box<dyn CompletionProvider>>,
553 collaboration_hub: Option<Box<dyn CollaborationHub>>,
554 blink_manager: Model<BlinkManager>,
555 show_cursor_names: bool,
556 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
557 pub show_local_selections: bool,
558 mode: EditorMode,
559 show_breadcrumbs: bool,
560 show_gutter: bool,
561 show_line_numbers: Option<bool>,
562 use_relative_line_numbers: Option<bool>,
563 show_git_diff_gutter: Option<bool>,
564 show_code_actions: Option<bool>,
565 show_runnables: Option<bool>,
566 show_wrap_guides: Option<bool>,
567 show_indent_guides: Option<bool>,
568 placeholder_text: Option<Arc<str>>,
569 highlight_order: usize,
570 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
571 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
572 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
573 scrollbar_marker_state: ScrollbarMarkerState,
574 active_indent_guides_state: ActiveIndentGuidesState,
575 nav_history: Option<ItemNavHistory>,
576 context_menu: RwLock<Option<ContextMenu>>,
577 mouse_context_menu: Option<MouseContextMenu>,
578 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
579 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
580 signature_help_state: SignatureHelpState,
581 auto_signature_help: Option<bool>,
582 find_all_references_task_sources: Vec<Anchor>,
583 next_completion_id: CompletionId,
584 completion_documentation_pre_resolve_debounce: DebouncedDelay,
585 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
586 code_actions_task: Option<Task<Result<()>>>,
587 document_highlights_task: Option<Task<()>>,
588 linked_editing_range_task: Option<Task<Option<()>>>,
589 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
590 pending_rename: Option<RenameState>,
591 searchable: bool,
592 cursor_shape: CursorShape,
593 current_line_highlight: Option<CurrentLineHighlight>,
594 collapse_matches: bool,
595 autoindent_mode: Option<AutoindentMode>,
596 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
597 input_enabled: bool,
598 use_modal_editing: bool,
599 read_only: bool,
600 leader_peer_id: Option<PeerId>,
601 remote_id: Option<ViewId>,
602 hover_state: HoverState,
603 gutter_hovered: bool,
604 hovered_link_state: Option<HoveredLinkState>,
605 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
606 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
607 active_inline_completion: Option<CompletionState>,
608 // enable_inline_completions is a switch that Vim can use to disable
609 // inline completions based on its mode.
610 enable_inline_completions: bool,
611 show_inline_completions_override: Option<bool>,
612 inlay_hint_cache: InlayHintCache,
613 expanded_hunks: ExpandedHunks,
614 next_inlay_id: usize,
615 _subscriptions: Vec<Subscription>,
616 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
617 gutter_dimensions: GutterDimensions,
618 style: Option<EditorStyle>,
619 text_style_refinement: Option<TextStyleRefinement>,
620 next_editor_action_id: EditorActionId,
621 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
622 use_autoclose: bool,
623 use_auto_surround: bool,
624 auto_replace_emoji_shortcode: bool,
625 show_git_blame_gutter: bool,
626 show_git_blame_inline: bool,
627 show_git_blame_inline_delay_task: Option<Task<()>>,
628 git_blame_inline_enabled: bool,
629 serialize_dirty_buffers: bool,
630 show_selection_menu: Option<bool>,
631 blame: Option<Model<GitBlame>>,
632 blame_subscription: Option<Subscription>,
633 custom_context_menu: Option<
634 Box<
635 dyn 'static
636 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
637 >,
638 >,
639 last_bounds: Option<Bounds<Pixels>>,
640 expect_bounds_change: Option<Bounds<Pixels>>,
641 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
642 tasks_update_task: Option<Task<()>>,
643 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
644 breadcrumb_header: Option<String>,
645 focused_block: Option<FocusedBlock>,
646 next_scroll_position: NextScrollCursorCenterTopBottom,
647 addons: HashMap<TypeId, Box<dyn Addon>>,
648 _scroll_cursor_center_top_bottom_task: Task<()>,
649}
650
651#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
652enum NextScrollCursorCenterTopBottom {
653 #[default]
654 Center,
655 Top,
656 Bottom,
657}
658
659impl NextScrollCursorCenterTopBottom {
660 fn next(&self) -> Self {
661 match self {
662 Self::Center => Self::Top,
663 Self::Top => Self::Bottom,
664 Self::Bottom => Self::Center,
665 }
666 }
667}
668
669#[derive(Clone)]
670pub struct EditorSnapshot {
671 pub mode: EditorMode,
672 show_gutter: bool,
673 show_line_numbers: Option<bool>,
674 show_git_diff_gutter: Option<bool>,
675 show_code_actions: Option<bool>,
676 show_runnables: Option<bool>,
677 git_blame_gutter_max_author_length: Option<usize>,
678 pub display_snapshot: DisplaySnapshot,
679 pub placeholder_text: Option<Arc<str>>,
680 is_focused: bool,
681 scroll_anchor: ScrollAnchor,
682 ongoing_scroll: OngoingScroll,
683 current_line_highlight: CurrentLineHighlight,
684 gutter_hovered: bool,
685}
686
687const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
688
689#[derive(Default, Debug, Clone, Copy)]
690pub struct GutterDimensions {
691 pub left_padding: Pixels,
692 pub right_padding: Pixels,
693 pub width: Pixels,
694 pub margin: Pixels,
695 pub git_blame_entries_width: Option<Pixels>,
696}
697
698impl GutterDimensions {
699 /// The full width of the space taken up by the gutter.
700 pub fn full_width(&self) -> Pixels {
701 self.margin + self.width
702 }
703
704 /// The width of the space reserved for the fold indicators,
705 /// use alongside 'justify_end' and `gutter_width` to
706 /// right align content with the line numbers
707 pub fn fold_area_width(&self) -> Pixels {
708 self.margin + self.right_padding
709 }
710}
711
712#[derive(Debug)]
713pub struct RemoteSelection {
714 pub replica_id: ReplicaId,
715 pub selection: Selection<Anchor>,
716 pub cursor_shape: CursorShape,
717 pub peer_id: PeerId,
718 pub line_mode: bool,
719 pub participant_index: Option<ParticipantIndex>,
720 pub user_name: Option<SharedString>,
721}
722
723#[derive(Clone, Debug)]
724struct SelectionHistoryEntry {
725 selections: Arc<[Selection<Anchor>]>,
726 select_next_state: Option<SelectNextState>,
727 select_prev_state: Option<SelectNextState>,
728 add_selections_state: Option<AddSelectionsState>,
729}
730
731enum SelectionHistoryMode {
732 Normal,
733 Undoing,
734 Redoing,
735}
736
737#[derive(Clone, PartialEq, Eq, Hash)]
738struct HoveredCursor {
739 replica_id: u16,
740 selection_id: usize,
741}
742
743impl Default for SelectionHistoryMode {
744 fn default() -> Self {
745 Self::Normal
746 }
747}
748
749#[derive(Default)]
750struct SelectionHistory {
751 #[allow(clippy::type_complexity)]
752 selections_by_transaction:
753 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
754 mode: SelectionHistoryMode,
755 undo_stack: VecDeque<SelectionHistoryEntry>,
756 redo_stack: VecDeque<SelectionHistoryEntry>,
757}
758
759impl SelectionHistory {
760 fn insert_transaction(
761 &mut self,
762 transaction_id: TransactionId,
763 selections: Arc<[Selection<Anchor>]>,
764 ) {
765 self.selections_by_transaction
766 .insert(transaction_id, (selections, None));
767 }
768
769 #[allow(clippy::type_complexity)]
770 fn transaction(
771 &self,
772 transaction_id: TransactionId,
773 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
774 self.selections_by_transaction.get(&transaction_id)
775 }
776
777 #[allow(clippy::type_complexity)]
778 fn transaction_mut(
779 &mut self,
780 transaction_id: TransactionId,
781 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
782 self.selections_by_transaction.get_mut(&transaction_id)
783 }
784
785 fn push(&mut self, entry: SelectionHistoryEntry) {
786 if !entry.selections.is_empty() {
787 match self.mode {
788 SelectionHistoryMode::Normal => {
789 self.push_undo(entry);
790 self.redo_stack.clear();
791 }
792 SelectionHistoryMode::Undoing => self.push_redo(entry),
793 SelectionHistoryMode::Redoing => self.push_undo(entry),
794 }
795 }
796 }
797
798 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
799 if self
800 .undo_stack
801 .back()
802 .map_or(true, |e| e.selections != entry.selections)
803 {
804 self.undo_stack.push_back(entry);
805 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
806 self.undo_stack.pop_front();
807 }
808 }
809 }
810
811 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
812 if self
813 .redo_stack
814 .back()
815 .map_or(true, |e| e.selections != entry.selections)
816 {
817 self.redo_stack.push_back(entry);
818 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
819 self.redo_stack.pop_front();
820 }
821 }
822 }
823}
824
825struct RowHighlight {
826 index: usize,
827 range: Range<Anchor>,
828 color: Hsla,
829 should_autoscroll: bool,
830}
831
832#[derive(Clone, Debug)]
833struct AddSelectionsState {
834 above: bool,
835 stack: Vec<usize>,
836}
837
838#[derive(Clone)]
839struct SelectNextState {
840 query: AhoCorasick,
841 wordwise: bool,
842 done: bool,
843}
844
845impl std::fmt::Debug for SelectNextState {
846 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
847 f.debug_struct(std::any::type_name::<Self>())
848 .field("wordwise", &self.wordwise)
849 .field("done", &self.done)
850 .finish()
851 }
852}
853
854#[derive(Debug)]
855struct AutocloseRegion {
856 selection_id: usize,
857 range: Range<Anchor>,
858 pair: BracketPair,
859}
860
861#[derive(Debug)]
862struct SnippetState {
863 ranges: Vec<Vec<Range<Anchor>>>,
864 active_index: usize,
865}
866
867#[doc(hidden)]
868pub struct RenameState {
869 pub range: Range<Anchor>,
870 pub old_name: Arc<str>,
871 pub editor: View<Editor>,
872 block_id: CustomBlockId,
873}
874
875struct InvalidationStack<T>(Vec<T>);
876
877struct RegisteredInlineCompletionProvider {
878 provider: Arc<dyn InlineCompletionProviderHandle>,
879 _subscription: Subscription,
880}
881
882enum ContextMenu {
883 Completions(CompletionsMenu),
884 CodeActions(CodeActionsMenu),
885}
886
887impl ContextMenu {
888 fn select_first(
889 &mut self,
890 provider: Option<&dyn CompletionProvider>,
891 cx: &mut ViewContext<Editor>,
892 ) -> bool {
893 if self.visible() {
894 match self {
895 ContextMenu::Completions(menu) => menu.select_first(provider, cx),
896 ContextMenu::CodeActions(menu) => menu.select_first(cx),
897 }
898 true
899 } else {
900 false
901 }
902 }
903
904 fn select_prev(
905 &mut self,
906 provider: Option<&dyn CompletionProvider>,
907 cx: &mut ViewContext<Editor>,
908 ) -> bool {
909 if self.visible() {
910 match self {
911 ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
912 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
913 }
914 true
915 } else {
916 false
917 }
918 }
919
920 fn select_next(
921 &mut self,
922 provider: Option<&dyn CompletionProvider>,
923 cx: &mut ViewContext<Editor>,
924 ) -> bool {
925 if self.visible() {
926 match self {
927 ContextMenu::Completions(menu) => menu.select_next(provider, cx),
928 ContextMenu::CodeActions(menu) => menu.select_next(cx),
929 }
930 true
931 } else {
932 false
933 }
934 }
935
936 fn select_last(
937 &mut self,
938 provider: Option<&dyn CompletionProvider>,
939 cx: &mut ViewContext<Editor>,
940 ) -> bool {
941 if self.visible() {
942 match self {
943 ContextMenu::Completions(menu) => menu.select_last(provider, cx),
944 ContextMenu::CodeActions(menu) => menu.select_last(cx),
945 }
946 true
947 } else {
948 false
949 }
950 }
951
952 fn visible(&self) -> bool {
953 match self {
954 ContextMenu::Completions(menu) => menu.visible(),
955 ContextMenu::CodeActions(menu) => menu.visible(),
956 }
957 }
958
959 fn render(
960 &self,
961 cursor_position: DisplayPoint,
962 style: &EditorStyle,
963 max_height: Pixels,
964 workspace: Option<WeakView<Workspace>>,
965 cx: &mut ViewContext<Editor>,
966 ) -> (ContextMenuOrigin, AnyElement) {
967 match self {
968 ContextMenu::Completions(menu) => (
969 ContextMenuOrigin::EditorPoint(cursor_position),
970 menu.render(style, max_height, workspace, cx),
971 ),
972 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
973 }
974 }
975}
976
977enum ContextMenuOrigin {
978 EditorPoint(DisplayPoint),
979 GutterIndicator(DisplayRow),
980}
981
982#[derive(Clone)]
983struct CompletionsMenu {
984 id: CompletionId,
985 sort_completions: bool,
986 initial_position: Anchor,
987 buffer: Model<Buffer>,
988 completions: Arc<RwLock<Box<[Completion]>>>,
989 match_candidates: Arc<[StringMatchCandidate]>,
990 matches: Arc<[StringMatch]>,
991 selected_item: usize,
992 scroll_handle: UniformListScrollHandle,
993 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
994}
995
996impl CompletionsMenu {
997 fn select_first(
998 &mut self,
999 provider: Option<&dyn CompletionProvider>,
1000 cx: &mut ViewContext<Editor>,
1001 ) {
1002 self.selected_item = 0;
1003 self.scroll_handle.scroll_to_item(self.selected_item);
1004 self.attempt_resolve_selected_completion_documentation(provider, cx);
1005 cx.notify();
1006 }
1007
1008 fn select_prev(
1009 &mut self,
1010 provider: Option<&dyn CompletionProvider>,
1011 cx: &mut ViewContext<Editor>,
1012 ) {
1013 if self.selected_item > 0 {
1014 self.selected_item -= 1;
1015 } else {
1016 self.selected_item = self.matches.len() - 1;
1017 }
1018 self.scroll_handle.scroll_to_item(self.selected_item);
1019 self.attempt_resolve_selected_completion_documentation(provider, cx);
1020 cx.notify();
1021 }
1022
1023 fn select_next(
1024 &mut self,
1025 provider: Option<&dyn CompletionProvider>,
1026 cx: &mut ViewContext<Editor>,
1027 ) {
1028 if self.selected_item + 1 < self.matches.len() {
1029 self.selected_item += 1;
1030 } else {
1031 self.selected_item = 0;
1032 }
1033 self.scroll_handle.scroll_to_item(self.selected_item);
1034 self.attempt_resolve_selected_completion_documentation(provider, cx);
1035 cx.notify();
1036 }
1037
1038 fn select_last(
1039 &mut self,
1040 provider: Option<&dyn CompletionProvider>,
1041 cx: &mut ViewContext<Editor>,
1042 ) {
1043 self.selected_item = self.matches.len() - 1;
1044 self.scroll_handle.scroll_to_item(self.selected_item);
1045 self.attempt_resolve_selected_completion_documentation(provider, cx);
1046 cx.notify();
1047 }
1048
1049 fn pre_resolve_completion_documentation(
1050 buffer: Model<Buffer>,
1051 completions: Arc<RwLock<Box<[Completion]>>>,
1052 matches: Arc<[StringMatch]>,
1053 editor: &Editor,
1054 cx: &mut ViewContext<Editor>,
1055 ) -> Task<()> {
1056 let settings = EditorSettings::get_global(cx);
1057 if !settings.show_completion_documentation {
1058 return Task::ready(());
1059 }
1060
1061 let Some(provider) = editor.completion_provider.as_ref() else {
1062 return Task::ready(());
1063 };
1064
1065 let resolve_task = provider.resolve_completions(
1066 buffer,
1067 matches.iter().map(|m| m.candidate_id).collect(),
1068 completions.clone(),
1069 cx,
1070 );
1071
1072 cx.spawn(move |this, mut cx| async move {
1073 if let Some(true) = resolve_task.await.log_err() {
1074 this.update(&mut cx, |_, cx| cx.notify()).ok();
1075 }
1076 })
1077 }
1078
1079 fn attempt_resolve_selected_completion_documentation(
1080 &mut self,
1081 provider: Option<&dyn CompletionProvider>,
1082 cx: &mut ViewContext<Editor>,
1083 ) {
1084 let settings = EditorSettings::get_global(cx);
1085 if !settings.show_completion_documentation {
1086 return;
1087 }
1088
1089 let completion_index = self.matches[self.selected_item].candidate_id;
1090 let Some(provider) = provider else {
1091 return;
1092 };
1093
1094 let resolve_task = provider.resolve_completions(
1095 self.buffer.clone(),
1096 vec![completion_index],
1097 self.completions.clone(),
1098 cx,
1099 );
1100
1101 let delay_ms =
1102 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1103 let delay = Duration::from_millis(delay_ms);
1104
1105 self.selected_completion_documentation_resolve_debounce
1106 .lock()
1107 .fire_new(delay, cx, |_, cx| {
1108 cx.spawn(move |this, mut cx| async move {
1109 if let Some(true) = resolve_task.await.log_err() {
1110 this.update(&mut cx, |_, cx| cx.notify()).ok();
1111 }
1112 })
1113 });
1114 }
1115
1116 fn visible(&self) -> bool {
1117 !self.matches.is_empty()
1118 }
1119
1120 fn render(
1121 &self,
1122 style: &EditorStyle,
1123 max_height: Pixels,
1124 workspace: Option<WeakView<Workspace>>,
1125 cx: &mut ViewContext<Editor>,
1126 ) -> AnyElement {
1127 let settings = EditorSettings::get_global(cx);
1128 let show_completion_documentation = settings.show_completion_documentation;
1129
1130 let widest_completion_ix = self
1131 .matches
1132 .iter()
1133 .enumerate()
1134 .max_by_key(|(_, mat)| {
1135 let completions = self.completions.read();
1136 let completion = &completions[mat.candidate_id];
1137 let documentation = &completion.documentation;
1138
1139 let mut len = completion.label.text.chars().count();
1140 if let Some(Documentation::SingleLine(text)) = documentation {
1141 if show_completion_documentation {
1142 len += text.chars().count();
1143 }
1144 }
1145
1146 len
1147 })
1148 .map(|(ix, _)| ix);
1149
1150 let completions = self.completions.clone();
1151 let matches = self.matches.clone();
1152 let selected_item = self.selected_item;
1153 let style = style.clone();
1154
1155 let multiline_docs = if show_completion_documentation {
1156 let mat = &self.matches[selected_item];
1157 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1158 Some(Documentation::MultiLinePlainText(text)) => {
1159 Some(div().child(SharedString::from(text.clone())))
1160 }
1161 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1162 Some(div().child(render_parsed_markdown(
1163 "completions_markdown",
1164 parsed,
1165 &style,
1166 workspace,
1167 cx,
1168 )))
1169 }
1170 _ => None,
1171 };
1172 multiline_docs.map(|div| {
1173 div.id("multiline_docs")
1174 .max_h(max_height)
1175 .flex_1()
1176 .px_1p5()
1177 .py_1()
1178 .min_w(px(260.))
1179 .max_w(px(640.))
1180 .w(px(500.))
1181 .overflow_y_scroll()
1182 .occlude()
1183 })
1184 } else {
1185 None
1186 };
1187
1188 let list = uniform_list(
1189 cx.view().clone(),
1190 "completions",
1191 matches.len(),
1192 move |_editor, range, cx| {
1193 let start_ix = range.start;
1194 let completions_guard = completions.read();
1195
1196 matches[range]
1197 .iter()
1198 .enumerate()
1199 .map(|(ix, mat)| {
1200 let item_ix = start_ix + ix;
1201 let candidate_id = mat.candidate_id;
1202 let completion = &completions_guard[candidate_id];
1203
1204 let documentation = if show_completion_documentation {
1205 &completion.documentation
1206 } else {
1207 &None
1208 };
1209
1210 let highlights = gpui::combine_highlights(
1211 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1212 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1213 |(range, mut highlight)| {
1214 // Ignore font weight for syntax highlighting, as we'll use it
1215 // for fuzzy matches.
1216 highlight.font_weight = None;
1217
1218 if completion.lsp_completion.deprecated.unwrap_or(false) {
1219 highlight.strikethrough = Some(StrikethroughStyle {
1220 thickness: 1.0.into(),
1221 ..Default::default()
1222 });
1223 highlight.color = Some(cx.theme().colors().text_muted);
1224 }
1225
1226 (range, highlight)
1227 },
1228 ),
1229 );
1230 let completion_label = StyledText::new(completion.label.text.clone())
1231 .with_highlights(&style.text, highlights);
1232 let documentation_label =
1233 if let Some(Documentation::SingleLine(text)) = documentation {
1234 if text.trim().is_empty() {
1235 None
1236 } else {
1237 Some(
1238 Label::new(text.clone())
1239 .ml_4()
1240 .size(LabelSize::Small)
1241 .color(Color::Muted),
1242 )
1243 }
1244 } else {
1245 None
1246 };
1247
1248 let color_swatch = completion
1249 .color()
1250 .map(|color| div().size_4().bg(color).rounded_sm());
1251
1252 div().min_w(px(220.)).max_w(px(540.)).child(
1253 ListItem::new(mat.candidate_id)
1254 .inset(true)
1255 .selected(item_ix == selected_item)
1256 .on_click(cx.listener(move |editor, _event, cx| {
1257 cx.stop_propagation();
1258 if let Some(task) = editor.confirm_completion(
1259 &ConfirmCompletion {
1260 item_ix: Some(item_ix),
1261 },
1262 cx,
1263 ) {
1264 task.detach_and_log_err(cx)
1265 }
1266 }))
1267 .start_slot::<Div>(color_swatch)
1268 .child(h_flex().overflow_hidden().child(completion_label))
1269 .end_slot::<Label>(documentation_label),
1270 )
1271 })
1272 .collect()
1273 },
1274 )
1275 .occlude()
1276 .max_h(max_height)
1277 .track_scroll(self.scroll_handle.clone())
1278 .with_width_from_item(widest_completion_ix)
1279 .with_sizing_behavior(ListSizingBehavior::Infer);
1280
1281 Popover::new()
1282 .child(list)
1283 .when_some(multiline_docs, |popover, multiline_docs| {
1284 popover.aside(multiline_docs)
1285 })
1286 .into_any_element()
1287 }
1288
1289 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1290 let mut matches = if let Some(query) = query {
1291 fuzzy::match_strings(
1292 &self.match_candidates,
1293 query,
1294 query.chars().any(|c| c.is_uppercase()),
1295 100,
1296 &Default::default(),
1297 executor,
1298 )
1299 .await
1300 } else {
1301 self.match_candidates
1302 .iter()
1303 .enumerate()
1304 .map(|(candidate_id, candidate)| StringMatch {
1305 candidate_id,
1306 score: Default::default(),
1307 positions: Default::default(),
1308 string: candidate.string.clone(),
1309 })
1310 .collect()
1311 };
1312
1313 // Remove all candidates where the query's start does not match the start of any word in the candidate
1314 if let Some(query) = query {
1315 if let Some(query_start) = query.chars().next() {
1316 matches.retain(|string_match| {
1317 split_words(&string_match.string).any(|word| {
1318 // Check that the first codepoint of the word as lowercase matches the first
1319 // codepoint of the query as lowercase
1320 word.chars()
1321 .flat_map(|codepoint| codepoint.to_lowercase())
1322 .zip(query_start.to_lowercase())
1323 .all(|(word_cp, query_cp)| word_cp == query_cp)
1324 })
1325 });
1326 }
1327 }
1328
1329 let completions = self.completions.read();
1330 if self.sort_completions {
1331 matches.sort_unstable_by_key(|mat| {
1332 // We do want to strike a balance here between what the language server tells us
1333 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1334 // `Creat` and there is a local variable called `CreateComponent`).
1335 // So what we do is: we bucket all matches into two buckets
1336 // - Strong matches
1337 // - Weak matches
1338 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1339 // and the Weak matches are the rest.
1340 //
1341 // For the strong matches, we sort by the language-servers score first and for the weak
1342 // matches, we prefer our fuzzy finder first.
1343 //
1344 // The thinking behind that: it's useless to take the sort_text the language-server gives
1345 // us into account when it's obviously a bad match.
1346
1347 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1348 enum MatchScore<'a> {
1349 Strong {
1350 sort_text: Option<&'a str>,
1351 score: Reverse<OrderedFloat<f64>>,
1352 sort_key: (usize, &'a str),
1353 },
1354 Weak {
1355 score: Reverse<OrderedFloat<f64>>,
1356 sort_text: Option<&'a str>,
1357 sort_key: (usize, &'a str),
1358 },
1359 }
1360
1361 let completion = &completions[mat.candidate_id];
1362 let sort_key = completion.sort_key();
1363 let sort_text = completion.lsp_completion.sort_text.as_deref();
1364 let score = Reverse(OrderedFloat(mat.score));
1365
1366 if mat.score >= 0.2 {
1367 MatchScore::Strong {
1368 sort_text,
1369 score,
1370 sort_key,
1371 }
1372 } else {
1373 MatchScore::Weak {
1374 score,
1375 sort_text,
1376 sort_key,
1377 }
1378 }
1379 });
1380 }
1381
1382 for mat in &mut matches {
1383 let completion = &completions[mat.candidate_id];
1384 mat.string.clone_from(&completion.label.text);
1385 for position in &mut mat.positions {
1386 *position += completion.label.filter_range.start;
1387 }
1388 }
1389 drop(completions);
1390
1391 self.matches = matches.into();
1392 self.selected_item = 0;
1393 }
1394}
1395
1396struct AvailableCodeAction {
1397 excerpt_id: ExcerptId,
1398 action: CodeAction,
1399 provider: Arc<dyn CodeActionProvider>,
1400}
1401
1402#[derive(Clone)]
1403struct CodeActionContents {
1404 tasks: Option<Arc<ResolvedTasks>>,
1405 actions: Option<Arc<[AvailableCodeAction]>>,
1406}
1407
1408impl CodeActionContents {
1409 fn len(&self) -> usize {
1410 match (&self.tasks, &self.actions) {
1411 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1412 (Some(tasks), None) => tasks.templates.len(),
1413 (None, Some(actions)) => actions.len(),
1414 (None, None) => 0,
1415 }
1416 }
1417
1418 fn is_empty(&self) -> bool {
1419 match (&self.tasks, &self.actions) {
1420 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1421 (Some(tasks), None) => tasks.templates.is_empty(),
1422 (None, Some(actions)) => actions.is_empty(),
1423 (None, None) => true,
1424 }
1425 }
1426
1427 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1428 self.tasks
1429 .iter()
1430 .flat_map(|tasks| {
1431 tasks
1432 .templates
1433 .iter()
1434 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1435 })
1436 .chain(self.actions.iter().flat_map(|actions| {
1437 actions.iter().map(|available| CodeActionsItem::CodeAction {
1438 excerpt_id: available.excerpt_id,
1439 action: available.action.clone(),
1440 provider: available.provider.clone(),
1441 })
1442 }))
1443 }
1444 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1445 match (&self.tasks, &self.actions) {
1446 (Some(tasks), Some(actions)) => {
1447 if index < tasks.templates.len() {
1448 tasks
1449 .templates
1450 .get(index)
1451 .cloned()
1452 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1453 } else {
1454 actions.get(index - tasks.templates.len()).map(|available| {
1455 CodeActionsItem::CodeAction {
1456 excerpt_id: available.excerpt_id,
1457 action: available.action.clone(),
1458 provider: available.provider.clone(),
1459 }
1460 })
1461 }
1462 }
1463 (Some(tasks), None) => tasks
1464 .templates
1465 .get(index)
1466 .cloned()
1467 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1468 (None, Some(actions)) => {
1469 actions
1470 .get(index)
1471 .map(|available| CodeActionsItem::CodeAction {
1472 excerpt_id: available.excerpt_id,
1473 action: available.action.clone(),
1474 provider: available.provider.clone(),
1475 })
1476 }
1477 (None, None) => None,
1478 }
1479 }
1480}
1481
1482#[allow(clippy::large_enum_variant)]
1483#[derive(Clone)]
1484enum CodeActionsItem {
1485 Task(TaskSourceKind, ResolvedTask),
1486 CodeAction {
1487 excerpt_id: ExcerptId,
1488 action: CodeAction,
1489 provider: Arc<dyn CodeActionProvider>,
1490 },
1491}
1492
1493impl CodeActionsItem {
1494 fn as_task(&self) -> Option<&ResolvedTask> {
1495 let Self::Task(_, task) = self else {
1496 return None;
1497 };
1498 Some(task)
1499 }
1500 fn as_code_action(&self) -> Option<&CodeAction> {
1501 let Self::CodeAction { action, .. } = self else {
1502 return None;
1503 };
1504 Some(action)
1505 }
1506 fn label(&self) -> String {
1507 match self {
1508 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1509 Self::Task(_, task) => task.resolved_label.clone(),
1510 }
1511 }
1512}
1513
1514struct CodeActionsMenu {
1515 actions: CodeActionContents,
1516 buffer: Model<Buffer>,
1517 selected_item: usize,
1518 scroll_handle: UniformListScrollHandle,
1519 deployed_from_indicator: Option<DisplayRow>,
1520}
1521
1522impl CodeActionsMenu {
1523 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1524 self.selected_item = 0;
1525 self.scroll_handle.scroll_to_item(self.selected_item);
1526 cx.notify()
1527 }
1528
1529 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1530 if self.selected_item > 0 {
1531 self.selected_item -= 1;
1532 } else {
1533 self.selected_item = self.actions.len() - 1;
1534 }
1535 self.scroll_handle.scroll_to_item(self.selected_item);
1536 cx.notify();
1537 }
1538
1539 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1540 if self.selected_item + 1 < self.actions.len() {
1541 self.selected_item += 1;
1542 } else {
1543 self.selected_item = 0;
1544 }
1545 self.scroll_handle.scroll_to_item(self.selected_item);
1546 cx.notify();
1547 }
1548
1549 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1550 self.selected_item = self.actions.len() - 1;
1551 self.scroll_handle.scroll_to_item(self.selected_item);
1552 cx.notify()
1553 }
1554
1555 fn visible(&self) -> bool {
1556 !self.actions.is_empty()
1557 }
1558
1559 fn render(
1560 &self,
1561 cursor_position: DisplayPoint,
1562 _style: &EditorStyle,
1563 max_height: Pixels,
1564 cx: &mut ViewContext<Editor>,
1565 ) -> (ContextMenuOrigin, AnyElement) {
1566 let actions = self.actions.clone();
1567 let selected_item = self.selected_item;
1568 let element = uniform_list(
1569 cx.view().clone(),
1570 "code_actions_menu",
1571 self.actions.len(),
1572 move |_this, range, cx| {
1573 actions
1574 .iter()
1575 .skip(range.start)
1576 .take(range.end - range.start)
1577 .enumerate()
1578 .map(|(ix, action)| {
1579 let item_ix = range.start + ix;
1580 let selected = selected_item == item_ix;
1581 let colors = cx.theme().colors();
1582 div()
1583 .px_1()
1584 .rounded_md()
1585 .text_color(colors.text)
1586 .when(selected, |style| {
1587 style
1588 .bg(colors.element_active)
1589 .text_color(colors.text_accent)
1590 })
1591 .hover(|style| {
1592 style
1593 .bg(colors.element_hover)
1594 .text_color(colors.text_accent)
1595 })
1596 .whitespace_nowrap()
1597 .when_some(action.as_code_action(), |this, action| {
1598 this.on_mouse_down(
1599 MouseButton::Left,
1600 cx.listener(move |editor, _, cx| {
1601 cx.stop_propagation();
1602 if let Some(task) = editor.confirm_code_action(
1603 &ConfirmCodeAction {
1604 item_ix: Some(item_ix),
1605 },
1606 cx,
1607 ) {
1608 task.detach_and_log_err(cx)
1609 }
1610 }),
1611 )
1612 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1613 .child(SharedString::from(action.lsp_action.title.clone()))
1614 })
1615 .when_some(action.as_task(), |this, task| {
1616 this.on_mouse_down(
1617 MouseButton::Left,
1618 cx.listener(move |editor, _, cx| {
1619 cx.stop_propagation();
1620 if let Some(task) = editor.confirm_code_action(
1621 &ConfirmCodeAction {
1622 item_ix: Some(item_ix),
1623 },
1624 cx,
1625 ) {
1626 task.detach_and_log_err(cx)
1627 }
1628 }),
1629 )
1630 .child(SharedString::from(task.resolved_label.clone()))
1631 })
1632 })
1633 .collect()
1634 },
1635 )
1636 .elevation_1(cx)
1637 .p_1()
1638 .max_h(max_height)
1639 .occlude()
1640 .track_scroll(self.scroll_handle.clone())
1641 .with_width_from_item(
1642 self.actions
1643 .iter()
1644 .enumerate()
1645 .max_by_key(|(_, action)| match action {
1646 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1647 CodeActionsItem::CodeAction { action, .. } => {
1648 action.lsp_action.title.chars().count()
1649 }
1650 })
1651 .map(|(ix, _)| ix),
1652 )
1653 .with_sizing_behavior(ListSizingBehavior::Infer)
1654 .into_any_element();
1655
1656 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1657 ContextMenuOrigin::GutterIndicator(row)
1658 } else {
1659 ContextMenuOrigin::EditorPoint(cursor_position)
1660 };
1661
1662 (cursor_position, element)
1663 }
1664}
1665
1666#[derive(Debug)]
1667struct ActiveDiagnosticGroup {
1668 primary_range: Range<Anchor>,
1669 primary_message: String,
1670 group_id: usize,
1671 blocks: HashMap<CustomBlockId, Diagnostic>,
1672 is_valid: bool,
1673}
1674
1675#[derive(Serialize, Deserialize, Clone, Debug)]
1676pub struct ClipboardSelection {
1677 pub len: usize,
1678 pub is_entire_line: bool,
1679 pub first_line_indent: u32,
1680}
1681
1682#[derive(Debug)]
1683pub(crate) struct NavigationData {
1684 cursor_anchor: Anchor,
1685 cursor_position: Point,
1686 scroll_anchor: ScrollAnchor,
1687 scroll_top_row: u32,
1688}
1689
1690#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1691pub enum GotoDefinitionKind {
1692 Symbol,
1693 Declaration,
1694 Type,
1695 Implementation,
1696}
1697
1698#[derive(Debug, Clone)]
1699enum InlayHintRefreshReason {
1700 Toggle(bool),
1701 SettingsChange(InlayHintSettings),
1702 NewLinesShown,
1703 BufferEdited(HashSet<Arc<Language>>),
1704 RefreshRequested,
1705 ExcerptsRemoved(Vec<ExcerptId>),
1706}
1707
1708impl InlayHintRefreshReason {
1709 fn description(&self) -> &'static str {
1710 match self {
1711 Self::Toggle(_) => "toggle",
1712 Self::SettingsChange(_) => "settings change",
1713 Self::NewLinesShown => "new lines shown",
1714 Self::BufferEdited(_) => "buffer edited",
1715 Self::RefreshRequested => "refresh requested",
1716 Self::ExcerptsRemoved(_) => "excerpts removed",
1717 }
1718 }
1719}
1720
1721pub(crate) struct FocusedBlock {
1722 id: BlockId,
1723 focus_handle: WeakFocusHandle,
1724}
1725
1726impl Editor {
1727 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1728 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1729 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1730 Self::new(
1731 EditorMode::SingleLine { auto_width: false },
1732 buffer,
1733 None,
1734 false,
1735 cx,
1736 )
1737 }
1738
1739 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1740 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1741 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1742 Self::new(EditorMode::Full, buffer, None, false, cx)
1743 }
1744
1745 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1746 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1747 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1748 Self::new(
1749 EditorMode::SingleLine { auto_width: true },
1750 buffer,
1751 None,
1752 false,
1753 cx,
1754 )
1755 }
1756
1757 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1758 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1759 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1760 Self::new(
1761 EditorMode::AutoHeight { max_lines },
1762 buffer,
1763 None,
1764 false,
1765 cx,
1766 )
1767 }
1768
1769 pub fn for_buffer(
1770 buffer: Model<Buffer>,
1771 project: Option<Model<Project>>,
1772 cx: &mut ViewContext<Self>,
1773 ) -> Self {
1774 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1775 Self::new(EditorMode::Full, buffer, project, false, cx)
1776 }
1777
1778 pub fn for_multibuffer(
1779 buffer: Model<MultiBuffer>,
1780 project: Option<Model<Project>>,
1781 show_excerpt_controls: bool,
1782 cx: &mut ViewContext<Self>,
1783 ) -> Self {
1784 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1785 }
1786
1787 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1788 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1789 let mut clone = Self::new(
1790 self.mode,
1791 self.buffer.clone(),
1792 self.project.clone(),
1793 show_excerpt_controls,
1794 cx,
1795 );
1796 self.display_map.update(cx, |display_map, cx| {
1797 let snapshot = display_map.snapshot(cx);
1798 clone.display_map.update(cx, |display_map, cx| {
1799 display_map.set_state(&snapshot, cx);
1800 });
1801 });
1802 clone.selections.clone_state(&self.selections);
1803 clone.scroll_manager.clone_state(&self.scroll_manager);
1804 clone.searchable = self.searchable;
1805 clone
1806 }
1807
1808 pub fn new(
1809 mode: EditorMode,
1810 buffer: Model<MultiBuffer>,
1811 project: Option<Model<Project>>,
1812 show_excerpt_controls: bool,
1813 cx: &mut ViewContext<Self>,
1814 ) -> Self {
1815 let style = cx.text_style();
1816 let font_size = style.font_size.to_pixels(cx.rem_size());
1817 let editor = cx.view().downgrade();
1818 let fold_placeholder = FoldPlaceholder {
1819 constrain_width: true,
1820 render: Arc::new(move |fold_id, fold_range, cx| {
1821 let editor = editor.clone();
1822 div()
1823 .id(fold_id)
1824 .bg(cx.theme().colors().ghost_element_background)
1825 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1826 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1827 .rounded_sm()
1828 .size_full()
1829 .cursor_pointer()
1830 .child("⋯")
1831 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1832 .on_click(move |_, cx| {
1833 editor
1834 .update(cx, |editor, cx| {
1835 editor.unfold_ranges(
1836 [fold_range.start..fold_range.end],
1837 true,
1838 false,
1839 cx,
1840 );
1841 cx.stop_propagation();
1842 })
1843 .ok();
1844 })
1845 .into_any()
1846 }),
1847 merge_adjacent: true,
1848 };
1849 let display_map = cx.new_model(|cx| {
1850 DisplayMap::new(
1851 buffer.clone(),
1852 style.font(),
1853 font_size,
1854 None,
1855 show_excerpt_controls,
1856 FILE_HEADER_HEIGHT,
1857 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1858 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1859 fold_placeholder,
1860 cx,
1861 )
1862 });
1863
1864 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1865
1866 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1867
1868 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1869 .then(|| language_settings::SoftWrap::None);
1870
1871 let mut project_subscriptions = Vec::new();
1872 if mode == EditorMode::Full {
1873 if let Some(project) = project.as_ref() {
1874 if buffer.read(cx).is_singleton() {
1875 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1876 cx.emit(EditorEvent::TitleChanged);
1877 }));
1878 }
1879 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1880 if let project::Event::RefreshInlayHints = event {
1881 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1882 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1883 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1884 let focus_handle = editor.focus_handle(cx);
1885 if focus_handle.is_focused(cx) {
1886 let snapshot = buffer.read(cx).snapshot();
1887 for (range, snippet) in snippet_edits {
1888 let editor_range =
1889 language::range_from_lsp(*range).to_offset(&snapshot);
1890 editor
1891 .insert_snippet(&[editor_range], snippet.clone(), cx)
1892 .ok();
1893 }
1894 }
1895 }
1896 }
1897 }));
1898 if let Some(task_inventory) = project
1899 .read(cx)
1900 .task_store()
1901 .read(cx)
1902 .task_inventory()
1903 .cloned()
1904 {
1905 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1906 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1907 }));
1908 }
1909 }
1910 }
1911
1912 let inlay_hint_settings = inlay_hint_settings(
1913 selections.newest_anchor().head(),
1914 &buffer.read(cx).snapshot(cx),
1915 cx,
1916 );
1917 let focus_handle = cx.focus_handle();
1918 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1919 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1920 .detach();
1921 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1922 .detach();
1923 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1924
1925 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1926 Some(false)
1927 } else {
1928 None
1929 };
1930
1931 let mut code_action_providers = Vec::new();
1932 if let Some(project) = project.clone() {
1933 code_action_providers.push(Arc::new(project) as Arc<_>);
1934 }
1935
1936 let mut this = Self {
1937 focus_handle,
1938 show_cursor_when_unfocused: false,
1939 last_focused_descendant: None,
1940 buffer: buffer.clone(),
1941 display_map: display_map.clone(),
1942 selections,
1943 scroll_manager: ScrollManager::new(cx),
1944 columnar_selection_tail: None,
1945 add_selections_state: None,
1946 select_next_state: None,
1947 select_prev_state: None,
1948 selection_history: Default::default(),
1949 autoclose_regions: Default::default(),
1950 snippet_stack: Default::default(),
1951 select_larger_syntax_node_stack: Vec::new(),
1952 ime_transaction: Default::default(),
1953 active_diagnostics: None,
1954 soft_wrap_mode_override,
1955 completion_provider: project.clone().map(|project| Box::new(project) as _),
1956 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1957 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1958 project,
1959 blink_manager: blink_manager.clone(),
1960 show_local_selections: true,
1961 mode,
1962 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1963 show_gutter: mode == EditorMode::Full,
1964 show_line_numbers: None,
1965 use_relative_line_numbers: None,
1966 show_git_diff_gutter: None,
1967 show_code_actions: None,
1968 show_runnables: None,
1969 show_wrap_guides: None,
1970 show_indent_guides,
1971 placeholder_text: None,
1972 highlight_order: 0,
1973 highlighted_rows: HashMap::default(),
1974 background_highlights: Default::default(),
1975 gutter_highlights: TreeMap::default(),
1976 scrollbar_marker_state: ScrollbarMarkerState::default(),
1977 active_indent_guides_state: ActiveIndentGuidesState::default(),
1978 nav_history: None,
1979 context_menu: RwLock::new(None),
1980 mouse_context_menu: None,
1981 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1982 completion_tasks: Default::default(),
1983 signature_help_state: SignatureHelpState::default(),
1984 auto_signature_help: None,
1985 find_all_references_task_sources: Vec::new(),
1986 next_completion_id: 0,
1987 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1988 next_inlay_id: 0,
1989 code_action_providers,
1990 available_code_actions: Default::default(),
1991 code_actions_task: Default::default(),
1992 document_highlights_task: Default::default(),
1993 linked_editing_range_task: Default::default(),
1994 pending_rename: Default::default(),
1995 searchable: true,
1996 cursor_shape: EditorSettings::get_global(cx)
1997 .cursor_shape
1998 .unwrap_or_default(),
1999 current_line_highlight: None,
2000 autoindent_mode: Some(AutoindentMode::EachLine),
2001 collapse_matches: false,
2002 workspace: None,
2003 input_enabled: true,
2004 use_modal_editing: mode == EditorMode::Full,
2005 read_only: false,
2006 use_autoclose: true,
2007 use_auto_surround: true,
2008 auto_replace_emoji_shortcode: false,
2009 leader_peer_id: None,
2010 remote_id: None,
2011 hover_state: Default::default(),
2012 hovered_link_state: Default::default(),
2013 inline_completion_provider: None,
2014 active_inline_completion: None,
2015 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
2016 expanded_hunks: ExpandedHunks::default(),
2017 gutter_hovered: false,
2018 pixel_position_of_newest_cursor: None,
2019 last_bounds: None,
2020 expect_bounds_change: None,
2021 gutter_dimensions: GutterDimensions::default(),
2022 style: None,
2023 show_cursor_names: false,
2024 hovered_cursors: Default::default(),
2025 next_editor_action_id: EditorActionId::default(),
2026 editor_actions: Rc::default(),
2027 show_inline_completions_override: None,
2028 enable_inline_completions: true,
2029 custom_context_menu: None,
2030 show_git_blame_gutter: false,
2031 show_git_blame_inline: false,
2032 show_selection_menu: None,
2033 show_git_blame_inline_delay_task: None,
2034 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2035 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2036 .session
2037 .restore_unsaved_buffers,
2038 blame: None,
2039 blame_subscription: None,
2040 tasks: Default::default(),
2041 _subscriptions: vec![
2042 cx.observe(&buffer, Self::on_buffer_changed),
2043 cx.subscribe(&buffer, Self::on_buffer_event),
2044 cx.observe(&display_map, Self::on_display_map_changed),
2045 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2046 cx.observe_global::<SettingsStore>(Self::settings_changed),
2047 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2048 cx.observe_window_activation(|editor, cx| {
2049 let active = cx.is_window_active();
2050 editor.blink_manager.update(cx, |blink_manager, cx| {
2051 if active {
2052 blink_manager.enable(cx);
2053 } else {
2054 blink_manager.disable(cx);
2055 }
2056 });
2057 }),
2058 ],
2059 tasks_update_task: None,
2060 linked_edit_ranges: Default::default(),
2061 previous_search_ranges: None,
2062 breadcrumb_header: None,
2063 focused_block: None,
2064 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2065 addons: HashMap::default(),
2066 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2067 text_style_refinement: None,
2068 };
2069 this.tasks_update_task = Some(this.refresh_runnables(cx));
2070 this._subscriptions.extend(project_subscriptions);
2071
2072 this.end_selection(cx);
2073 this.scroll_manager.show_scrollbar(cx);
2074
2075 if mode == EditorMode::Full {
2076 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2077 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2078
2079 if this.git_blame_inline_enabled {
2080 this.git_blame_inline_enabled = true;
2081 this.start_git_blame_inline(false, cx);
2082 }
2083 }
2084
2085 this.report_editor_event("open", None, cx);
2086 this
2087 }
2088
2089 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2090 self.mouse_context_menu
2091 .as_ref()
2092 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2093 }
2094
2095 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2096 let mut key_context = KeyContext::new_with_defaults();
2097 key_context.add("Editor");
2098 let mode = match self.mode {
2099 EditorMode::SingleLine { .. } => "single_line",
2100 EditorMode::AutoHeight { .. } => "auto_height",
2101 EditorMode::Full => "full",
2102 };
2103
2104 if EditorSettings::jupyter_enabled(cx) {
2105 key_context.add("jupyter");
2106 }
2107
2108 key_context.set("mode", mode);
2109 if self.pending_rename.is_some() {
2110 key_context.add("renaming");
2111 }
2112 if self.context_menu_visible() {
2113 match self.context_menu.read().as_ref() {
2114 Some(ContextMenu::Completions(_)) => {
2115 key_context.add("menu");
2116 key_context.add("showing_completions")
2117 }
2118 Some(ContextMenu::CodeActions(_)) => {
2119 key_context.add("menu");
2120 key_context.add("showing_code_actions")
2121 }
2122 None => {}
2123 }
2124 }
2125
2126 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2127 if !self.focus_handle(cx).contains_focused(cx)
2128 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2129 {
2130 for addon in self.addons.values() {
2131 addon.extend_key_context(&mut key_context, cx)
2132 }
2133 }
2134
2135 if let Some(extension) = self
2136 .buffer
2137 .read(cx)
2138 .as_singleton()
2139 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2140 {
2141 key_context.set("extension", extension.to_string());
2142 }
2143
2144 if self.has_active_inline_completion(cx) {
2145 key_context.add("copilot_suggestion");
2146 key_context.add("inline_completion");
2147 }
2148
2149 key_context
2150 }
2151
2152 pub fn new_file(
2153 workspace: &mut Workspace,
2154 _: &workspace::NewFile,
2155 cx: &mut ViewContext<Workspace>,
2156 ) {
2157 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2158 "Failed to create buffer",
2159 cx,
2160 |e, _| match e.error_code() {
2161 ErrorCode::RemoteUpgradeRequired => Some(format!(
2162 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2163 e.error_tag("required").unwrap_or("the latest version")
2164 )),
2165 _ => None,
2166 },
2167 );
2168 }
2169
2170 pub fn new_in_workspace(
2171 workspace: &mut Workspace,
2172 cx: &mut ViewContext<Workspace>,
2173 ) -> Task<Result<View<Editor>>> {
2174 let project = workspace.project().clone();
2175 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2176
2177 cx.spawn(|workspace, mut cx| async move {
2178 let buffer = create.await?;
2179 workspace.update(&mut cx, |workspace, cx| {
2180 let editor =
2181 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2182 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2183 editor
2184 })
2185 })
2186 }
2187
2188 fn new_file_vertical(
2189 workspace: &mut Workspace,
2190 _: &workspace::NewFileSplitVertical,
2191 cx: &mut ViewContext<Workspace>,
2192 ) {
2193 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2194 }
2195
2196 fn new_file_horizontal(
2197 workspace: &mut Workspace,
2198 _: &workspace::NewFileSplitHorizontal,
2199 cx: &mut ViewContext<Workspace>,
2200 ) {
2201 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2202 }
2203
2204 fn new_file_in_direction(
2205 workspace: &mut Workspace,
2206 direction: SplitDirection,
2207 cx: &mut ViewContext<Workspace>,
2208 ) {
2209 let project = workspace.project().clone();
2210 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2211
2212 cx.spawn(|workspace, mut cx| async move {
2213 let buffer = create.await?;
2214 workspace.update(&mut cx, move |workspace, cx| {
2215 workspace.split_item(
2216 direction,
2217 Box::new(
2218 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2219 ),
2220 cx,
2221 )
2222 })?;
2223 anyhow::Ok(())
2224 })
2225 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2226 ErrorCode::RemoteUpgradeRequired => Some(format!(
2227 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2228 e.error_tag("required").unwrap_or("the latest version")
2229 )),
2230 _ => None,
2231 });
2232 }
2233
2234 pub fn leader_peer_id(&self) -> Option<PeerId> {
2235 self.leader_peer_id
2236 }
2237
2238 pub fn buffer(&self) -> &Model<MultiBuffer> {
2239 &self.buffer
2240 }
2241
2242 pub fn workspace(&self) -> Option<View<Workspace>> {
2243 self.workspace.as_ref()?.0.upgrade()
2244 }
2245
2246 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2247 self.buffer().read(cx).title(cx)
2248 }
2249
2250 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2251 let git_blame_gutter_max_author_length = self
2252 .render_git_blame_gutter(cx)
2253 .then(|| {
2254 if let Some(blame) = self.blame.as_ref() {
2255 let max_author_length =
2256 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2257 Some(max_author_length)
2258 } else {
2259 None
2260 }
2261 })
2262 .flatten();
2263
2264 EditorSnapshot {
2265 mode: self.mode,
2266 show_gutter: self.show_gutter,
2267 show_line_numbers: self.show_line_numbers,
2268 show_git_diff_gutter: self.show_git_diff_gutter,
2269 show_code_actions: self.show_code_actions,
2270 show_runnables: self.show_runnables,
2271 git_blame_gutter_max_author_length,
2272 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2273 scroll_anchor: self.scroll_manager.anchor(),
2274 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2275 placeholder_text: self.placeholder_text.clone(),
2276 is_focused: self.focus_handle.is_focused(cx),
2277 current_line_highlight: self
2278 .current_line_highlight
2279 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2280 gutter_hovered: self.gutter_hovered,
2281 }
2282 }
2283
2284 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2285 self.buffer.read(cx).language_at(point, cx)
2286 }
2287
2288 pub fn file_at<T: ToOffset>(
2289 &self,
2290 point: T,
2291 cx: &AppContext,
2292 ) -> Option<Arc<dyn language::File>> {
2293 self.buffer.read(cx).read(cx).file_at(point).cloned()
2294 }
2295
2296 pub fn active_excerpt(
2297 &self,
2298 cx: &AppContext,
2299 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2300 self.buffer
2301 .read(cx)
2302 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2303 }
2304
2305 pub fn mode(&self) -> EditorMode {
2306 self.mode
2307 }
2308
2309 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2310 self.collaboration_hub.as_deref()
2311 }
2312
2313 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2314 self.collaboration_hub = Some(hub);
2315 }
2316
2317 pub fn set_custom_context_menu(
2318 &mut self,
2319 f: impl 'static
2320 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2321 ) {
2322 self.custom_context_menu = Some(Box::new(f))
2323 }
2324
2325 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2326 self.completion_provider = provider;
2327 }
2328
2329 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2330 self.semantics_provider.clone()
2331 }
2332
2333 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2334 self.semantics_provider = provider;
2335 }
2336
2337 pub fn set_inline_completion_provider<T>(
2338 &mut self,
2339 provider: Option<Model<T>>,
2340 cx: &mut ViewContext<Self>,
2341 ) where
2342 T: InlineCompletionProvider,
2343 {
2344 self.inline_completion_provider =
2345 provider.map(|provider| RegisteredInlineCompletionProvider {
2346 _subscription: cx.observe(&provider, |this, _, cx| {
2347 if this.focus_handle.is_focused(cx) {
2348 this.update_visible_inline_completion(cx);
2349 }
2350 }),
2351 provider: Arc::new(provider),
2352 });
2353 self.refresh_inline_completion(false, false, cx);
2354 }
2355
2356 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2357 self.placeholder_text.as_deref()
2358 }
2359
2360 pub fn set_placeholder_text(
2361 &mut self,
2362 placeholder_text: impl Into<Arc<str>>,
2363 cx: &mut ViewContext<Self>,
2364 ) {
2365 let placeholder_text = Some(placeholder_text.into());
2366 if self.placeholder_text != placeholder_text {
2367 self.placeholder_text = placeholder_text;
2368 cx.notify();
2369 }
2370 }
2371
2372 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2373 self.cursor_shape = cursor_shape;
2374
2375 // Disrupt blink for immediate user feedback that the cursor shape has changed
2376 self.blink_manager.update(cx, BlinkManager::show_cursor);
2377
2378 cx.notify();
2379 }
2380
2381 pub fn set_current_line_highlight(
2382 &mut self,
2383 current_line_highlight: Option<CurrentLineHighlight>,
2384 ) {
2385 self.current_line_highlight = current_line_highlight;
2386 }
2387
2388 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2389 self.collapse_matches = collapse_matches;
2390 }
2391
2392 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2393 if self.collapse_matches {
2394 return range.start..range.start;
2395 }
2396 range.clone()
2397 }
2398
2399 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2400 if self.display_map.read(cx).clip_at_line_ends != clip {
2401 self.display_map
2402 .update(cx, |map, _| map.clip_at_line_ends = clip);
2403 }
2404 }
2405
2406 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2407 self.input_enabled = input_enabled;
2408 }
2409
2410 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2411 self.enable_inline_completions = enabled;
2412 }
2413
2414 pub fn set_autoindent(&mut self, autoindent: bool) {
2415 if autoindent {
2416 self.autoindent_mode = Some(AutoindentMode::EachLine);
2417 } else {
2418 self.autoindent_mode = None;
2419 }
2420 }
2421
2422 pub fn read_only(&self, cx: &AppContext) -> bool {
2423 self.read_only || self.buffer.read(cx).read_only()
2424 }
2425
2426 pub fn set_read_only(&mut self, read_only: bool) {
2427 self.read_only = read_only;
2428 }
2429
2430 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2431 self.use_autoclose = autoclose;
2432 }
2433
2434 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2435 self.use_auto_surround = auto_surround;
2436 }
2437
2438 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2439 self.auto_replace_emoji_shortcode = auto_replace;
2440 }
2441
2442 pub fn toggle_inline_completions(
2443 &mut self,
2444 _: &ToggleInlineCompletions,
2445 cx: &mut ViewContext<Self>,
2446 ) {
2447 if self.show_inline_completions_override.is_some() {
2448 self.set_show_inline_completions(None, cx);
2449 } else {
2450 let cursor = self.selections.newest_anchor().head();
2451 if let Some((buffer, cursor_buffer_position)) =
2452 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2453 {
2454 let show_inline_completions =
2455 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2456 self.set_show_inline_completions(Some(show_inline_completions), cx);
2457 }
2458 }
2459 }
2460
2461 pub fn set_show_inline_completions(
2462 &mut self,
2463 show_inline_completions: Option<bool>,
2464 cx: &mut ViewContext<Self>,
2465 ) {
2466 self.show_inline_completions_override = show_inline_completions;
2467 self.refresh_inline_completion(false, true, cx);
2468 }
2469
2470 fn should_show_inline_completions(
2471 &self,
2472 buffer: &Model<Buffer>,
2473 buffer_position: language::Anchor,
2474 cx: &AppContext,
2475 ) -> bool {
2476 if let Some(provider) = self.inline_completion_provider() {
2477 if let Some(show_inline_completions) = self.show_inline_completions_override {
2478 show_inline_completions
2479 } else {
2480 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2481 }
2482 } else {
2483 false
2484 }
2485 }
2486
2487 pub fn set_use_modal_editing(&mut self, to: bool) {
2488 self.use_modal_editing = to;
2489 }
2490
2491 pub fn use_modal_editing(&self) -> bool {
2492 self.use_modal_editing
2493 }
2494
2495 fn selections_did_change(
2496 &mut self,
2497 local: bool,
2498 old_cursor_position: &Anchor,
2499 show_completions: bool,
2500 cx: &mut ViewContext<Self>,
2501 ) {
2502 cx.invalidate_character_coordinates();
2503
2504 // Copy selections to primary selection buffer
2505 #[cfg(target_os = "linux")]
2506 if local {
2507 let selections = self.selections.all::<usize>(cx);
2508 let buffer_handle = self.buffer.read(cx).read(cx);
2509
2510 let mut text = String::new();
2511 for (index, selection) in selections.iter().enumerate() {
2512 let text_for_selection = buffer_handle
2513 .text_for_range(selection.start..selection.end)
2514 .collect::<String>();
2515
2516 text.push_str(&text_for_selection);
2517 if index != selections.len() - 1 {
2518 text.push('\n');
2519 }
2520 }
2521
2522 if !text.is_empty() {
2523 cx.write_to_primary(ClipboardItem::new_string(text));
2524 }
2525 }
2526
2527 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2528 self.buffer.update(cx, |buffer, cx| {
2529 buffer.set_active_selections(
2530 &self.selections.disjoint_anchors(),
2531 self.selections.line_mode,
2532 self.cursor_shape,
2533 cx,
2534 )
2535 });
2536 }
2537 let display_map = self
2538 .display_map
2539 .update(cx, |display_map, cx| display_map.snapshot(cx));
2540 let buffer = &display_map.buffer_snapshot;
2541 self.add_selections_state = None;
2542 self.select_next_state = None;
2543 self.select_prev_state = None;
2544 self.select_larger_syntax_node_stack.clear();
2545 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2546 self.snippet_stack
2547 .invalidate(&self.selections.disjoint_anchors(), buffer);
2548 self.take_rename(false, cx);
2549
2550 let new_cursor_position = self.selections.newest_anchor().head();
2551
2552 self.push_to_nav_history(
2553 *old_cursor_position,
2554 Some(new_cursor_position.to_point(buffer)),
2555 cx,
2556 );
2557
2558 if local {
2559 let new_cursor_position = self.selections.newest_anchor().head();
2560 let mut context_menu = self.context_menu.write();
2561 let completion_menu = match context_menu.as_ref() {
2562 Some(ContextMenu::Completions(menu)) => Some(menu),
2563
2564 _ => {
2565 *context_menu = None;
2566 None
2567 }
2568 };
2569
2570 if let Some(completion_menu) = completion_menu {
2571 let cursor_position = new_cursor_position.to_offset(buffer);
2572 let (word_range, kind) =
2573 buffer.surrounding_word(completion_menu.initial_position, true);
2574 if kind == Some(CharKind::Word)
2575 && word_range.to_inclusive().contains(&cursor_position)
2576 {
2577 let mut completion_menu = completion_menu.clone();
2578 drop(context_menu);
2579
2580 let query = Self::completion_query(buffer, cursor_position);
2581 cx.spawn(move |this, mut cx| async move {
2582 completion_menu
2583 .filter(query.as_deref(), cx.background_executor().clone())
2584 .await;
2585
2586 this.update(&mut cx, |this, cx| {
2587 let mut context_menu = this.context_menu.write();
2588 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2589 return;
2590 };
2591
2592 if menu.id > completion_menu.id {
2593 return;
2594 }
2595
2596 *context_menu = Some(ContextMenu::Completions(completion_menu));
2597 drop(context_menu);
2598 cx.notify();
2599 })
2600 })
2601 .detach();
2602
2603 if show_completions {
2604 self.show_completions(&ShowCompletions { trigger: None }, cx);
2605 }
2606 } else {
2607 drop(context_menu);
2608 self.hide_context_menu(cx);
2609 }
2610 } else {
2611 drop(context_menu);
2612 }
2613
2614 hide_hover(self, cx);
2615
2616 if old_cursor_position.to_display_point(&display_map).row()
2617 != new_cursor_position.to_display_point(&display_map).row()
2618 {
2619 self.available_code_actions.take();
2620 }
2621 self.refresh_code_actions(cx);
2622 self.refresh_document_highlights(cx);
2623 refresh_matching_bracket_highlights(self, cx);
2624 self.discard_inline_completion(false, cx);
2625 linked_editing_ranges::refresh_linked_ranges(self, cx);
2626 if self.git_blame_inline_enabled {
2627 self.start_inline_blame_timer(cx);
2628 }
2629 }
2630
2631 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2632 cx.emit(EditorEvent::SelectionsChanged { local });
2633
2634 if self.selections.disjoint_anchors().len() == 1 {
2635 cx.emit(SearchEvent::ActiveMatchChanged)
2636 }
2637 cx.notify();
2638 }
2639
2640 pub fn change_selections<R>(
2641 &mut self,
2642 autoscroll: Option<Autoscroll>,
2643 cx: &mut ViewContext<Self>,
2644 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2645 ) -> R {
2646 self.change_selections_inner(autoscroll, true, cx, change)
2647 }
2648
2649 pub fn change_selections_inner<R>(
2650 &mut self,
2651 autoscroll: Option<Autoscroll>,
2652 request_completions: bool,
2653 cx: &mut ViewContext<Self>,
2654 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2655 ) -> R {
2656 let old_cursor_position = self.selections.newest_anchor().head();
2657 self.push_to_selection_history();
2658
2659 let (changed, result) = self.selections.change_with(cx, change);
2660
2661 if changed {
2662 if let Some(autoscroll) = autoscroll {
2663 self.request_autoscroll(autoscroll, cx);
2664 }
2665 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2666
2667 if self.should_open_signature_help_automatically(
2668 &old_cursor_position,
2669 self.signature_help_state.backspace_pressed(),
2670 cx,
2671 ) {
2672 self.show_signature_help(&ShowSignatureHelp, cx);
2673 }
2674 self.signature_help_state.set_backspace_pressed(false);
2675 }
2676
2677 result
2678 }
2679
2680 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2681 where
2682 I: IntoIterator<Item = (Range<S>, T)>,
2683 S: ToOffset,
2684 T: Into<Arc<str>>,
2685 {
2686 if self.read_only(cx) {
2687 return;
2688 }
2689
2690 self.buffer
2691 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2692 }
2693
2694 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2695 where
2696 I: IntoIterator<Item = (Range<S>, T)>,
2697 S: ToOffset,
2698 T: Into<Arc<str>>,
2699 {
2700 if self.read_only(cx) {
2701 return;
2702 }
2703
2704 self.buffer.update(cx, |buffer, cx| {
2705 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2706 });
2707 }
2708
2709 pub fn edit_with_block_indent<I, S, T>(
2710 &mut self,
2711 edits: I,
2712 original_indent_columns: Vec<u32>,
2713 cx: &mut ViewContext<Self>,
2714 ) where
2715 I: IntoIterator<Item = (Range<S>, T)>,
2716 S: ToOffset,
2717 T: Into<Arc<str>>,
2718 {
2719 if self.read_only(cx) {
2720 return;
2721 }
2722
2723 self.buffer.update(cx, |buffer, cx| {
2724 buffer.edit(
2725 edits,
2726 Some(AutoindentMode::Block {
2727 original_indent_columns,
2728 }),
2729 cx,
2730 )
2731 });
2732 }
2733
2734 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2735 self.hide_context_menu(cx);
2736
2737 match phase {
2738 SelectPhase::Begin {
2739 position,
2740 add,
2741 click_count,
2742 } => self.begin_selection(position, add, click_count, cx),
2743 SelectPhase::BeginColumnar {
2744 position,
2745 goal_column,
2746 reset,
2747 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2748 SelectPhase::Extend {
2749 position,
2750 click_count,
2751 } => self.extend_selection(position, click_count, cx),
2752 SelectPhase::Update {
2753 position,
2754 goal_column,
2755 scroll_delta,
2756 } => self.update_selection(position, goal_column, scroll_delta, cx),
2757 SelectPhase::End => self.end_selection(cx),
2758 }
2759 }
2760
2761 fn extend_selection(
2762 &mut self,
2763 position: DisplayPoint,
2764 click_count: usize,
2765 cx: &mut ViewContext<Self>,
2766 ) {
2767 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2768 let tail = self.selections.newest::<usize>(cx).tail();
2769 self.begin_selection(position, false, click_count, cx);
2770
2771 let position = position.to_offset(&display_map, Bias::Left);
2772 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2773
2774 let mut pending_selection = self
2775 .selections
2776 .pending_anchor()
2777 .expect("extend_selection not called with pending selection");
2778 if position >= tail {
2779 pending_selection.start = tail_anchor;
2780 } else {
2781 pending_selection.end = tail_anchor;
2782 pending_selection.reversed = true;
2783 }
2784
2785 let mut pending_mode = self.selections.pending_mode().unwrap();
2786 match &mut pending_mode {
2787 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2788 _ => {}
2789 }
2790
2791 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2792 s.set_pending(pending_selection, pending_mode)
2793 });
2794 }
2795
2796 fn begin_selection(
2797 &mut self,
2798 position: DisplayPoint,
2799 add: bool,
2800 click_count: usize,
2801 cx: &mut ViewContext<Self>,
2802 ) {
2803 if !self.focus_handle.is_focused(cx) {
2804 self.last_focused_descendant = None;
2805 cx.focus(&self.focus_handle);
2806 }
2807
2808 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2809 let buffer = &display_map.buffer_snapshot;
2810 let newest_selection = self.selections.newest_anchor().clone();
2811 let position = display_map.clip_point(position, Bias::Left);
2812
2813 let start;
2814 let end;
2815 let mode;
2816 let auto_scroll;
2817 match click_count {
2818 1 => {
2819 start = buffer.anchor_before(position.to_point(&display_map));
2820 end = start;
2821 mode = SelectMode::Character;
2822 auto_scroll = true;
2823 }
2824 2 => {
2825 let range = movement::surrounding_word(&display_map, position);
2826 start = buffer.anchor_before(range.start.to_point(&display_map));
2827 end = buffer.anchor_before(range.end.to_point(&display_map));
2828 mode = SelectMode::Word(start..end);
2829 auto_scroll = true;
2830 }
2831 3 => {
2832 let position = display_map
2833 .clip_point(position, Bias::Left)
2834 .to_point(&display_map);
2835 let line_start = display_map.prev_line_boundary(position).0;
2836 let next_line_start = buffer.clip_point(
2837 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2838 Bias::Left,
2839 );
2840 start = buffer.anchor_before(line_start);
2841 end = buffer.anchor_before(next_line_start);
2842 mode = SelectMode::Line(start..end);
2843 auto_scroll = true;
2844 }
2845 _ => {
2846 start = buffer.anchor_before(0);
2847 end = buffer.anchor_before(buffer.len());
2848 mode = SelectMode::All;
2849 auto_scroll = false;
2850 }
2851 }
2852
2853 let point_to_delete: Option<usize> = {
2854 let selected_points: Vec<Selection<Point>> =
2855 self.selections.disjoint_in_range(start..end, cx);
2856
2857 if !add || click_count > 1 {
2858 None
2859 } else if !selected_points.is_empty() {
2860 Some(selected_points[0].id)
2861 } else {
2862 let clicked_point_already_selected =
2863 self.selections.disjoint.iter().find(|selection| {
2864 selection.start.to_point(buffer) == start.to_point(buffer)
2865 || selection.end.to_point(buffer) == end.to_point(buffer)
2866 });
2867
2868 clicked_point_already_selected.map(|selection| selection.id)
2869 }
2870 };
2871
2872 let selections_count = self.selections.count();
2873
2874 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2875 if let Some(point_to_delete) = point_to_delete {
2876 s.delete(point_to_delete);
2877
2878 if selections_count == 1 {
2879 s.set_pending_anchor_range(start..end, mode);
2880 }
2881 } else {
2882 if !add {
2883 s.clear_disjoint();
2884 } else if click_count > 1 {
2885 s.delete(newest_selection.id)
2886 }
2887
2888 s.set_pending_anchor_range(start..end, mode);
2889 }
2890 });
2891 }
2892
2893 fn begin_columnar_selection(
2894 &mut self,
2895 position: DisplayPoint,
2896 goal_column: u32,
2897 reset: bool,
2898 cx: &mut ViewContext<Self>,
2899 ) {
2900 if !self.focus_handle.is_focused(cx) {
2901 self.last_focused_descendant = None;
2902 cx.focus(&self.focus_handle);
2903 }
2904
2905 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2906
2907 if reset {
2908 let pointer_position = display_map
2909 .buffer_snapshot
2910 .anchor_before(position.to_point(&display_map));
2911
2912 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2913 s.clear_disjoint();
2914 s.set_pending_anchor_range(
2915 pointer_position..pointer_position,
2916 SelectMode::Character,
2917 );
2918 });
2919 }
2920
2921 let tail = self.selections.newest::<Point>(cx).tail();
2922 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2923
2924 if !reset {
2925 self.select_columns(
2926 tail.to_display_point(&display_map),
2927 position,
2928 goal_column,
2929 &display_map,
2930 cx,
2931 );
2932 }
2933 }
2934
2935 fn update_selection(
2936 &mut self,
2937 position: DisplayPoint,
2938 goal_column: u32,
2939 scroll_delta: gpui::Point<f32>,
2940 cx: &mut ViewContext<Self>,
2941 ) {
2942 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2943
2944 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2945 let tail = tail.to_display_point(&display_map);
2946 self.select_columns(tail, position, goal_column, &display_map, cx);
2947 } else if let Some(mut pending) = self.selections.pending_anchor() {
2948 let buffer = self.buffer.read(cx).snapshot(cx);
2949 let head;
2950 let tail;
2951 let mode = self.selections.pending_mode().unwrap();
2952 match &mode {
2953 SelectMode::Character => {
2954 head = position.to_point(&display_map);
2955 tail = pending.tail().to_point(&buffer);
2956 }
2957 SelectMode::Word(original_range) => {
2958 let original_display_range = original_range.start.to_display_point(&display_map)
2959 ..original_range.end.to_display_point(&display_map);
2960 let original_buffer_range = original_display_range.start.to_point(&display_map)
2961 ..original_display_range.end.to_point(&display_map);
2962 if movement::is_inside_word(&display_map, position)
2963 || original_display_range.contains(&position)
2964 {
2965 let word_range = movement::surrounding_word(&display_map, position);
2966 if word_range.start < original_display_range.start {
2967 head = word_range.start.to_point(&display_map);
2968 } else {
2969 head = word_range.end.to_point(&display_map);
2970 }
2971 } else {
2972 head = position.to_point(&display_map);
2973 }
2974
2975 if head <= original_buffer_range.start {
2976 tail = original_buffer_range.end;
2977 } else {
2978 tail = original_buffer_range.start;
2979 }
2980 }
2981 SelectMode::Line(original_range) => {
2982 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2983
2984 let position = display_map
2985 .clip_point(position, Bias::Left)
2986 .to_point(&display_map);
2987 let line_start = display_map.prev_line_boundary(position).0;
2988 let next_line_start = buffer.clip_point(
2989 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2990 Bias::Left,
2991 );
2992
2993 if line_start < original_range.start {
2994 head = line_start
2995 } else {
2996 head = next_line_start
2997 }
2998
2999 if head <= original_range.start {
3000 tail = original_range.end;
3001 } else {
3002 tail = original_range.start;
3003 }
3004 }
3005 SelectMode::All => {
3006 return;
3007 }
3008 };
3009
3010 if head < tail {
3011 pending.start = buffer.anchor_before(head);
3012 pending.end = buffer.anchor_before(tail);
3013 pending.reversed = true;
3014 } else {
3015 pending.start = buffer.anchor_before(tail);
3016 pending.end = buffer.anchor_before(head);
3017 pending.reversed = false;
3018 }
3019
3020 self.change_selections(None, cx, |s| {
3021 s.set_pending(pending, mode);
3022 });
3023 } else {
3024 log::error!("update_selection dispatched with no pending selection");
3025 return;
3026 }
3027
3028 self.apply_scroll_delta(scroll_delta, cx);
3029 cx.notify();
3030 }
3031
3032 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3033 self.columnar_selection_tail.take();
3034 if self.selections.pending_anchor().is_some() {
3035 let selections = self.selections.all::<usize>(cx);
3036 self.change_selections(None, cx, |s| {
3037 s.select(selections);
3038 s.clear_pending();
3039 });
3040 }
3041 }
3042
3043 fn select_columns(
3044 &mut self,
3045 tail: DisplayPoint,
3046 head: DisplayPoint,
3047 goal_column: u32,
3048 display_map: &DisplaySnapshot,
3049 cx: &mut ViewContext<Self>,
3050 ) {
3051 let start_row = cmp::min(tail.row(), head.row());
3052 let end_row = cmp::max(tail.row(), head.row());
3053 let start_column = cmp::min(tail.column(), goal_column);
3054 let end_column = cmp::max(tail.column(), goal_column);
3055 let reversed = start_column < tail.column();
3056
3057 let selection_ranges = (start_row.0..=end_row.0)
3058 .map(DisplayRow)
3059 .filter_map(|row| {
3060 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3061 let start = display_map
3062 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3063 .to_point(display_map);
3064 let end = display_map
3065 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3066 .to_point(display_map);
3067 if reversed {
3068 Some(end..start)
3069 } else {
3070 Some(start..end)
3071 }
3072 } else {
3073 None
3074 }
3075 })
3076 .collect::<Vec<_>>();
3077
3078 self.change_selections(None, cx, |s| {
3079 s.select_ranges(selection_ranges);
3080 });
3081 cx.notify();
3082 }
3083
3084 pub fn has_pending_nonempty_selection(&self) -> bool {
3085 let pending_nonempty_selection = match self.selections.pending_anchor() {
3086 Some(Selection { start, end, .. }) => start != end,
3087 None => false,
3088 };
3089
3090 pending_nonempty_selection
3091 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3092 }
3093
3094 pub fn has_pending_selection(&self) -> bool {
3095 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3096 }
3097
3098 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3099 if self.clear_expanded_diff_hunks(cx) {
3100 cx.notify();
3101 return;
3102 }
3103 if self.dismiss_menus_and_popups(true, cx) {
3104 return;
3105 }
3106
3107 if self.mode == EditorMode::Full
3108 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3109 {
3110 return;
3111 }
3112
3113 cx.propagate();
3114 }
3115
3116 pub fn dismiss_menus_and_popups(
3117 &mut self,
3118 should_report_inline_completion_event: bool,
3119 cx: &mut ViewContext<Self>,
3120 ) -> bool {
3121 if self.take_rename(false, cx).is_some() {
3122 return true;
3123 }
3124
3125 if hide_hover(self, cx) {
3126 return true;
3127 }
3128
3129 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3130 return true;
3131 }
3132
3133 if self.hide_context_menu(cx).is_some() {
3134 return true;
3135 }
3136
3137 if self.mouse_context_menu.take().is_some() {
3138 return true;
3139 }
3140
3141 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3142 return true;
3143 }
3144
3145 if self.snippet_stack.pop().is_some() {
3146 return true;
3147 }
3148
3149 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3150 self.dismiss_diagnostics(cx);
3151 return true;
3152 }
3153
3154 false
3155 }
3156
3157 fn linked_editing_ranges_for(
3158 &self,
3159 selection: Range<text::Anchor>,
3160 cx: &AppContext,
3161 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3162 if self.linked_edit_ranges.is_empty() {
3163 return None;
3164 }
3165 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3166 selection.end.buffer_id.and_then(|end_buffer_id| {
3167 if selection.start.buffer_id != Some(end_buffer_id) {
3168 return None;
3169 }
3170 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3171 let snapshot = buffer.read(cx).snapshot();
3172 self.linked_edit_ranges
3173 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3174 .map(|ranges| (ranges, snapshot, buffer))
3175 })?;
3176 use text::ToOffset as TO;
3177 // find offset from the start of current range to current cursor position
3178 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3179
3180 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3181 let start_difference = start_offset - start_byte_offset;
3182 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3183 let end_difference = end_offset - start_byte_offset;
3184 // Current range has associated linked ranges.
3185 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3186 for range in linked_ranges.iter() {
3187 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3188 let end_offset = start_offset + end_difference;
3189 let start_offset = start_offset + start_difference;
3190 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3191 continue;
3192 }
3193 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3194 if s.start.buffer_id != selection.start.buffer_id
3195 || s.end.buffer_id != selection.end.buffer_id
3196 {
3197 return false;
3198 }
3199 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3200 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3201 }) {
3202 continue;
3203 }
3204 let start = buffer_snapshot.anchor_after(start_offset);
3205 let end = buffer_snapshot.anchor_after(end_offset);
3206 linked_edits
3207 .entry(buffer.clone())
3208 .or_default()
3209 .push(start..end);
3210 }
3211 Some(linked_edits)
3212 }
3213
3214 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3215 let text: Arc<str> = text.into();
3216
3217 if self.read_only(cx) {
3218 return;
3219 }
3220
3221 let selections = self.selections.all_adjusted(cx);
3222 let mut bracket_inserted = false;
3223 let mut edits = Vec::new();
3224 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3225 let mut new_selections = Vec::with_capacity(selections.len());
3226 let mut new_autoclose_regions = Vec::new();
3227 let snapshot = self.buffer.read(cx).read(cx);
3228
3229 for (selection, autoclose_region) in
3230 self.selections_with_autoclose_regions(selections, &snapshot)
3231 {
3232 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3233 // Determine if the inserted text matches the opening or closing
3234 // bracket of any of this language's bracket pairs.
3235 let mut bracket_pair = None;
3236 let mut is_bracket_pair_start = false;
3237 let mut is_bracket_pair_end = false;
3238 if !text.is_empty() {
3239 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3240 // and they are removing the character that triggered IME popup.
3241 for (pair, enabled) in scope.brackets() {
3242 if !pair.close && !pair.surround {
3243 continue;
3244 }
3245
3246 if enabled && pair.start.ends_with(text.as_ref()) {
3247 bracket_pair = Some(pair.clone());
3248 is_bracket_pair_start = true;
3249 break;
3250 }
3251 if pair.end.as_str() == text.as_ref() {
3252 bracket_pair = Some(pair.clone());
3253 is_bracket_pair_end = true;
3254 break;
3255 }
3256 }
3257 }
3258
3259 if let Some(bracket_pair) = bracket_pair {
3260 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3261 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3262 let auto_surround =
3263 self.use_auto_surround && snapshot_settings.use_auto_surround;
3264 if selection.is_empty() {
3265 if is_bracket_pair_start {
3266 let prefix_len = bracket_pair.start.len() - text.len();
3267
3268 // If the inserted text is a suffix of an opening bracket and the
3269 // selection is preceded by the rest of the opening bracket, then
3270 // insert the closing bracket.
3271 let following_text_allows_autoclose = snapshot
3272 .chars_at(selection.start)
3273 .next()
3274 .map_or(true, |c| scope.should_autoclose_before(c));
3275 let preceding_text_matches_prefix = prefix_len == 0
3276 || (selection.start.column >= (prefix_len as u32)
3277 && snapshot.contains_str_at(
3278 Point::new(
3279 selection.start.row,
3280 selection.start.column - (prefix_len as u32),
3281 ),
3282 &bracket_pair.start[..prefix_len],
3283 ));
3284
3285 if autoclose
3286 && bracket_pair.close
3287 && following_text_allows_autoclose
3288 && preceding_text_matches_prefix
3289 {
3290 let anchor = snapshot.anchor_before(selection.end);
3291 new_selections.push((selection.map(|_| anchor), text.len()));
3292 new_autoclose_regions.push((
3293 anchor,
3294 text.len(),
3295 selection.id,
3296 bracket_pair.clone(),
3297 ));
3298 edits.push((
3299 selection.range(),
3300 format!("{}{}", text, bracket_pair.end).into(),
3301 ));
3302 bracket_inserted = true;
3303 continue;
3304 }
3305 }
3306
3307 if let Some(region) = autoclose_region {
3308 // If the selection is followed by an auto-inserted closing bracket,
3309 // then don't insert that closing bracket again; just move the selection
3310 // past the closing bracket.
3311 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3312 && text.as_ref() == region.pair.end.as_str();
3313 if should_skip {
3314 let anchor = snapshot.anchor_after(selection.end);
3315 new_selections
3316 .push((selection.map(|_| anchor), region.pair.end.len()));
3317 continue;
3318 }
3319 }
3320
3321 let always_treat_brackets_as_autoclosed = snapshot
3322 .settings_at(selection.start, cx)
3323 .always_treat_brackets_as_autoclosed;
3324 if always_treat_brackets_as_autoclosed
3325 && is_bracket_pair_end
3326 && snapshot.contains_str_at(selection.end, text.as_ref())
3327 {
3328 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3329 // and the inserted text is a closing bracket and the selection is followed
3330 // by the closing bracket then move the selection past the closing bracket.
3331 let anchor = snapshot.anchor_after(selection.end);
3332 new_selections.push((selection.map(|_| anchor), text.len()));
3333 continue;
3334 }
3335 }
3336 // If an opening bracket is 1 character long and is typed while
3337 // text is selected, then surround that text with the bracket pair.
3338 else if auto_surround
3339 && bracket_pair.surround
3340 && is_bracket_pair_start
3341 && bracket_pair.start.chars().count() == 1
3342 {
3343 edits.push((selection.start..selection.start, text.clone()));
3344 edits.push((
3345 selection.end..selection.end,
3346 bracket_pair.end.as_str().into(),
3347 ));
3348 bracket_inserted = true;
3349 new_selections.push((
3350 Selection {
3351 id: selection.id,
3352 start: snapshot.anchor_after(selection.start),
3353 end: snapshot.anchor_before(selection.end),
3354 reversed: selection.reversed,
3355 goal: selection.goal,
3356 },
3357 0,
3358 ));
3359 continue;
3360 }
3361 }
3362 }
3363
3364 if self.auto_replace_emoji_shortcode
3365 && selection.is_empty()
3366 && text.as_ref().ends_with(':')
3367 {
3368 if let Some(possible_emoji_short_code) =
3369 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3370 {
3371 if !possible_emoji_short_code.is_empty() {
3372 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3373 let emoji_shortcode_start = Point::new(
3374 selection.start.row,
3375 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3376 );
3377
3378 // Remove shortcode from buffer
3379 edits.push((
3380 emoji_shortcode_start..selection.start,
3381 "".to_string().into(),
3382 ));
3383 new_selections.push((
3384 Selection {
3385 id: selection.id,
3386 start: snapshot.anchor_after(emoji_shortcode_start),
3387 end: snapshot.anchor_before(selection.start),
3388 reversed: selection.reversed,
3389 goal: selection.goal,
3390 },
3391 0,
3392 ));
3393
3394 // Insert emoji
3395 let selection_start_anchor = snapshot.anchor_after(selection.start);
3396 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3397 edits.push((selection.start..selection.end, emoji.to_string().into()));
3398
3399 continue;
3400 }
3401 }
3402 }
3403 }
3404
3405 // If not handling any auto-close operation, then just replace the selected
3406 // text with the given input and move the selection to the end of the
3407 // newly inserted text.
3408 let anchor = snapshot.anchor_after(selection.end);
3409 if !self.linked_edit_ranges.is_empty() {
3410 let start_anchor = snapshot.anchor_before(selection.start);
3411
3412 let is_word_char = text.chars().next().map_or(true, |char| {
3413 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3414 classifier.is_word(char)
3415 });
3416
3417 if is_word_char {
3418 if let Some(ranges) = self
3419 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3420 {
3421 for (buffer, edits) in ranges {
3422 linked_edits
3423 .entry(buffer.clone())
3424 .or_default()
3425 .extend(edits.into_iter().map(|range| (range, text.clone())));
3426 }
3427 }
3428 }
3429 }
3430
3431 new_selections.push((selection.map(|_| anchor), 0));
3432 edits.push((selection.start..selection.end, text.clone()));
3433 }
3434
3435 drop(snapshot);
3436
3437 self.transact(cx, |this, cx| {
3438 this.buffer.update(cx, |buffer, cx| {
3439 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3440 });
3441 for (buffer, edits) in linked_edits {
3442 buffer.update(cx, |buffer, cx| {
3443 let snapshot = buffer.snapshot();
3444 let edits = edits
3445 .into_iter()
3446 .map(|(range, text)| {
3447 use text::ToPoint as TP;
3448 let end_point = TP::to_point(&range.end, &snapshot);
3449 let start_point = TP::to_point(&range.start, &snapshot);
3450 (start_point..end_point, text)
3451 })
3452 .sorted_by_key(|(range, _)| range.start)
3453 .collect::<Vec<_>>();
3454 buffer.edit(edits, None, cx);
3455 })
3456 }
3457 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3458 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3459 let snapshot = this.buffer.read(cx).read(cx);
3460 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3461 .zip(new_selection_deltas)
3462 .map(|(selection, delta)| Selection {
3463 id: selection.id,
3464 start: selection.start + delta,
3465 end: selection.end + delta,
3466 reversed: selection.reversed,
3467 goal: SelectionGoal::None,
3468 })
3469 .collect::<Vec<_>>();
3470
3471 let mut i = 0;
3472 for (position, delta, selection_id, pair) in new_autoclose_regions {
3473 let position = position.to_offset(&snapshot) + delta;
3474 let start = snapshot.anchor_before(position);
3475 let end = snapshot.anchor_after(position);
3476 while let Some(existing_state) = this.autoclose_regions.get(i) {
3477 match existing_state.range.start.cmp(&start, &snapshot) {
3478 Ordering::Less => i += 1,
3479 Ordering::Greater => break,
3480 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3481 Ordering::Less => i += 1,
3482 Ordering::Equal => break,
3483 Ordering::Greater => break,
3484 },
3485 }
3486 }
3487 this.autoclose_regions.insert(
3488 i,
3489 AutocloseRegion {
3490 selection_id,
3491 range: start..end,
3492 pair,
3493 },
3494 );
3495 }
3496
3497 drop(snapshot);
3498 let had_active_inline_completion = this.has_active_inline_completion(cx);
3499 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3500 s.select(new_selections)
3501 });
3502
3503 if !bracket_inserted {
3504 if let Some(on_type_format_task) =
3505 this.trigger_on_type_formatting(text.to_string(), cx)
3506 {
3507 on_type_format_task.detach_and_log_err(cx);
3508 }
3509 }
3510
3511 let editor_settings = EditorSettings::get_global(cx);
3512 if bracket_inserted
3513 && (editor_settings.auto_signature_help
3514 || editor_settings.show_signature_help_after_edits)
3515 {
3516 this.show_signature_help(&ShowSignatureHelp, cx);
3517 }
3518
3519 let trigger_in_words = !had_active_inline_completion;
3520 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3521 linked_editing_ranges::refresh_linked_ranges(this, cx);
3522 this.refresh_inline_completion(true, false, cx);
3523 });
3524 }
3525
3526 fn find_possible_emoji_shortcode_at_position(
3527 snapshot: &MultiBufferSnapshot,
3528 position: Point,
3529 ) -> Option<String> {
3530 let mut chars = Vec::new();
3531 let mut found_colon = false;
3532 for char in snapshot.reversed_chars_at(position).take(100) {
3533 // Found a possible emoji shortcode in the middle of the buffer
3534 if found_colon {
3535 if char.is_whitespace() {
3536 chars.reverse();
3537 return Some(chars.iter().collect());
3538 }
3539 // If the previous character is not a whitespace, we are in the middle of a word
3540 // and we only want to complete the shortcode if the word is made up of other emojis
3541 let mut containing_word = String::new();
3542 for ch in snapshot
3543 .reversed_chars_at(position)
3544 .skip(chars.len() + 1)
3545 .take(100)
3546 {
3547 if ch.is_whitespace() {
3548 break;
3549 }
3550 containing_word.push(ch);
3551 }
3552 let containing_word = containing_word.chars().rev().collect::<String>();
3553 if util::word_consists_of_emojis(containing_word.as_str()) {
3554 chars.reverse();
3555 return Some(chars.iter().collect());
3556 }
3557 }
3558
3559 if char.is_whitespace() || !char.is_ascii() {
3560 return None;
3561 }
3562 if char == ':' {
3563 found_colon = true;
3564 } else {
3565 chars.push(char);
3566 }
3567 }
3568 // Found a possible emoji shortcode at the beginning of the buffer
3569 chars.reverse();
3570 Some(chars.iter().collect())
3571 }
3572
3573 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3574 self.transact(cx, |this, cx| {
3575 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3576 let selections = this.selections.all::<usize>(cx);
3577 let multi_buffer = this.buffer.read(cx);
3578 let buffer = multi_buffer.snapshot(cx);
3579 selections
3580 .iter()
3581 .map(|selection| {
3582 let start_point = selection.start.to_point(&buffer);
3583 let mut indent =
3584 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3585 indent.len = cmp::min(indent.len, start_point.column);
3586 let start = selection.start;
3587 let end = selection.end;
3588 let selection_is_empty = start == end;
3589 let language_scope = buffer.language_scope_at(start);
3590 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3591 &language_scope
3592 {
3593 let leading_whitespace_len = buffer
3594 .reversed_chars_at(start)
3595 .take_while(|c| c.is_whitespace() && *c != '\n')
3596 .map(|c| c.len_utf8())
3597 .sum::<usize>();
3598
3599 let trailing_whitespace_len = buffer
3600 .chars_at(end)
3601 .take_while(|c| c.is_whitespace() && *c != '\n')
3602 .map(|c| c.len_utf8())
3603 .sum::<usize>();
3604
3605 let insert_extra_newline =
3606 language.brackets().any(|(pair, enabled)| {
3607 let pair_start = pair.start.trim_end();
3608 let pair_end = pair.end.trim_start();
3609
3610 enabled
3611 && pair.newline
3612 && buffer.contains_str_at(
3613 end + trailing_whitespace_len,
3614 pair_end,
3615 )
3616 && buffer.contains_str_at(
3617 (start - leading_whitespace_len)
3618 .saturating_sub(pair_start.len()),
3619 pair_start,
3620 )
3621 });
3622
3623 // Comment extension on newline is allowed only for cursor selections
3624 let comment_delimiter = maybe!({
3625 if !selection_is_empty {
3626 return None;
3627 }
3628
3629 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3630 return None;
3631 }
3632
3633 let delimiters = language.line_comment_prefixes();
3634 let max_len_of_delimiter =
3635 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3636 let (snapshot, range) =
3637 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3638
3639 let mut index_of_first_non_whitespace = 0;
3640 let comment_candidate = snapshot
3641 .chars_for_range(range)
3642 .skip_while(|c| {
3643 let should_skip = c.is_whitespace();
3644 if should_skip {
3645 index_of_first_non_whitespace += 1;
3646 }
3647 should_skip
3648 })
3649 .take(max_len_of_delimiter)
3650 .collect::<String>();
3651 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3652 comment_candidate.starts_with(comment_prefix.as_ref())
3653 })?;
3654 let cursor_is_placed_after_comment_marker =
3655 index_of_first_non_whitespace + comment_prefix.len()
3656 <= start_point.column as usize;
3657 if cursor_is_placed_after_comment_marker {
3658 Some(comment_prefix.clone())
3659 } else {
3660 None
3661 }
3662 });
3663 (comment_delimiter, insert_extra_newline)
3664 } else {
3665 (None, false)
3666 };
3667
3668 let capacity_for_delimiter = comment_delimiter
3669 .as_deref()
3670 .map(str::len)
3671 .unwrap_or_default();
3672 let mut new_text =
3673 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3674 new_text.push('\n');
3675 new_text.extend(indent.chars());
3676 if let Some(delimiter) = &comment_delimiter {
3677 new_text.push_str(delimiter);
3678 }
3679 if insert_extra_newline {
3680 new_text = new_text.repeat(2);
3681 }
3682
3683 let anchor = buffer.anchor_after(end);
3684 let new_selection = selection.map(|_| anchor);
3685 (
3686 (start..end, new_text),
3687 (insert_extra_newline, new_selection),
3688 )
3689 })
3690 .unzip()
3691 };
3692
3693 this.edit_with_autoindent(edits, cx);
3694 let buffer = this.buffer.read(cx).snapshot(cx);
3695 let new_selections = selection_fixup_info
3696 .into_iter()
3697 .map(|(extra_newline_inserted, new_selection)| {
3698 let mut cursor = new_selection.end.to_point(&buffer);
3699 if extra_newline_inserted {
3700 cursor.row -= 1;
3701 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3702 }
3703 new_selection.map(|_| cursor)
3704 })
3705 .collect();
3706
3707 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3708 this.refresh_inline_completion(true, false, cx);
3709 });
3710 }
3711
3712 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3713 let buffer = self.buffer.read(cx);
3714 let snapshot = buffer.snapshot(cx);
3715
3716 let mut edits = Vec::new();
3717 let mut rows = Vec::new();
3718
3719 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3720 let cursor = selection.head();
3721 let row = cursor.row;
3722
3723 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3724
3725 let newline = "\n".to_string();
3726 edits.push((start_of_line..start_of_line, newline));
3727
3728 rows.push(row + rows_inserted as u32);
3729 }
3730
3731 self.transact(cx, |editor, cx| {
3732 editor.edit(edits, cx);
3733
3734 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3735 let mut index = 0;
3736 s.move_cursors_with(|map, _, _| {
3737 let row = rows[index];
3738 index += 1;
3739
3740 let point = Point::new(row, 0);
3741 let boundary = map.next_line_boundary(point).1;
3742 let clipped = map.clip_point(boundary, Bias::Left);
3743
3744 (clipped, SelectionGoal::None)
3745 });
3746 });
3747
3748 let mut indent_edits = Vec::new();
3749 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3750 for row in rows {
3751 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3752 for (row, indent) in indents {
3753 if indent.len == 0 {
3754 continue;
3755 }
3756
3757 let text = match indent.kind {
3758 IndentKind::Space => " ".repeat(indent.len as usize),
3759 IndentKind::Tab => "\t".repeat(indent.len as usize),
3760 };
3761 let point = Point::new(row.0, 0);
3762 indent_edits.push((point..point, text));
3763 }
3764 }
3765 editor.edit(indent_edits, cx);
3766 });
3767 }
3768
3769 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3770 let buffer = self.buffer.read(cx);
3771 let snapshot = buffer.snapshot(cx);
3772
3773 let mut edits = Vec::new();
3774 let mut rows = Vec::new();
3775 let mut rows_inserted = 0;
3776
3777 for selection in self.selections.all_adjusted(cx) {
3778 let cursor = selection.head();
3779 let row = cursor.row;
3780
3781 let point = Point::new(row + 1, 0);
3782 let start_of_line = snapshot.clip_point(point, Bias::Left);
3783
3784 let newline = "\n".to_string();
3785 edits.push((start_of_line..start_of_line, newline));
3786
3787 rows_inserted += 1;
3788 rows.push(row + rows_inserted);
3789 }
3790
3791 self.transact(cx, |editor, cx| {
3792 editor.edit(edits, cx);
3793
3794 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3795 let mut index = 0;
3796 s.move_cursors_with(|map, _, _| {
3797 let row = rows[index];
3798 index += 1;
3799
3800 let point = Point::new(row, 0);
3801 let boundary = map.next_line_boundary(point).1;
3802 let clipped = map.clip_point(boundary, Bias::Left);
3803
3804 (clipped, SelectionGoal::None)
3805 });
3806 });
3807
3808 let mut indent_edits = Vec::new();
3809 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3810 for row in rows {
3811 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3812 for (row, indent) in indents {
3813 if indent.len == 0 {
3814 continue;
3815 }
3816
3817 let text = match indent.kind {
3818 IndentKind::Space => " ".repeat(indent.len as usize),
3819 IndentKind::Tab => "\t".repeat(indent.len as usize),
3820 };
3821 let point = Point::new(row.0, 0);
3822 indent_edits.push((point..point, text));
3823 }
3824 }
3825 editor.edit(indent_edits, cx);
3826 });
3827 }
3828
3829 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3830 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3831 original_indent_columns: Vec::new(),
3832 });
3833 self.insert_with_autoindent_mode(text, autoindent, cx);
3834 }
3835
3836 fn insert_with_autoindent_mode(
3837 &mut self,
3838 text: &str,
3839 autoindent_mode: Option<AutoindentMode>,
3840 cx: &mut ViewContext<Self>,
3841 ) {
3842 if self.read_only(cx) {
3843 return;
3844 }
3845
3846 let text: Arc<str> = text.into();
3847 self.transact(cx, |this, cx| {
3848 let old_selections = this.selections.all_adjusted(cx);
3849 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3850 let anchors = {
3851 let snapshot = buffer.read(cx);
3852 old_selections
3853 .iter()
3854 .map(|s| {
3855 let anchor = snapshot.anchor_after(s.head());
3856 s.map(|_| anchor)
3857 })
3858 .collect::<Vec<_>>()
3859 };
3860 buffer.edit(
3861 old_selections
3862 .iter()
3863 .map(|s| (s.start..s.end, text.clone())),
3864 autoindent_mode,
3865 cx,
3866 );
3867 anchors
3868 });
3869
3870 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3871 s.select_anchors(selection_anchors);
3872 })
3873 });
3874 }
3875
3876 fn trigger_completion_on_input(
3877 &mut self,
3878 text: &str,
3879 trigger_in_words: bool,
3880 cx: &mut ViewContext<Self>,
3881 ) {
3882 if self.is_completion_trigger(text, trigger_in_words, cx) {
3883 self.show_completions(
3884 &ShowCompletions {
3885 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3886 },
3887 cx,
3888 );
3889 } else {
3890 self.hide_context_menu(cx);
3891 }
3892 }
3893
3894 fn is_completion_trigger(
3895 &self,
3896 text: &str,
3897 trigger_in_words: bool,
3898 cx: &mut ViewContext<Self>,
3899 ) -> bool {
3900 let position = self.selections.newest_anchor().head();
3901 let multibuffer = self.buffer.read(cx);
3902 let Some(buffer) = position
3903 .buffer_id
3904 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3905 else {
3906 return false;
3907 };
3908
3909 if let Some(completion_provider) = &self.completion_provider {
3910 completion_provider.is_completion_trigger(
3911 &buffer,
3912 position.text_anchor,
3913 text,
3914 trigger_in_words,
3915 cx,
3916 )
3917 } else {
3918 false
3919 }
3920 }
3921
3922 /// If any empty selections is touching the start of its innermost containing autoclose
3923 /// region, expand it to select the brackets.
3924 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3925 let selections = self.selections.all::<usize>(cx);
3926 let buffer = self.buffer.read(cx).read(cx);
3927 let new_selections = self
3928 .selections_with_autoclose_regions(selections, &buffer)
3929 .map(|(mut selection, region)| {
3930 if !selection.is_empty() {
3931 return selection;
3932 }
3933
3934 if let Some(region) = region {
3935 let mut range = region.range.to_offset(&buffer);
3936 if selection.start == range.start && range.start >= region.pair.start.len() {
3937 range.start -= region.pair.start.len();
3938 if buffer.contains_str_at(range.start, ®ion.pair.start)
3939 && buffer.contains_str_at(range.end, ®ion.pair.end)
3940 {
3941 range.end += region.pair.end.len();
3942 selection.start = range.start;
3943 selection.end = range.end;
3944
3945 return selection;
3946 }
3947 }
3948 }
3949
3950 let always_treat_brackets_as_autoclosed = buffer
3951 .settings_at(selection.start, cx)
3952 .always_treat_brackets_as_autoclosed;
3953
3954 if !always_treat_brackets_as_autoclosed {
3955 return selection;
3956 }
3957
3958 if let Some(scope) = buffer.language_scope_at(selection.start) {
3959 for (pair, enabled) in scope.brackets() {
3960 if !enabled || !pair.close {
3961 continue;
3962 }
3963
3964 if buffer.contains_str_at(selection.start, &pair.end) {
3965 let pair_start_len = pair.start.len();
3966 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3967 {
3968 selection.start -= pair_start_len;
3969 selection.end += pair.end.len();
3970
3971 return selection;
3972 }
3973 }
3974 }
3975 }
3976
3977 selection
3978 })
3979 .collect();
3980
3981 drop(buffer);
3982 self.change_selections(None, cx, |selections| selections.select(new_selections));
3983 }
3984
3985 /// Iterate the given selections, and for each one, find the smallest surrounding
3986 /// autoclose region. This uses the ordering of the selections and the autoclose
3987 /// regions to avoid repeated comparisons.
3988 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3989 &'a self,
3990 selections: impl IntoIterator<Item = Selection<D>>,
3991 buffer: &'a MultiBufferSnapshot,
3992 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3993 let mut i = 0;
3994 let mut regions = self.autoclose_regions.as_slice();
3995 selections.into_iter().map(move |selection| {
3996 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3997
3998 let mut enclosing = None;
3999 while let Some(pair_state) = regions.get(i) {
4000 if pair_state.range.end.to_offset(buffer) < range.start {
4001 regions = ®ions[i + 1..];
4002 i = 0;
4003 } else if pair_state.range.start.to_offset(buffer) > range.end {
4004 break;
4005 } else {
4006 if pair_state.selection_id == selection.id {
4007 enclosing = Some(pair_state);
4008 }
4009 i += 1;
4010 }
4011 }
4012
4013 (selection.clone(), enclosing)
4014 })
4015 }
4016
4017 /// Remove any autoclose regions that no longer contain their selection.
4018 fn invalidate_autoclose_regions(
4019 &mut self,
4020 mut selections: &[Selection<Anchor>],
4021 buffer: &MultiBufferSnapshot,
4022 ) {
4023 self.autoclose_regions.retain(|state| {
4024 let mut i = 0;
4025 while let Some(selection) = selections.get(i) {
4026 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4027 selections = &selections[1..];
4028 continue;
4029 }
4030 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4031 break;
4032 }
4033 if selection.id == state.selection_id {
4034 return true;
4035 } else {
4036 i += 1;
4037 }
4038 }
4039 false
4040 });
4041 }
4042
4043 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4044 let offset = position.to_offset(buffer);
4045 let (word_range, kind) = buffer.surrounding_word(offset, true);
4046 if offset > word_range.start && kind == Some(CharKind::Word) {
4047 Some(
4048 buffer
4049 .text_for_range(word_range.start..offset)
4050 .collect::<String>(),
4051 )
4052 } else {
4053 None
4054 }
4055 }
4056
4057 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4058 self.refresh_inlay_hints(
4059 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4060 cx,
4061 );
4062 }
4063
4064 pub fn inlay_hints_enabled(&self) -> bool {
4065 self.inlay_hint_cache.enabled
4066 }
4067
4068 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4069 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4070 return;
4071 }
4072
4073 let reason_description = reason.description();
4074 let ignore_debounce = matches!(
4075 reason,
4076 InlayHintRefreshReason::SettingsChange(_)
4077 | InlayHintRefreshReason::Toggle(_)
4078 | InlayHintRefreshReason::ExcerptsRemoved(_)
4079 );
4080 let (invalidate_cache, required_languages) = match reason {
4081 InlayHintRefreshReason::Toggle(enabled) => {
4082 self.inlay_hint_cache.enabled = enabled;
4083 if enabled {
4084 (InvalidationStrategy::RefreshRequested, None)
4085 } else {
4086 self.inlay_hint_cache.clear();
4087 self.splice_inlays(
4088 self.visible_inlay_hints(cx)
4089 .iter()
4090 .map(|inlay| inlay.id)
4091 .collect(),
4092 Vec::new(),
4093 cx,
4094 );
4095 return;
4096 }
4097 }
4098 InlayHintRefreshReason::SettingsChange(new_settings) => {
4099 match self.inlay_hint_cache.update_settings(
4100 &self.buffer,
4101 new_settings,
4102 self.visible_inlay_hints(cx),
4103 cx,
4104 ) {
4105 ControlFlow::Break(Some(InlaySplice {
4106 to_remove,
4107 to_insert,
4108 })) => {
4109 self.splice_inlays(to_remove, to_insert, cx);
4110 return;
4111 }
4112 ControlFlow::Break(None) => return,
4113 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4114 }
4115 }
4116 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4117 if let Some(InlaySplice {
4118 to_remove,
4119 to_insert,
4120 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4121 {
4122 self.splice_inlays(to_remove, to_insert, cx);
4123 }
4124 return;
4125 }
4126 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4127 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4128 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4129 }
4130 InlayHintRefreshReason::RefreshRequested => {
4131 (InvalidationStrategy::RefreshRequested, None)
4132 }
4133 };
4134
4135 if let Some(InlaySplice {
4136 to_remove,
4137 to_insert,
4138 }) = self.inlay_hint_cache.spawn_hint_refresh(
4139 reason_description,
4140 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4141 invalidate_cache,
4142 ignore_debounce,
4143 cx,
4144 ) {
4145 self.splice_inlays(to_remove, to_insert, cx);
4146 }
4147 }
4148
4149 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4150 self.display_map
4151 .read(cx)
4152 .current_inlays()
4153 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4154 .cloned()
4155 .collect()
4156 }
4157
4158 pub fn excerpts_for_inlay_hints_query(
4159 &self,
4160 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4161 cx: &mut ViewContext<Editor>,
4162 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4163 let Some(project) = self.project.as_ref() else {
4164 return HashMap::default();
4165 };
4166 let project = project.read(cx);
4167 let multi_buffer = self.buffer().read(cx);
4168 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4169 let multi_buffer_visible_start = self
4170 .scroll_manager
4171 .anchor()
4172 .anchor
4173 .to_point(&multi_buffer_snapshot);
4174 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4175 multi_buffer_visible_start
4176 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4177 Bias::Left,
4178 );
4179 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4180 multi_buffer
4181 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4182 .into_iter()
4183 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4184 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4185 let buffer = buffer_handle.read(cx);
4186 let buffer_file = project::File::from_dyn(buffer.file())?;
4187 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4188 let worktree_entry = buffer_worktree
4189 .read(cx)
4190 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4191 if worktree_entry.is_ignored {
4192 return None;
4193 }
4194
4195 let language = buffer.language()?;
4196 if let Some(restrict_to_languages) = restrict_to_languages {
4197 if !restrict_to_languages.contains(language) {
4198 return None;
4199 }
4200 }
4201 Some((
4202 excerpt_id,
4203 (
4204 buffer_handle,
4205 buffer.version().clone(),
4206 excerpt_visible_range,
4207 ),
4208 ))
4209 })
4210 .collect()
4211 }
4212
4213 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4214 TextLayoutDetails {
4215 text_system: cx.text_system().clone(),
4216 editor_style: self.style.clone().unwrap(),
4217 rem_size: cx.rem_size(),
4218 scroll_anchor: self.scroll_manager.anchor(),
4219 visible_rows: self.visible_line_count(),
4220 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4221 }
4222 }
4223
4224 fn splice_inlays(
4225 &self,
4226 to_remove: Vec<InlayId>,
4227 to_insert: Vec<Inlay>,
4228 cx: &mut ViewContext<Self>,
4229 ) {
4230 self.display_map.update(cx, |display_map, cx| {
4231 display_map.splice_inlays(to_remove, to_insert, cx);
4232 });
4233 cx.notify();
4234 }
4235
4236 fn trigger_on_type_formatting(
4237 &self,
4238 input: String,
4239 cx: &mut ViewContext<Self>,
4240 ) -> Option<Task<Result<()>>> {
4241 if input.len() != 1 {
4242 return None;
4243 }
4244
4245 let project = self.project.as_ref()?;
4246 let position = self.selections.newest_anchor().head();
4247 let (buffer, buffer_position) = self
4248 .buffer
4249 .read(cx)
4250 .text_anchor_for_position(position, cx)?;
4251
4252 let settings = language_settings::language_settings(
4253 buffer
4254 .read(cx)
4255 .language_at(buffer_position)
4256 .map(|l| l.name()),
4257 buffer.read(cx).file(),
4258 cx,
4259 );
4260 if !settings.use_on_type_format {
4261 return None;
4262 }
4263
4264 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4265 // hence we do LSP request & edit on host side only — add formats to host's history.
4266 let push_to_lsp_host_history = true;
4267 // If this is not the host, append its history with new edits.
4268 let push_to_client_history = project.read(cx).is_via_collab();
4269
4270 let on_type_formatting = project.update(cx, |project, cx| {
4271 project.on_type_format(
4272 buffer.clone(),
4273 buffer_position,
4274 input,
4275 push_to_lsp_host_history,
4276 cx,
4277 )
4278 });
4279 Some(cx.spawn(|editor, mut cx| async move {
4280 if let Some(transaction) = on_type_formatting.await? {
4281 if push_to_client_history {
4282 buffer
4283 .update(&mut cx, |buffer, _| {
4284 buffer.push_transaction(transaction, Instant::now());
4285 })
4286 .ok();
4287 }
4288 editor.update(&mut cx, |editor, cx| {
4289 editor.refresh_document_highlights(cx);
4290 })?;
4291 }
4292 Ok(())
4293 }))
4294 }
4295
4296 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4297 if self.pending_rename.is_some() {
4298 return;
4299 }
4300
4301 let Some(provider) = self.completion_provider.as_ref() else {
4302 return;
4303 };
4304
4305 let position = self.selections.newest_anchor().head();
4306 let (buffer, buffer_position) =
4307 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4308 output
4309 } else {
4310 return;
4311 };
4312
4313 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4314 let is_followup_invoke = {
4315 let context_menu_state = self.context_menu.read();
4316 matches!(
4317 context_menu_state.deref(),
4318 Some(ContextMenu::Completions(_))
4319 )
4320 };
4321 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4322 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4323 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4324 CompletionTriggerKind::TRIGGER_CHARACTER
4325 }
4326
4327 _ => CompletionTriggerKind::INVOKED,
4328 };
4329 let completion_context = CompletionContext {
4330 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4331 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4332 Some(String::from(trigger))
4333 } else {
4334 None
4335 }
4336 }),
4337 trigger_kind,
4338 };
4339 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4340 let sort_completions = provider.sort_completions();
4341
4342 let id = post_inc(&mut self.next_completion_id);
4343 let task = cx.spawn(|this, mut cx| {
4344 async move {
4345 this.update(&mut cx, |this, _| {
4346 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4347 })?;
4348 let completions = completions.await.log_err();
4349 let menu = if let Some(completions) = completions {
4350 let mut menu = CompletionsMenu {
4351 id,
4352 sort_completions,
4353 initial_position: position,
4354 match_candidates: completions
4355 .iter()
4356 .enumerate()
4357 .map(|(id, completion)| {
4358 StringMatchCandidate::new(
4359 id,
4360 completion.label.text[completion.label.filter_range.clone()]
4361 .into(),
4362 )
4363 })
4364 .collect(),
4365 buffer: buffer.clone(),
4366 completions: Arc::new(RwLock::new(completions.into())),
4367 matches: Vec::new().into(),
4368 selected_item: 0,
4369 scroll_handle: UniformListScrollHandle::new(),
4370 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4371 DebouncedDelay::new(),
4372 )),
4373 };
4374 menu.filter(query.as_deref(), cx.background_executor().clone())
4375 .await;
4376
4377 if menu.matches.is_empty() {
4378 None
4379 } else {
4380 this.update(&mut cx, |editor, cx| {
4381 let completions = menu.completions.clone();
4382 let matches = menu.matches.clone();
4383
4384 let delay_ms = EditorSettings::get_global(cx)
4385 .completion_documentation_secondary_query_debounce;
4386 let delay = Duration::from_millis(delay_ms);
4387 editor
4388 .completion_documentation_pre_resolve_debounce
4389 .fire_new(delay, cx, |editor, cx| {
4390 CompletionsMenu::pre_resolve_completion_documentation(
4391 buffer,
4392 completions,
4393 matches,
4394 editor,
4395 cx,
4396 )
4397 });
4398 })
4399 .ok();
4400 Some(menu)
4401 }
4402 } else {
4403 None
4404 };
4405
4406 this.update(&mut cx, |this, cx| {
4407 let mut context_menu = this.context_menu.write();
4408 match context_menu.as_ref() {
4409 None => {}
4410
4411 Some(ContextMenu::Completions(prev_menu)) => {
4412 if prev_menu.id > id {
4413 return;
4414 }
4415 }
4416
4417 _ => return,
4418 }
4419
4420 if this.focus_handle.is_focused(cx) && menu.is_some() {
4421 let menu = menu.unwrap();
4422 *context_menu = Some(ContextMenu::Completions(menu));
4423 drop(context_menu);
4424 this.discard_inline_completion(false, cx);
4425 cx.notify();
4426 } else if this.completion_tasks.len() <= 1 {
4427 // If there are no more completion tasks and the last menu was
4428 // empty, we should hide it. If it was already hidden, we should
4429 // also show the copilot completion when available.
4430 drop(context_menu);
4431 if this.hide_context_menu(cx).is_none() {
4432 this.update_visible_inline_completion(cx);
4433 }
4434 }
4435 })?;
4436
4437 Ok::<_, anyhow::Error>(())
4438 }
4439 .log_err()
4440 });
4441
4442 self.completion_tasks.push((id, task));
4443 }
4444
4445 pub fn confirm_completion(
4446 &mut self,
4447 action: &ConfirmCompletion,
4448 cx: &mut ViewContext<Self>,
4449 ) -> Option<Task<Result<()>>> {
4450 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4451 }
4452
4453 pub fn compose_completion(
4454 &mut self,
4455 action: &ComposeCompletion,
4456 cx: &mut ViewContext<Self>,
4457 ) -> Option<Task<Result<()>>> {
4458 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4459 }
4460
4461 fn do_completion(
4462 &mut self,
4463 item_ix: Option<usize>,
4464 intent: CompletionIntent,
4465 cx: &mut ViewContext<Editor>,
4466 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4467 use language::ToOffset as _;
4468
4469 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4470 menu
4471 } else {
4472 return None;
4473 };
4474
4475 let mat = completions_menu
4476 .matches
4477 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4478 let buffer_handle = completions_menu.buffer;
4479 let completions = completions_menu.completions.read();
4480 let completion = completions.get(mat.candidate_id)?;
4481 cx.stop_propagation();
4482
4483 let snippet;
4484 let text;
4485
4486 if completion.is_snippet() {
4487 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4488 text = snippet.as_ref().unwrap().text.clone();
4489 } else {
4490 snippet = None;
4491 text = completion.new_text.clone();
4492 };
4493 let selections = self.selections.all::<usize>(cx);
4494 let buffer = buffer_handle.read(cx);
4495 let old_range = completion.old_range.to_offset(buffer);
4496 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4497
4498 let newest_selection = self.selections.newest_anchor();
4499 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4500 return None;
4501 }
4502
4503 let lookbehind = newest_selection
4504 .start
4505 .text_anchor
4506 .to_offset(buffer)
4507 .saturating_sub(old_range.start);
4508 let lookahead = old_range
4509 .end
4510 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4511 let mut common_prefix_len = old_text
4512 .bytes()
4513 .zip(text.bytes())
4514 .take_while(|(a, b)| a == b)
4515 .count();
4516
4517 let snapshot = self.buffer.read(cx).snapshot(cx);
4518 let mut range_to_replace: Option<Range<isize>> = None;
4519 let mut ranges = Vec::new();
4520 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4521 for selection in &selections {
4522 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4523 let start = selection.start.saturating_sub(lookbehind);
4524 let end = selection.end + lookahead;
4525 if selection.id == newest_selection.id {
4526 range_to_replace = Some(
4527 ((start + common_prefix_len) as isize - selection.start as isize)
4528 ..(end as isize - selection.start as isize),
4529 );
4530 }
4531 ranges.push(start + common_prefix_len..end);
4532 } else {
4533 common_prefix_len = 0;
4534 ranges.clear();
4535 ranges.extend(selections.iter().map(|s| {
4536 if s.id == newest_selection.id {
4537 range_to_replace = Some(
4538 old_range.start.to_offset_utf16(&snapshot).0 as isize
4539 - selection.start as isize
4540 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4541 - selection.start as isize,
4542 );
4543 old_range.clone()
4544 } else {
4545 s.start..s.end
4546 }
4547 }));
4548 break;
4549 }
4550 if !self.linked_edit_ranges.is_empty() {
4551 let start_anchor = snapshot.anchor_before(selection.head());
4552 let end_anchor = snapshot.anchor_after(selection.tail());
4553 if let Some(ranges) = self
4554 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4555 {
4556 for (buffer, edits) in ranges {
4557 linked_edits.entry(buffer.clone()).or_default().extend(
4558 edits
4559 .into_iter()
4560 .map(|range| (range, text[common_prefix_len..].to_owned())),
4561 );
4562 }
4563 }
4564 }
4565 }
4566 let text = &text[common_prefix_len..];
4567
4568 cx.emit(EditorEvent::InputHandled {
4569 utf16_range_to_replace: range_to_replace,
4570 text: text.into(),
4571 });
4572
4573 self.transact(cx, |this, cx| {
4574 if let Some(mut snippet) = snippet {
4575 snippet.text = text.to_string();
4576 for tabstop in snippet.tabstops.iter_mut().flatten() {
4577 tabstop.start -= common_prefix_len as isize;
4578 tabstop.end -= common_prefix_len as isize;
4579 }
4580
4581 this.insert_snippet(&ranges, snippet, cx).log_err();
4582 } else {
4583 this.buffer.update(cx, |buffer, cx| {
4584 buffer.edit(
4585 ranges.iter().map(|range| (range.clone(), text)),
4586 this.autoindent_mode.clone(),
4587 cx,
4588 );
4589 });
4590 }
4591 for (buffer, edits) in linked_edits {
4592 buffer.update(cx, |buffer, cx| {
4593 let snapshot = buffer.snapshot();
4594 let edits = edits
4595 .into_iter()
4596 .map(|(range, text)| {
4597 use text::ToPoint as TP;
4598 let end_point = TP::to_point(&range.end, &snapshot);
4599 let start_point = TP::to_point(&range.start, &snapshot);
4600 (start_point..end_point, text)
4601 })
4602 .sorted_by_key(|(range, _)| range.start)
4603 .collect::<Vec<_>>();
4604 buffer.edit(edits, None, cx);
4605 })
4606 }
4607
4608 this.refresh_inline_completion(true, false, cx);
4609 });
4610
4611 let show_new_completions_on_confirm = completion
4612 .confirm
4613 .as_ref()
4614 .map_or(false, |confirm| confirm(intent, cx));
4615 if show_new_completions_on_confirm {
4616 self.show_completions(&ShowCompletions { trigger: None }, cx);
4617 }
4618
4619 let provider = self.completion_provider.as_ref()?;
4620 let apply_edits = provider.apply_additional_edits_for_completion(
4621 buffer_handle,
4622 completion.clone(),
4623 true,
4624 cx,
4625 );
4626
4627 let editor_settings = EditorSettings::get_global(cx);
4628 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4629 // After the code completion is finished, users often want to know what signatures are needed.
4630 // so we should automatically call signature_help
4631 self.show_signature_help(&ShowSignatureHelp, cx);
4632 }
4633
4634 Some(cx.foreground_executor().spawn(async move {
4635 apply_edits.await?;
4636 Ok(())
4637 }))
4638 }
4639
4640 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4641 let mut context_menu = self.context_menu.write();
4642 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4643 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4644 // Toggle if we're selecting the same one
4645 *context_menu = None;
4646 cx.notify();
4647 return;
4648 } else {
4649 // Otherwise, clear it and start a new one
4650 *context_menu = None;
4651 cx.notify();
4652 }
4653 }
4654 drop(context_menu);
4655 let snapshot = self.snapshot(cx);
4656 let deployed_from_indicator = action.deployed_from_indicator;
4657 let mut task = self.code_actions_task.take();
4658 let action = action.clone();
4659 cx.spawn(|editor, mut cx| async move {
4660 while let Some(prev_task) = task {
4661 prev_task.await.log_err();
4662 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4663 }
4664
4665 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4666 if editor.focus_handle.is_focused(cx) {
4667 let multibuffer_point = action
4668 .deployed_from_indicator
4669 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4670 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4671 let (buffer, buffer_row) = snapshot
4672 .buffer_snapshot
4673 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4674 .and_then(|(buffer_snapshot, range)| {
4675 editor
4676 .buffer
4677 .read(cx)
4678 .buffer(buffer_snapshot.remote_id())
4679 .map(|buffer| (buffer, range.start.row))
4680 })?;
4681 let (_, code_actions) = editor
4682 .available_code_actions
4683 .clone()
4684 .and_then(|(location, code_actions)| {
4685 let snapshot = location.buffer.read(cx).snapshot();
4686 let point_range = location.range.to_point(&snapshot);
4687 let point_range = point_range.start.row..=point_range.end.row;
4688 if point_range.contains(&buffer_row) {
4689 Some((location, code_actions))
4690 } else {
4691 None
4692 }
4693 })
4694 .unzip();
4695 let buffer_id = buffer.read(cx).remote_id();
4696 let tasks = editor
4697 .tasks
4698 .get(&(buffer_id, buffer_row))
4699 .map(|t| Arc::new(t.to_owned()));
4700 if tasks.is_none() && code_actions.is_none() {
4701 return None;
4702 }
4703
4704 editor.completion_tasks.clear();
4705 editor.discard_inline_completion(false, cx);
4706 let task_context =
4707 tasks
4708 .as_ref()
4709 .zip(editor.project.clone())
4710 .map(|(tasks, project)| {
4711 let position = Point::new(buffer_row, tasks.column);
4712 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4713 let location = Location {
4714 buffer: buffer.clone(),
4715 range: range_start..range_start,
4716 };
4717 // Fill in the environmental variables from the tree-sitter captures
4718 let mut captured_task_variables = TaskVariables::default();
4719 for (capture_name, value) in tasks.extra_variables.clone() {
4720 captured_task_variables.insert(
4721 task::VariableName::Custom(capture_name.into()),
4722 value.clone(),
4723 );
4724 }
4725 project.update(cx, |project, cx| {
4726 project.task_store().update(cx, |task_store, cx| {
4727 task_store.task_context_for_location(
4728 captured_task_variables,
4729 location,
4730 cx,
4731 )
4732 })
4733 })
4734 });
4735
4736 Some(cx.spawn(|editor, mut cx| async move {
4737 let task_context = match task_context {
4738 Some(task_context) => task_context.await,
4739 None => None,
4740 };
4741 let resolved_tasks =
4742 tasks.zip(task_context).map(|(tasks, task_context)| {
4743 Arc::new(ResolvedTasks {
4744 templates: tasks
4745 .templates
4746 .iter()
4747 .filter_map(|(kind, template)| {
4748 template
4749 .resolve_task(&kind.to_id_base(), &task_context)
4750 .map(|task| (kind.clone(), task))
4751 })
4752 .collect(),
4753 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4754 multibuffer_point.row,
4755 tasks.column,
4756 )),
4757 })
4758 });
4759 let spawn_straight_away = resolved_tasks
4760 .as_ref()
4761 .map_or(false, |tasks| tasks.templates.len() == 1)
4762 && code_actions
4763 .as_ref()
4764 .map_or(true, |actions| actions.is_empty());
4765 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4766 *editor.context_menu.write() =
4767 Some(ContextMenu::CodeActions(CodeActionsMenu {
4768 buffer,
4769 actions: CodeActionContents {
4770 tasks: resolved_tasks,
4771 actions: code_actions,
4772 },
4773 selected_item: Default::default(),
4774 scroll_handle: UniformListScrollHandle::default(),
4775 deployed_from_indicator,
4776 }));
4777 if spawn_straight_away {
4778 if let Some(task) = editor.confirm_code_action(
4779 &ConfirmCodeAction { item_ix: Some(0) },
4780 cx,
4781 ) {
4782 cx.notify();
4783 return task;
4784 }
4785 }
4786 cx.notify();
4787 Task::ready(Ok(()))
4788 }) {
4789 task.await
4790 } else {
4791 Ok(())
4792 }
4793 }))
4794 } else {
4795 Some(Task::ready(Ok(())))
4796 }
4797 })?;
4798 if let Some(task) = spawned_test_task {
4799 task.await?;
4800 }
4801
4802 Ok::<_, anyhow::Error>(())
4803 })
4804 .detach_and_log_err(cx);
4805 }
4806
4807 pub fn confirm_code_action(
4808 &mut self,
4809 action: &ConfirmCodeAction,
4810 cx: &mut ViewContext<Self>,
4811 ) -> Option<Task<Result<()>>> {
4812 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4813 menu
4814 } else {
4815 return None;
4816 };
4817 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4818 let action = actions_menu.actions.get(action_ix)?;
4819 let title = action.label();
4820 let buffer = actions_menu.buffer;
4821 let workspace = self.workspace()?;
4822
4823 match action {
4824 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4825 workspace.update(cx, |workspace, cx| {
4826 workspace::tasks::schedule_resolved_task(
4827 workspace,
4828 task_source_kind,
4829 resolved_task,
4830 false,
4831 cx,
4832 );
4833
4834 Some(Task::ready(Ok(())))
4835 })
4836 }
4837 CodeActionsItem::CodeAction {
4838 excerpt_id,
4839 action,
4840 provider,
4841 } => {
4842 let apply_code_action =
4843 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4844 let workspace = workspace.downgrade();
4845 Some(cx.spawn(|editor, cx| async move {
4846 let project_transaction = apply_code_action.await?;
4847 Self::open_project_transaction(
4848 &editor,
4849 workspace,
4850 project_transaction,
4851 title,
4852 cx,
4853 )
4854 .await
4855 }))
4856 }
4857 }
4858 }
4859
4860 pub async fn open_project_transaction(
4861 this: &WeakView<Editor>,
4862 workspace: WeakView<Workspace>,
4863 transaction: ProjectTransaction,
4864 title: String,
4865 mut cx: AsyncWindowContext,
4866 ) -> Result<()> {
4867 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4868 cx.update(|cx| {
4869 entries.sort_unstable_by_key(|(buffer, _)| {
4870 buffer.read(cx).file().map(|f| f.path().clone())
4871 });
4872 })?;
4873
4874 // If the project transaction's edits are all contained within this editor, then
4875 // avoid opening a new editor to display them.
4876
4877 if let Some((buffer, transaction)) = entries.first() {
4878 if entries.len() == 1 {
4879 let excerpt = this.update(&mut cx, |editor, cx| {
4880 editor
4881 .buffer()
4882 .read(cx)
4883 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4884 })?;
4885 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4886 if excerpted_buffer == *buffer {
4887 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4888 let excerpt_range = excerpt_range.to_offset(buffer);
4889 buffer
4890 .edited_ranges_for_transaction::<usize>(transaction)
4891 .all(|range| {
4892 excerpt_range.start <= range.start
4893 && excerpt_range.end >= range.end
4894 })
4895 })?;
4896
4897 if all_edits_within_excerpt {
4898 return Ok(());
4899 }
4900 }
4901 }
4902 }
4903 } else {
4904 return Ok(());
4905 }
4906
4907 let mut ranges_to_highlight = Vec::new();
4908 let excerpt_buffer = cx.new_model(|cx| {
4909 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4910 for (buffer_handle, transaction) in &entries {
4911 let buffer = buffer_handle.read(cx);
4912 ranges_to_highlight.extend(
4913 multibuffer.push_excerpts_with_context_lines(
4914 buffer_handle.clone(),
4915 buffer
4916 .edited_ranges_for_transaction::<usize>(transaction)
4917 .collect(),
4918 DEFAULT_MULTIBUFFER_CONTEXT,
4919 cx,
4920 ),
4921 );
4922 }
4923 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4924 multibuffer
4925 })?;
4926
4927 workspace.update(&mut cx, |workspace, cx| {
4928 let project = workspace.project().clone();
4929 let editor =
4930 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4931 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4932 editor.update(cx, |editor, cx| {
4933 editor.highlight_background::<Self>(
4934 &ranges_to_highlight,
4935 |theme| theme.editor_highlighted_line_background,
4936 cx,
4937 );
4938 });
4939 })?;
4940
4941 Ok(())
4942 }
4943
4944 pub fn clear_code_action_providers(&mut self) {
4945 self.code_action_providers.clear();
4946 self.available_code_actions.take();
4947 }
4948
4949 pub fn push_code_action_provider(
4950 &mut self,
4951 provider: Arc<dyn CodeActionProvider>,
4952 cx: &mut ViewContext<Self>,
4953 ) {
4954 self.code_action_providers.push(provider);
4955 self.refresh_code_actions(cx);
4956 }
4957
4958 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4959 let buffer = self.buffer.read(cx);
4960 let newest_selection = self.selections.newest_anchor().clone();
4961 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4962 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4963 if start_buffer != end_buffer {
4964 return None;
4965 }
4966
4967 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4968 cx.background_executor()
4969 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4970 .await;
4971
4972 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4973 let providers = this.code_action_providers.clone();
4974 let tasks = this
4975 .code_action_providers
4976 .iter()
4977 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4978 .collect::<Vec<_>>();
4979 (providers, tasks)
4980 })?;
4981
4982 let mut actions = Vec::new();
4983 for (provider, provider_actions) in
4984 providers.into_iter().zip(future::join_all(tasks).await)
4985 {
4986 if let Some(provider_actions) = provider_actions.log_err() {
4987 actions.extend(provider_actions.into_iter().map(|action| {
4988 AvailableCodeAction {
4989 excerpt_id: newest_selection.start.excerpt_id,
4990 action,
4991 provider: provider.clone(),
4992 }
4993 }));
4994 }
4995 }
4996
4997 this.update(&mut cx, |this, cx| {
4998 this.available_code_actions = if actions.is_empty() {
4999 None
5000 } else {
5001 Some((
5002 Location {
5003 buffer: start_buffer,
5004 range: start..end,
5005 },
5006 actions.into(),
5007 ))
5008 };
5009 cx.notify();
5010 })
5011 }));
5012 None
5013 }
5014
5015 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5016 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5017 self.show_git_blame_inline = false;
5018
5019 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5020 cx.background_executor().timer(delay).await;
5021
5022 this.update(&mut cx, |this, cx| {
5023 this.show_git_blame_inline = true;
5024 cx.notify();
5025 })
5026 .log_err();
5027 }));
5028 }
5029 }
5030
5031 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5032 if self.pending_rename.is_some() {
5033 return None;
5034 }
5035
5036 let provider = self.semantics_provider.clone()?;
5037 let buffer = self.buffer.read(cx);
5038 let newest_selection = self.selections.newest_anchor().clone();
5039 let cursor_position = newest_selection.head();
5040 let (cursor_buffer, cursor_buffer_position) =
5041 buffer.text_anchor_for_position(cursor_position, cx)?;
5042 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5043 if cursor_buffer != tail_buffer {
5044 return None;
5045 }
5046
5047 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5048 cx.background_executor()
5049 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5050 .await;
5051
5052 let highlights = if let Some(highlights) = cx
5053 .update(|cx| {
5054 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5055 })
5056 .ok()
5057 .flatten()
5058 {
5059 highlights.await.log_err()
5060 } else {
5061 None
5062 };
5063
5064 if let Some(highlights) = highlights {
5065 this.update(&mut cx, |this, cx| {
5066 if this.pending_rename.is_some() {
5067 return;
5068 }
5069
5070 let buffer_id = cursor_position.buffer_id;
5071 let buffer = this.buffer.read(cx);
5072 if !buffer
5073 .text_anchor_for_position(cursor_position, cx)
5074 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5075 {
5076 return;
5077 }
5078
5079 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5080 let mut write_ranges = Vec::new();
5081 let mut read_ranges = Vec::new();
5082 for highlight in highlights {
5083 for (excerpt_id, excerpt_range) in
5084 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5085 {
5086 let start = highlight
5087 .range
5088 .start
5089 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5090 let end = highlight
5091 .range
5092 .end
5093 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5094 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5095 continue;
5096 }
5097
5098 let range = Anchor {
5099 buffer_id,
5100 excerpt_id,
5101 text_anchor: start,
5102 }..Anchor {
5103 buffer_id,
5104 excerpt_id,
5105 text_anchor: end,
5106 };
5107 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5108 write_ranges.push(range);
5109 } else {
5110 read_ranges.push(range);
5111 }
5112 }
5113 }
5114
5115 this.highlight_background::<DocumentHighlightRead>(
5116 &read_ranges,
5117 |theme| theme.editor_document_highlight_read_background,
5118 cx,
5119 );
5120 this.highlight_background::<DocumentHighlightWrite>(
5121 &write_ranges,
5122 |theme| theme.editor_document_highlight_write_background,
5123 cx,
5124 );
5125 cx.notify();
5126 })
5127 .log_err();
5128 }
5129 }));
5130 None
5131 }
5132
5133 pub fn refresh_inline_completion(
5134 &mut self,
5135 debounce: bool,
5136 user_requested: bool,
5137 cx: &mut ViewContext<Self>,
5138 ) -> Option<()> {
5139 let provider = self.inline_completion_provider()?;
5140 let cursor = self.selections.newest_anchor().head();
5141 let (buffer, cursor_buffer_position) =
5142 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5143
5144 if !user_requested
5145 && (!self.enable_inline_completions
5146 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5147 {
5148 self.discard_inline_completion(false, cx);
5149 return None;
5150 }
5151
5152 self.update_visible_inline_completion(cx);
5153 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5154 Some(())
5155 }
5156
5157 fn cycle_inline_completion(
5158 &mut self,
5159 direction: Direction,
5160 cx: &mut ViewContext<Self>,
5161 ) -> Option<()> {
5162 let provider = self.inline_completion_provider()?;
5163 let cursor = self.selections.newest_anchor().head();
5164 let (buffer, cursor_buffer_position) =
5165 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5166 if !self.enable_inline_completions
5167 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5168 {
5169 return None;
5170 }
5171
5172 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5173 self.update_visible_inline_completion(cx);
5174
5175 Some(())
5176 }
5177
5178 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5179 if !self.has_active_inline_completion(cx) {
5180 self.refresh_inline_completion(false, true, cx);
5181 return;
5182 }
5183
5184 self.update_visible_inline_completion(cx);
5185 }
5186
5187 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5188 self.show_cursor_names(cx);
5189 }
5190
5191 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5192 self.show_cursor_names = true;
5193 cx.notify();
5194 cx.spawn(|this, mut cx| async move {
5195 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5196 this.update(&mut cx, |this, cx| {
5197 this.show_cursor_names = false;
5198 cx.notify()
5199 })
5200 .ok()
5201 })
5202 .detach();
5203 }
5204
5205 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5206 if self.has_active_inline_completion(cx) {
5207 self.cycle_inline_completion(Direction::Next, cx);
5208 } else {
5209 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5210 if is_copilot_disabled {
5211 cx.propagate();
5212 }
5213 }
5214 }
5215
5216 pub fn previous_inline_completion(
5217 &mut self,
5218 _: &PreviousInlineCompletion,
5219 cx: &mut ViewContext<Self>,
5220 ) {
5221 if self.has_active_inline_completion(cx) {
5222 self.cycle_inline_completion(Direction::Prev, cx);
5223 } else {
5224 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5225 if is_copilot_disabled {
5226 cx.propagate();
5227 }
5228 }
5229 }
5230
5231 pub fn accept_inline_completion(
5232 &mut self,
5233 _: &AcceptInlineCompletion,
5234 cx: &mut ViewContext<Self>,
5235 ) {
5236 let Some(completion) = self.take_active_inline_completion(cx) else {
5237 return;
5238 };
5239 if let Some(provider) = self.inline_completion_provider() {
5240 provider.accept(cx);
5241 }
5242
5243 cx.emit(EditorEvent::InputHandled {
5244 utf16_range_to_replace: None,
5245 text: completion.text.to_string().into(),
5246 });
5247
5248 if let Some(range) = completion.delete_range {
5249 self.change_selections(None, cx, |s| s.select_ranges([range]))
5250 }
5251 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5252 self.refresh_inline_completion(true, true, cx);
5253 cx.notify();
5254 }
5255
5256 pub fn accept_partial_inline_completion(
5257 &mut self,
5258 _: &AcceptPartialInlineCompletion,
5259 cx: &mut ViewContext<Self>,
5260 ) {
5261 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5262 if let Some(completion) = self.take_active_inline_completion(cx) {
5263 let mut partial_completion = completion
5264 .text
5265 .chars()
5266 .by_ref()
5267 .take_while(|c| c.is_alphabetic())
5268 .collect::<String>();
5269 if partial_completion.is_empty() {
5270 partial_completion = completion
5271 .text
5272 .chars()
5273 .by_ref()
5274 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5275 .collect::<String>();
5276 }
5277
5278 cx.emit(EditorEvent::InputHandled {
5279 utf16_range_to_replace: None,
5280 text: partial_completion.clone().into(),
5281 });
5282
5283 if let Some(range) = completion.delete_range {
5284 self.change_selections(None, cx, |s| s.select_ranges([range]))
5285 }
5286 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5287
5288 self.refresh_inline_completion(true, true, cx);
5289 cx.notify();
5290 }
5291 }
5292 }
5293
5294 fn discard_inline_completion(
5295 &mut self,
5296 should_report_inline_completion_event: bool,
5297 cx: &mut ViewContext<Self>,
5298 ) -> bool {
5299 if let Some(provider) = self.inline_completion_provider() {
5300 provider.discard(should_report_inline_completion_event, cx);
5301 }
5302
5303 self.take_active_inline_completion(cx).is_some()
5304 }
5305
5306 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5307 if let Some(completion) = self.active_inline_completion.as_ref() {
5308 let buffer = self.buffer.read(cx).read(cx);
5309 completion.position.is_valid(&buffer)
5310 } else {
5311 false
5312 }
5313 }
5314
5315 fn take_active_inline_completion(
5316 &mut self,
5317 cx: &mut ViewContext<Self>,
5318 ) -> Option<CompletionState> {
5319 let completion = self.active_inline_completion.take()?;
5320 let render_inlay_ids = completion.render_inlay_ids.clone();
5321 self.display_map.update(cx, |map, cx| {
5322 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5323 });
5324 let buffer = self.buffer.read(cx).read(cx);
5325
5326 if completion.position.is_valid(&buffer) {
5327 Some(completion)
5328 } else {
5329 None
5330 }
5331 }
5332
5333 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5334 let selection = self.selections.newest_anchor();
5335 let cursor = selection.head();
5336
5337 let excerpt_id = cursor.excerpt_id;
5338
5339 if self.context_menu.read().is_none()
5340 && self.completion_tasks.is_empty()
5341 && selection.start == selection.end
5342 {
5343 if let Some(provider) = self.inline_completion_provider() {
5344 if let Some((buffer, cursor_buffer_position)) =
5345 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5346 {
5347 if let Some(proposal) =
5348 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5349 {
5350 let mut to_remove = Vec::new();
5351 if let Some(completion) = self.active_inline_completion.take() {
5352 to_remove.extend(completion.render_inlay_ids.iter());
5353 }
5354
5355 let to_add = proposal
5356 .inlays
5357 .iter()
5358 .filter_map(|inlay| {
5359 let snapshot = self.buffer.read(cx).snapshot(cx);
5360 let id = post_inc(&mut self.next_inlay_id);
5361 match inlay {
5362 InlayProposal::Hint(position, hint) => {
5363 let position =
5364 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5365 Some(Inlay::hint(id, position, hint))
5366 }
5367 InlayProposal::Suggestion(position, text) => {
5368 let position =
5369 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5370 Some(Inlay::suggestion(id, position, text.clone()))
5371 }
5372 }
5373 })
5374 .collect_vec();
5375
5376 self.active_inline_completion = Some(CompletionState {
5377 position: cursor,
5378 text: proposal.text,
5379 delete_range: proposal.delete_range.and_then(|range| {
5380 let snapshot = self.buffer.read(cx).snapshot(cx);
5381 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5382 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5383 Some(start?..end?)
5384 }),
5385 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5386 });
5387
5388 self.display_map
5389 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5390
5391 cx.notify();
5392 return;
5393 }
5394 }
5395 }
5396 }
5397
5398 self.discard_inline_completion(false, cx);
5399 }
5400
5401 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5402 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5403 }
5404
5405 fn render_code_actions_indicator(
5406 &self,
5407 _style: &EditorStyle,
5408 row: DisplayRow,
5409 is_active: bool,
5410 cx: &mut ViewContext<Self>,
5411 ) -> Option<IconButton> {
5412 if self.available_code_actions.is_some() {
5413 Some(
5414 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5415 .shape(ui::IconButtonShape::Square)
5416 .icon_size(IconSize::XSmall)
5417 .icon_color(Color::Muted)
5418 .selected(is_active)
5419 .tooltip({
5420 let focus_handle = self.focus_handle.clone();
5421 move |cx| {
5422 Tooltip::for_action_in(
5423 "Toggle Code Actions",
5424 &ToggleCodeActions {
5425 deployed_from_indicator: None,
5426 },
5427 &focus_handle,
5428 cx,
5429 )
5430 }
5431 })
5432 .on_click(cx.listener(move |editor, _e, cx| {
5433 editor.focus(cx);
5434 editor.toggle_code_actions(
5435 &ToggleCodeActions {
5436 deployed_from_indicator: Some(row),
5437 },
5438 cx,
5439 );
5440 })),
5441 )
5442 } else {
5443 None
5444 }
5445 }
5446
5447 fn clear_tasks(&mut self) {
5448 self.tasks.clear()
5449 }
5450
5451 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5452 if self.tasks.insert(key, value).is_some() {
5453 // This case should hopefully be rare, but just in case...
5454 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5455 }
5456 }
5457
5458 fn render_run_indicator(
5459 &self,
5460 _style: &EditorStyle,
5461 is_active: bool,
5462 row: DisplayRow,
5463 cx: &mut ViewContext<Self>,
5464 ) -> IconButton {
5465 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5466 .shape(ui::IconButtonShape::Square)
5467 .icon_size(IconSize::XSmall)
5468 .icon_color(Color::Muted)
5469 .selected(is_active)
5470 .on_click(cx.listener(move |editor, _e, cx| {
5471 editor.focus(cx);
5472 editor.toggle_code_actions(
5473 &ToggleCodeActions {
5474 deployed_from_indicator: Some(row),
5475 },
5476 cx,
5477 );
5478 }))
5479 }
5480
5481 pub fn context_menu_visible(&self) -> bool {
5482 self.context_menu
5483 .read()
5484 .as_ref()
5485 .map_or(false, |menu| menu.visible())
5486 }
5487
5488 fn render_context_menu(
5489 &self,
5490 cursor_position: DisplayPoint,
5491 style: &EditorStyle,
5492 max_height: Pixels,
5493 cx: &mut ViewContext<Editor>,
5494 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5495 self.context_menu.read().as_ref().map(|menu| {
5496 menu.render(
5497 cursor_position,
5498 style,
5499 max_height,
5500 self.workspace.as_ref().map(|(w, _)| w.clone()),
5501 cx,
5502 )
5503 })
5504 }
5505
5506 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5507 cx.notify();
5508 self.completion_tasks.clear();
5509 let context_menu = self.context_menu.write().take();
5510 if context_menu.is_some() {
5511 self.update_visible_inline_completion(cx);
5512 }
5513 context_menu
5514 }
5515
5516 pub fn insert_snippet(
5517 &mut self,
5518 insertion_ranges: &[Range<usize>],
5519 snippet: Snippet,
5520 cx: &mut ViewContext<Self>,
5521 ) -> Result<()> {
5522 struct Tabstop<T> {
5523 is_end_tabstop: bool,
5524 ranges: Vec<Range<T>>,
5525 }
5526
5527 let tabstops = self.buffer.update(cx, |buffer, cx| {
5528 let snippet_text: Arc<str> = snippet.text.clone().into();
5529 buffer.edit(
5530 insertion_ranges
5531 .iter()
5532 .cloned()
5533 .map(|range| (range, snippet_text.clone())),
5534 Some(AutoindentMode::EachLine),
5535 cx,
5536 );
5537
5538 let snapshot = &*buffer.read(cx);
5539 let snippet = &snippet;
5540 snippet
5541 .tabstops
5542 .iter()
5543 .map(|tabstop| {
5544 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5545 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5546 });
5547 let mut tabstop_ranges = tabstop
5548 .iter()
5549 .flat_map(|tabstop_range| {
5550 let mut delta = 0_isize;
5551 insertion_ranges.iter().map(move |insertion_range| {
5552 let insertion_start = insertion_range.start as isize + delta;
5553 delta +=
5554 snippet.text.len() as isize - insertion_range.len() as isize;
5555
5556 let start = ((insertion_start + tabstop_range.start) as usize)
5557 .min(snapshot.len());
5558 let end = ((insertion_start + tabstop_range.end) as usize)
5559 .min(snapshot.len());
5560 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5561 })
5562 })
5563 .collect::<Vec<_>>();
5564 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5565
5566 Tabstop {
5567 is_end_tabstop,
5568 ranges: tabstop_ranges,
5569 }
5570 })
5571 .collect::<Vec<_>>()
5572 });
5573 if let Some(tabstop) = tabstops.first() {
5574 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5575 s.select_ranges(tabstop.ranges.iter().cloned());
5576 });
5577
5578 // If we're already at the last tabstop and it's at the end of the snippet,
5579 // we're done, we don't need to keep the state around.
5580 if !tabstop.is_end_tabstop {
5581 let ranges = tabstops
5582 .into_iter()
5583 .map(|tabstop| tabstop.ranges)
5584 .collect::<Vec<_>>();
5585 self.snippet_stack.push(SnippetState {
5586 active_index: 0,
5587 ranges,
5588 });
5589 }
5590
5591 // Check whether the just-entered snippet ends with an auto-closable bracket.
5592 if self.autoclose_regions.is_empty() {
5593 let snapshot = self.buffer.read(cx).snapshot(cx);
5594 for selection in &mut self.selections.all::<Point>(cx) {
5595 let selection_head = selection.head();
5596 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5597 continue;
5598 };
5599
5600 let mut bracket_pair = None;
5601 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5602 let prev_chars = snapshot
5603 .reversed_chars_at(selection_head)
5604 .collect::<String>();
5605 for (pair, enabled) in scope.brackets() {
5606 if enabled
5607 && pair.close
5608 && prev_chars.starts_with(pair.start.as_str())
5609 && next_chars.starts_with(pair.end.as_str())
5610 {
5611 bracket_pair = Some(pair.clone());
5612 break;
5613 }
5614 }
5615 if let Some(pair) = bracket_pair {
5616 let start = snapshot.anchor_after(selection_head);
5617 let end = snapshot.anchor_after(selection_head);
5618 self.autoclose_regions.push(AutocloseRegion {
5619 selection_id: selection.id,
5620 range: start..end,
5621 pair,
5622 });
5623 }
5624 }
5625 }
5626 }
5627 Ok(())
5628 }
5629
5630 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5631 self.move_to_snippet_tabstop(Bias::Right, cx)
5632 }
5633
5634 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5635 self.move_to_snippet_tabstop(Bias::Left, cx)
5636 }
5637
5638 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5639 if let Some(mut snippet) = self.snippet_stack.pop() {
5640 match bias {
5641 Bias::Left => {
5642 if snippet.active_index > 0 {
5643 snippet.active_index -= 1;
5644 } else {
5645 self.snippet_stack.push(snippet);
5646 return false;
5647 }
5648 }
5649 Bias::Right => {
5650 if snippet.active_index + 1 < snippet.ranges.len() {
5651 snippet.active_index += 1;
5652 } else {
5653 self.snippet_stack.push(snippet);
5654 return false;
5655 }
5656 }
5657 }
5658 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5659 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5660 s.select_anchor_ranges(current_ranges.iter().cloned())
5661 });
5662 // If snippet state is not at the last tabstop, push it back on the stack
5663 if snippet.active_index + 1 < snippet.ranges.len() {
5664 self.snippet_stack.push(snippet);
5665 }
5666 return true;
5667 }
5668 }
5669
5670 false
5671 }
5672
5673 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5674 self.transact(cx, |this, cx| {
5675 this.select_all(&SelectAll, cx);
5676 this.insert("", cx);
5677 });
5678 }
5679
5680 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5681 self.transact(cx, |this, cx| {
5682 this.select_autoclose_pair(cx);
5683 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5684 if !this.linked_edit_ranges.is_empty() {
5685 let selections = this.selections.all::<MultiBufferPoint>(cx);
5686 let snapshot = this.buffer.read(cx).snapshot(cx);
5687
5688 for selection in selections.iter() {
5689 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5690 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5691 if selection_start.buffer_id != selection_end.buffer_id {
5692 continue;
5693 }
5694 if let Some(ranges) =
5695 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5696 {
5697 for (buffer, entries) in ranges {
5698 linked_ranges.entry(buffer).or_default().extend(entries);
5699 }
5700 }
5701 }
5702 }
5703
5704 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5705 if !this.selections.line_mode {
5706 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5707 for selection in &mut selections {
5708 if selection.is_empty() {
5709 let old_head = selection.head();
5710 let mut new_head =
5711 movement::left(&display_map, old_head.to_display_point(&display_map))
5712 .to_point(&display_map);
5713 if let Some((buffer, line_buffer_range)) = display_map
5714 .buffer_snapshot
5715 .buffer_line_for_row(MultiBufferRow(old_head.row))
5716 {
5717 let indent_size =
5718 buffer.indent_size_for_line(line_buffer_range.start.row);
5719 let indent_len = match indent_size.kind {
5720 IndentKind::Space => {
5721 buffer.settings_at(line_buffer_range.start, cx).tab_size
5722 }
5723 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5724 };
5725 if old_head.column <= indent_size.len && old_head.column > 0 {
5726 let indent_len = indent_len.get();
5727 new_head = cmp::min(
5728 new_head,
5729 MultiBufferPoint::new(
5730 old_head.row,
5731 ((old_head.column - 1) / indent_len) * indent_len,
5732 ),
5733 );
5734 }
5735 }
5736
5737 selection.set_head(new_head, SelectionGoal::None);
5738 }
5739 }
5740 }
5741
5742 this.signature_help_state.set_backspace_pressed(true);
5743 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5744 this.insert("", cx);
5745 let empty_str: Arc<str> = Arc::from("");
5746 for (buffer, edits) in linked_ranges {
5747 let snapshot = buffer.read(cx).snapshot();
5748 use text::ToPoint as TP;
5749
5750 let edits = edits
5751 .into_iter()
5752 .map(|range| {
5753 let end_point = TP::to_point(&range.end, &snapshot);
5754 let mut start_point = TP::to_point(&range.start, &snapshot);
5755
5756 if end_point == start_point {
5757 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5758 .saturating_sub(1);
5759 start_point = TP::to_point(&offset, &snapshot);
5760 };
5761
5762 (start_point..end_point, empty_str.clone())
5763 })
5764 .sorted_by_key(|(range, _)| range.start)
5765 .collect::<Vec<_>>();
5766 buffer.update(cx, |this, cx| {
5767 this.edit(edits, None, cx);
5768 })
5769 }
5770 this.refresh_inline_completion(true, false, cx);
5771 linked_editing_ranges::refresh_linked_ranges(this, cx);
5772 });
5773 }
5774
5775 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5776 self.transact(cx, |this, cx| {
5777 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5778 let line_mode = s.line_mode;
5779 s.move_with(|map, selection| {
5780 if selection.is_empty() && !line_mode {
5781 let cursor = movement::right(map, selection.head());
5782 selection.end = cursor;
5783 selection.reversed = true;
5784 selection.goal = SelectionGoal::None;
5785 }
5786 })
5787 });
5788 this.insert("", cx);
5789 this.refresh_inline_completion(true, false, cx);
5790 });
5791 }
5792
5793 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5794 if self.move_to_prev_snippet_tabstop(cx) {
5795 return;
5796 }
5797
5798 self.outdent(&Outdent, cx);
5799 }
5800
5801 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5802 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5803 return;
5804 }
5805
5806 let mut selections = self.selections.all_adjusted(cx);
5807 let buffer = self.buffer.read(cx);
5808 let snapshot = buffer.snapshot(cx);
5809 let rows_iter = selections.iter().map(|s| s.head().row);
5810 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5811
5812 let mut edits = Vec::new();
5813 let mut prev_edited_row = 0;
5814 let mut row_delta = 0;
5815 for selection in &mut selections {
5816 if selection.start.row != prev_edited_row {
5817 row_delta = 0;
5818 }
5819 prev_edited_row = selection.end.row;
5820
5821 // If the selection is non-empty, then increase the indentation of the selected lines.
5822 if !selection.is_empty() {
5823 row_delta =
5824 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5825 continue;
5826 }
5827
5828 // If the selection is empty and the cursor is in the leading whitespace before the
5829 // suggested indentation, then auto-indent the line.
5830 let cursor = selection.head();
5831 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5832 if let Some(suggested_indent) =
5833 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5834 {
5835 if cursor.column < suggested_indent.len
5836 && cursor.column <= current_indent.len
5837 && current_indent.len <= suggested_indent.len
5838 {
5839 selection.start = Point::new(cursor.row, suggested_indent.len);
5840 selection.end = selection.start;
5841 if row_delta == 0 {
5842 edits.extend(Buffer::edit_for_indent_size_adjustment(
5843 cursor.row,
5844 current_indent,
5845 suggested_indent,
5846 ));
5847 row_delta = suggested_indent.len - current_indent.len;
5848 }
5849 continue;
5850 }
5851 }
5852
5853 // Otherwise, insert a hard or soft tab.
5854 let settings = buffer.settings_at(cursor, cx);
5855 let tab_size = if settings.hard_tabs {
5856 IndentSize::tab()
5857 } else {
5858 let tab_size = settings.tab_size.get();
5859 let char_column = snapshot
5860 .text_for_range(Point::new(cursor.row, 0)..cursor)
5861 .flat_map(str::chars)
5862 .count()
5863 + row_delta as usize;
5864 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5865 IndentSize::spaces(chars_to_next_tab_stop)
5866 };
5867 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5868 selection.end = selection.start;
5869 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5870 row_delta += tab_size.len;
5871 }
5872
5873 self.transact(cx, |this, cx| {
5874 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5875 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5876 this.refresh_inline_completion(true, false, cx);
5877 });
5878 }
5879
5880 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5881 if self.read_only(cx) {
5882 return;
5883 }
5884 let mut selections = self.selections.all::<Point>(cx);
5885 let mut prev_edited_row = 0;
5886 let mut row_delta = 0;
5887 let mut edits = Vec::new();
5888 let buffer = self.buffer.read(cx);
5889 let snapshot = buffer.snapshot(cx);
5890 for selection in &mut selections {
5891 if selection.start.row != prev_edited_row {
5892 row_delta = 0;
5893 }
5894 prev_edited_row = selection.end.row;
5895
5896 row_delta =
5897 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5898 }
5899
5900 self.transact(cx, |this, cx| {
5901 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5902 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5903 });
5904 }
5905
5906 fn indent_selection(
5907 buffer: &MultiBuffer,
5908 snapshot: &MultiBufferSnapshot,
5909 selection: &mut Selection<Point>,
5910 edits: &mut Vec<(Range<Point>, String)>,
5911 delta_for_start_row: u32,
5912 cx: &AppContext,
5913 ) -> u32 {
5914 let settings = buffer.settings_at(selection.start, cx);
5915 let tab_size = settings.tab_size.get();
5916 let indent_kind = if settings.hard_tabs {
5917 IndentKind::Tab
5918 } else {
5919 IndentKind::Space
5920 };
5921 let mut start_row = selection.start.row;
5922 let mut end_row = selection.end.row + 1;
5923
5924 // If a selection ends at the beginning of a line, don't indent
5925 // that last line.
5926 if selection.end.column == 0 && selection.end.row > selection.start.row {
5927 end_row -= 1;
5928 }
5929
5930 // Avoid re-indenting a row that has already been indented by a
5931 // previous selection, but still update this selection's column
5932 // to reflect that indentation.
5933 if delta_for_start_row > 0 {
5934 start_row += 1;
5935 selection.start.column += delta_for_start_row;
5936 if selection.end.row == selection.start.row {
5937 selection.end.column += delta_for_start_row;
5938 }
5939 }
5940
5941 let mut delta_for_end_row = 0;
5942 let has_multiple_rows = start_row + 1 != end_row;
5943 for row in start_row..end_row {
5944 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5945 let indent_delta = match (current_indent.kind, indent_kind) {
5946 (IndentKind::Space, IndentKind::Space) => {
5947 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5948 IndentSize::spaces(columns_to_next_tab_stop)
5949 }
5950 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5951 (_, IndentKind::Tab) => IndentSize::tab(),
5952 };
5953
5954 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5955 0
5956 } else {
5957 selection.start.column
5958 };
5959 let row_start = Point::new(row, start);
5960 edits.push((
5961 row_start..row_start,
5962 indent_delta.chars().collect::<String>(),
5963 ));
5964
5965 // Update this selection's endpoints to reflect the indentation.
5966 if row == selection.start.row {
5967 selection.start.column += indent_delta.len;
5968 }
5969 if row == selection.end.row {
5970 selection.end.column += indent_delta.len;
5971 delta_for_end_row = indent_delta.len;
5972 }
5973 }
5974
5975 if selection.start.row == selection.end.row {
5976 delta_for_start_row + delta_for_end_row
5977 } else {
5978 delta_for_end_row
5979 }
5980 }
5981
5982 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5983 if self.read_only(cx) {
5984 return;
5985 }
5986 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5987 let selections = self.selections.all::<Point>(cx);
5988 let mut deletion_ranges = Vec::new();
5989 let mut last_outdent = None;
5990 {
5991 let buffer = self.buffer.read(cx);
5992 let snapshot = buffer.snapshot(cx);
5993 for selection in &selections {
5994 let settings = buffer.settings_at(selection.start, cx);
5995 let tab_size = settings.tab_size.get();
5996 let mut rows = selection.spanned_rows(false, &display_map);
5997
5998 // Avoid re-outdenting a row that has already been outdented by a
5999 // previous selection.
6000 if let Some(last_row) = last_outdent {
6001 if last_row == rows.start {
6002 rows.start = rows.start.next_row();
6003 }
6004 }
6005 let has_multiple_rows = rows.len() > 1;
6006 for row in rows.iter_rows() {
6007 let indent_size = snapshot.indent_size_for_line(row);
6008 if indent_size.len > 0 {
6009 let deletion_len = match indent_size.kind {
6010 IndentKind::Space => {
6011 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6012 if columns_to_prev_tab_stop == 0 {
6013 tab_size
6014 } else {
6015 columns_to_prev_tab_stop
6016 }
6017 }
6018 IndentKind::Tab => 1,
6019 };
6020 let start = if has_multiple_rows
6021 || deletion_len > selection.start.column
6022 || indent_size.len < selection.start.column
6023 {
6024 0
6025 } else {
6026 selection.start.column - deletion_len
6027 };
6028 deletion_ranges.push(
6029 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6030 );
6031 last_outdent = Some(row);
6032 }
6033 }
6034 }
6035 }
6036
6037 self.transact(cx, |this, cx| {
6038 this.buffer.update(cx, |buffer, cx| {
6039 let empty_str: Arc<str> = Arc::default();
6040 buffer.edit(
6041 deletion_ranges
6042 .into_iter()
6043 .map(|range| (range, empty_str.clone())),
6044 None,
6045 cx,
6046 );
6047 });
6048 let selections = this.selections.all::<usize>(cx);
6049 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6050 });
6051 }
6052
6053 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6054 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6055 let selections = self.selections.all::<Point>(cx);
6056
6057 let mut new_cursors = Vec::new();
6058 let mut edit_ranges = Vec::new();
6059 let mut selections = selections.iter().peekable();
6060 while let Some(selection) = selections.next() {
6061 let mut rows = selection.spanned_rows(false, &display_map);
6062 let goal_display_column = selection.head().to_display_point(&display_map).column();
6063
6064 // Accumulate contiguous regions of rows that we want to delete.
6065 while let Some(next_selection) = selections.peek() {
6066 let next_rows = next_selection.spanned_rows(false, &display_map);
6067 if next_rows.start <= rows.end {
6068 rows.end = next_rows.end;
6069 selections.next().unwrap();
6070 } else {
6071 break;
6072 }
6073 }
6074
6075 let buffer = &display_map.buffer_snapshot;
6076 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6077 let edit_end;
6078 let cursor_buffer_row;
6079 if buffer.max_point().row >= rows.end.0 {
6080 // If there's a line after the range, delete the \n from the end of the row range
6081 // and position the cursor on the next line.
6082 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6083 cursor_buffer_row = rows.end;
6084 } else {
6085 // If there isn't a line after the range, delete the \n from the line before the
6086 // start of the row range and position the cursor there.
6087 edit_start = edit_start.saturating_sub(1);
6088 edit_end = buffer.len();
6089 cursor_buffer_row = rows.start.previous_row();
6090 }
6091
6092 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6093 *cursor.column_mut() =
6094 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6095
6096 new_cursors.push((
6097 selection.id,
6098 buffer.anchor_after(cursor.to_point(&display_map)),
6099 ));
6100 edit_ranges.push(edit_start..edit_end);
6101 }
6102
6103 self.transact(cx, |this, cx| {
6104 let buffer = this.buffer.update(cx, |buffer, cx| {
6105 let empty_str: Arc<str> = Arc::default();
6106 buffer.edit(
6107 edit_ranges
6108 .into_iter()
6109 .map(|range| (range, empty_str.clone())),
6110 None,
6111 cx,
6112 );
6113 buffer.snapshot(cx)
6114 });
6115 let new_selections = new_cursors
6116 .into_iter()
6117 .map(|(id, cursor)| {
6118 let cursor = cursor.to_point(&buffer);
6119 Selection {
6120 id,
6121 start: cursor,
6122 end: cursor,
6123 reversed: false,
6124 goal: SelectionGoal::None,
6125 }
6126 })
6127 .collect();
6128
6129 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6130 s.select(new_selections);
6131 });
6132 });
6133 }
6134
6135 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6136 if self.read_only(cx) {
6137 return;
6138 }
6139 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6140 for selection in self.selections.all::<Point>(cx) {
6141 let start = MultiBufferRow(selection.start.row);
6142 let end = if selection.start.row == selection.end.row {
6143 MultiBufferRow(selection.start.row + 1)
6144 } else {
6145 MultiBufferRow(selection.end.row)
6146 };
6147
6148 if let Some(last_row_range) = row_ranges.last_mut() {
6149 if start <= last_row_range.end {
6150 last_row_range.end = end;
6151 continue;
6152 }
6153 }
6154 row_ranges.push(start..end);
6155 }
6156
6157 let snapshot = self.buffer.read(cx).snapshot(cx);
6158 let mut cursor_positions = Vec::new();
6159 for row_range in &row_ranges {
6160 let anchor = snapshot.anchor_before(Point::new(
6161 row_range.end.previous_row().0,
6162 snapshot.line_len(row_range.end.previous_row()),
6163 ));
6164 cursor_positions.push(anchor..anchor);
6165 }
6166
6167 self.transact(cx, |this, cx| {
6168 for row_range in row_ranges.into_iter().rev() {
6169 for row in row_range.iter_rows().rev() {
6170 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6171 let next_line_row = row.next_row();
6172 let indent = snapshot.indent_size_for_line(next_line_row);
6173 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6174
6175 let replace = if snapshot.line_len(next_line_row) > indent.len {
6176 " "
6177 } else {
6178 ""
6179 };
6180
6181 this.buffer.update(cx, |buffer, cx| {
6182 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6183 });
6184 }
6185 }
6186
6187 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6188 s.select_anchor_ranges(cursor_positions)
6189 });
6190 });
6191 }
6192
6193 pub fn sort_lines_case_sensitive(
6194 &mut self,
6195 _: &SortLinesCaseSensitive,
6196 cx: &mut ViewContext<Self>,
6197 ) {
6198 self.manipulate_lines(cx, |lines| lines.sort())
6199 }
6200
6201 pub fn sort_lines_case_insensitive(
6202 &mut self,
6203 _: &SortLinesCaseInsensitive,
6204 cx: &mut ViewContext<Self>,
6205 ) {
6206 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6207 }
6208
6209 pub fn unique_lines_case_insensitive(
6210 &mut self,
6211 _: &UniqueLinesCaseInsensitive,
6212 cx: &mut ViewContext<Self>,
6213 ) {
6214 self.manipulate_lines(cx, |lines| {
6215 let mut seen = HashSet::default();
6216 lines.retain(|line| seen.insert(line.to_lowercase()));
6217 })
6218 }
6219
6220 pub fn unique_lines_case_sensitive(
6221 &mut self,
6222 _: &UniqueLinesCaseSensitive,
6223 cx: &mut ViewContext<Self>,
6224 ) {
6225 self.manipulate_lines(cx, |lines| {
6226 let mut seen = HashSet::default();
6227 lines.retain(|line| seen.insert(*line));
6228 })
6229 }
6230
6231 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6232 let mut revert_changes = HashMap::default();
6233 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6234 for hunk in hunks_for_rows(
6235 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6236 &multi_buffer_snapshot,
6237 ) {
6238 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6239 }
6240 if !revert_changes.is_empty() {
6241 self.transact(cx, |editor, cx| {
6242 editor.revert(revert_changes, cx);
6243 });
6244 }
6245 }
6246
6247 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6248 let Some(project) = self.project.clone() else {
6249 return;
6250 };
6251 self.reload(project, cx).detach_and_notify_err(cx);
6252 }
6253
6254 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6255 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6256 if !revert_changes.is_empty() {
6257 self.transact(cx, |editor, cx| {
6258 editor.revert(revert_changes, cx);
6259 });
6260 }
6261 }
6262
6263 fn apply_selected_diff_hunks(&mut self, _: &ApplyDiffHunk, cx: &mut ViewContext<Self>) {
6264 let snapshot = self.buffer.read(cx).snapshot(cx);
6265 let hunks = hunks_for_selections(&snapshot, &self.selections.disjoint_anchors());
6266 let mut ranges_by_buffer = HashMap::default();
6267 self.transact(cx, |editor, cx| {
6268 for hunk in hunks {
6269 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
6270 ranges_by_buffer
6271 .entry(buffer.clone())
6272 .or_insert_with(Vec::new)
6273 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
6274 }
6275 }
6276
6277 for (buffer, ranges) in ranges_by_buffer {
6278 buffer.update(cx, |buffer, cx| {
6279 buffer.merge_into_base(ranges, cx);
6280 });
6281 }
6282 });
6283 }
6284
6285 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6286 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6287 let project_path = buffer.read(cx).project_path(cx)?;
6288 let project = self.project.as_ref()?.read(cx);
6289 let entry = project.entry_for_path(&project_path, cx)?;
6290 let parent = match &entry.canonical_path {
6291 Some(canonical_path) => canonical_path.to_path_buf(),
6292 None => project.absolute_path(&project_path, cx)?,
6293 }
6294 .parent()?
6295 .to_path_buf();
6296 Some(parent)
6297 }) {
6298 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6299 }
6300 }
6301
6302 fn gather_revert_changes(
6303 &mut self,
6304 selections: &[Selection<Anchor>],
6305 cx: &mut ViewContext<'_, Editor>,
6306 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6307 let mut revert_changes = HashMap::default();
6308 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6309 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6310 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6311 }
6312 revert_changes
6313 }
6314
6315 pub fn prepare_revert_change(
6316 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6317 multi_buffer: &Model<MultiBuffer>,
6318 hunk: &MultiBufferDiffHunk,
6319 cx: &AppContext,
6320 ) -> Option<()> {
6321 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6322 let buffer = buffer.read(cx);
6323 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6324 let buffer_snapshot = buffer.snapshot();
6325 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6326 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6327 probe
6328 .0
6329 .start
6330 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6331 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6332 }) {
6333 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6334 Some(())
6335 } else {
6336 None
6337 }
6338 }
6339
6340 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6341 self.manipulate_lines(cx, |lines| lines.reverse())
6342 }
6343
6344 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6345 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6346 }
6347
6348 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6349 where
6350 Fn: FnMut(&mut Vec<&str>),
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 edits = Vec::new();
6356
6357 let selections = self.selections.all::<Point>(cx);
6358 let mut selections = selections.iter().peekable();
6359 let mut contiguous_row_selections = Vec::new();
6360 let mut new_selections = Vec::new();
6361 let mut added_lines = 0;
6362 let mut removed_lines = 0;
6363
6364 while let Some(selection) = selections.next() {
6365 let (start_row, end_row) = consume_contiguous_rows(
6366 &mut contiguous_row_selections,
6367 selection,
6368 &display_map,
6369 &mut selections,
6370 );
6371
6372 let start_point = Point::new(start_row.0, 0);
6373 let end_point = Point::new(
6374 end_row.previous_row().0,
6375 buffer.line_len(end_row.previous_row()),
6376 );
6377 let text = buffer
6378 .text_for_range(start_point..end_point)
6379 .collect::<String>();
6380
6381 let mut lines = text.split('\n').collect_vec();
6382
6383 let lines_before = lines.len();
6384 callback(&mut lines);
6385 let lines_after = lines.len();
6386
6387 edits.push((start_point..end_point, lines.join("\n")));
6388
6389 // Selections must change based on added and removed line count
6390 let start_row =
6391 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6392 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6393 new_selections.push(Selection {
6394 id: selection.id,
6395 start: start_row,
6396 end: end_row,
6397 goal: SelectionGoal::None,
6398 reversed: selection.reversed,
6399 });
6400
6401 if lines_after > lines_before {
6402 added_lines += lines_after - lines_before;
6403 } else if lines_before > lines_after {
6404 removed_lines += lines_before - lines_after;
6405 }
6406 }
6407
6408 self.transact(cx, |this, cx| {
6409 let buffer = this.buffer.update(cx, |buffer, cx| {
6410 buffer.edit(edits, None, cx);
6411 buffer.snapshot(cx)
6412 });
6413
6414 // Recalculate offsets on newly edited buffer
6415 let new_selections = new_selections
6416 .iter()
6417 .map(|s| {
6418 let start_point = Point::new(s.start.0, 0);
6419 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6420 Selection {
6421 id: s.id,
6422 start: buffer.point_to_offset(start_point),
6423 end: buffer.point_to_offset(end_point),
6424 goal: s.goal,
6425 reversed: s.reversed,
6426 }
6427 })
6428 .collect();
6429
6430 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6431 s.select(new_selections);
6432 });
6433
6434 this.request_autoscroll(Autoscroll::fit(), cx);
6435 });
6436 }
6437
6438 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6439 self.manipulate_text(cx, |text| text.to_uppercase())
6440 }
6441
6442 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6443 self.manipulate_text(cx, |text| text.to_lowercase())
6444 }
6445
6446 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6447 self.manipulate_text(cx, |text| {
6448 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6449 // https://github.com/rutrum/convert-case/issues/16
6450 text.split('\n')
6451 .map(|line| line.to_case(Case::Title))
6452 .join("\n")
6453 })
6454 }
6455
6456 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6457 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6458 }
6459
6460 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6461 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6462 }
6463
6464 pub fn convert_to_upper_camel_case(
6465 &mut self,
6466 _: &ConvertToUpperCamelCase,
6467 cx: &mut ViewContext<Self>,
6468 ) {
6469 self.manipulate_text(cx, |text| {
6470 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6471 // https://github.com/rutrum/convert-case/issues/16
6472 text.split('\n')
6473 .map(|line| line.to_case(Case::UpperCamel))
6474 .join("\n")
6475 })
6476 }
6477
6478 pub fn convert_to_lower_camel_case(
6479 &mut self,
6480 _: &ConvertToLowerCamelCase,
6481 cx: &mut ViewContext<Self>,
6482 ) {
6483 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6484 }
6485
6486 pub fn convert_to_opposite_case(
6487 &mut self,
6488 _: &ConvertToOppositeCase,
6489 cx: &mut ViewContext<Self>,
6490 ) {
6491 self.manipulate_text(cx, |text| {
6492 text.chars()
6493 .fold(String::with_capacity(text.len()), |mut t, c| {
6494 if c.is_uppercase() {
6495 t.extend(c.to_lowercase());
6496 } else {
6497 t.extend(c.to_uppercase());
6498 }
6499 t
6500 })
6501 })
6502 }
6503
6504 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6505 where
6506 Fn: FnMut(&str) -> String,
6507 {
6508 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6509 let buffer = self.buffer.read(cx).snapshot(cx);
6510
6511 let mut new_selections = Vec::new();
6512 let mut edits = Vec::new();
6513 let mut selection_adjustment = 0i32;
6514
6515 for selection in self.selections.all::<usize>(cx) {
6516 let selection_is_empty = selection.is_empty();
6517
6518 let (start, end) = if selection_is_empty {
6519 let word_range = movement::surrounding_word(
6520 &display_map,
6521 selection.start.to_display_point(&display_map),
6522 );
6523 let start = word_range.start.to_offset(&display_map, Bias::Left);
6524 let end = word_range.end.to_offset(&display_map, Bias::Left);
6525 (start, end)
6526 } else {
6527 (selection.start, selection.end)
6528 };
6529
6530 let text = buffer.text_for_range(start..end).collect::<String>();
6531 let old_length = text.len() as i32;
6532 let text = callback(&text);
6533
6534 new_selections.push(Selection {
6535 start: (start as i32 - selection_adjustment) as usize,
6536 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6537 goal: SelectionGoal::None,
6538 ..selection
6539 });
6540
6541 selection_adjustment += old_length - text.len() as i32;
6542
6543 edits.push((start..end, text));
6544 }
6545
6546 self.transact(cx, |this, cx| {
6547 this.buffer.update(cx, |buffer, cx| {
6548 buffer.edit(edits, None, cx);
6549 });
6550
6551 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6552 s.select(new_selections);
6553 });
6554
6555 this.request_autoscroll(Autoscroll::fit(), cx);
6556 });
6557 }
6558
6559 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6560 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6561 let buffer = &display_map.buffer_snapshot;
6562 let selections = self.selections.all::<Point>(cx);
6563
6564 let mut edits = Vec::new();
6565 let mut selections_iter = selections.iter().peekable();
6566 while let Some(selection) = selections_iter.next() {
6567 // Avoid duplicating the same lines twice.
6568 let mut rows = selection.spanned_rows(false, &display_map);
6569
6570 while let Some(next_selection) = selections_iter.peek() {
6571 let next_rows = next_selection.spanned_rows(false, &display_map);
6572 if next_rows.start < rows.end {
6573 rows.end = next_rows.end;
6574 selections_iter.next().unwrap();
6575 } else {
6576 break;
6577 }
6578 }
6579
6580 // Copy the text from the selected row region and splice it either at the start
6581 // or end of the region.
6582 let start = Point::new(rows.start.0, 0);
6583 let end = Point::new(
6584 rows.end.previous_row().0,
6585 buffer.line_len(rows.end.previous_row()),
6586 );
6587 let text = buffer
6588 .text_for_range(start..end)
6589 .chain(Some("\n"))
6590 .collect::<String>();
6591 let insert_location = if upwards {
6592 Point::new(rows.end.0, 0)
6593 } else {
6594 start
6595 };
6596 edits.push((insert_location..insert_location, text));
6597 }
6598
6599 self.transact(cx, |this, cx| {
6600 this.buffer.update(cx, |buffer, cx| {
6601 buffer.edit(edits, None, cx);
6602 });
6603
6604 this.request_autoscroll(Autoscroll::fit(), cx);
6605 });
6606 }
6607
6608 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6609 self.duplicate_line(true, cx);
6610 }
6611
6612 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6613 self.duplicate_line(false, cx);
6614 }
6615
6616 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6617 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6618 let buffer = self.buffer.read(cx).snapshot(cx);
6619
6620 let mut edits = Vec::new();
6621 let mut unfold_ranges = Vec::new();
6622 let mut refold_ranges = Vec::new();
6623
6624 let selections = self.selections.all::<Point>(cx);
6625 let mut selections = selections.iter().peekable();
6626 let mut contiguous_row_selections = Vec::new();
6627 let mut new_selections = Vec::new();
6628
6629 while let Some(selection) = selections.next() {
6630 // Find all the selections that span a contiguous row range
6631 let (start_row, end_row) = consume_contiguous_rows(
6632 &mut contiguous_row_selections,
6633 selection,
6634 &display_map,
6635 &mut selections,
6636 );
6637
6638 // Move the text spanned by the row range to be before the line preceding the row range
6639 if start_row.0 > 0 {
6640 let range_to_move = Point::new(
6641 start_row.previous_row().0,
6642 buffer.line_len(start_row.previous_row()),
6643 )
6644 ..Point::new(
6645 end_row.previous_row().0,
6646 buffer.line_len(end_row.previous_row()),
6647 );
6648 let insertion_point = display_map
6649 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6650 .0;
6651
6652 // Don't move lines across excerpts
6653 if buffer
6654 .excerpt_boundaries_in_range((
6655 Bound::Excluded(insertion_point),
6656 Bound::Included(range_to_move.end),
6657 ))
6658 .next()
6659 .is_none()
6660 {
6661 let text = buffer
6662 .text_for_range(range_to_move.clone())
6663 .flat_map(|s| s.chars())
6664 .skip(1)
6665 .chain(['\n'])
6666 .collect::<String>();
6667
6668 edits.push((
6669 buffer.anchor_after(range_to_move.start)
6670 ..buffer.anchor_before(range_to_move.end),
6671 String::new(),
6672 ));
6673 let insertion_anchor = buffer.anchor_after(insertion_point);
6674 edits.push((insertion_anchor..insertion_anchor, text));
6675
6676 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6677
6678 // Move selections up
6679 new_selections.extend(contiguous_row_selections.drain(..).map(
6680 |mut selection| {
6681 selection.start.row -= row_delta;
6682 selection.end.row -= row_delta;
6683 selection
6684 },
6685 ));
6686
6687 // Move folds up
6688 unfold_ranges.push(range_to_move.clone());
6689 for fold in display_map.folds_in_range(
6690 buffer.anchor_before(range_to_move.start)
6691 ..buffer.anchor_after(range_to_move.end),
6692 ) {
6693 let mut start = fold.range.start.to_point(&buffer);
6694 let mut end = fold.range.end.to_point(&buffer);
6695 start.row -= row_delta;
6696 end.row -= row_delta;
6697 refold_ranges.push((start..end, fold.placeholder.clone()));
6698 }
6699 }
6700 }
6701
6702 // If we didn't move line(s), preserve the existing selections
6703 new_selections.append(&mut contiguous_row_selections);
6704 }
6705
6706 self.transact(cx, |this, cx| {
6707 this.unfold_ranges(unfold_ranges, true, true, cx);
6708 this.buffer.update(cx, |buffer, cx| {
6709 for (range, text) in edits {
6710 buffer.edit([(range, text)], None, cx);
6711 }
6712 });
6713 this.fold_ranges(refold_ranges, true, cx);
6714 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6715 s.select(new_selections);
6716 })
6717 });
6718 }
6719
6720 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6721 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6722 let buffer = self.buffer.read(cx).snapshot(cx);
6723
6724 let mut edits = Vec::new();
6725 let mut unfold_ranges = Vec::new();
6726 let mut refold_ranges = Vec::new();
6727
6728 let selections = self.selections.all::<Point>(cx);
6729 let mut selections = selections.iter().peekable();
6730 let mut contiguous_row_selections = Vec::new();
6731 let mut new_selections = Vec::new();
6732
6733 while let Some(selection) = selections.next() {
6734 // Find all the selections that span a contiguous row range
6735 let (start_row, end_row) = consume_contiguous_rows(
6736 &mut contiguous_row_selections,
6737 selection,
6738 &display_map,
6739 &mut selections,
6740 );
6741
6742 // Move the text spanned by the row range to be after the last line of the row range
6743 if end_row.0 <= buffer.max_point().row {
6744 let range_to_move =
6745 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6746 let insertion_point = display_map
6747 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6748 .0;
6749
6750 // Don't move lines across excerpt boundaries
6751 if buffer
6752 .excerpt_boundaries_in_range((
6753 Bound::Excluded(range_to_move.start),
6754 Bound::Included(insertion_point),
6755 ))
6756 .next()
6757 .is_none()
6758 {
6759 let mut text = String::from("\n");
6760 text.extend(buffer.text_for_range(range_to_move.clone()));
6761 text.pop(); // Drop trailing newline
6762 edits.push((
6763 buffer.anchor_after(range_to_move.start)
6764 ..buffer.anchor_before(range_to_move.end),
6765 String::new(),
6766 ));
6767 let insertion_anchor = buffer.anchor_after(insertion_point);
6768 edits.push((insertion_anchor..insertion_anchor, text));
6769
6770 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6771
6772 // Move selections down
6773 new_selections.extend(contiguous_row_selections.drain(..).map(
6774 |mut selection| {
6775 selection.start.row += row_delta;
6776 selection.end.row += row_delta;
6777 selection
6778 },
6779 ));
6780
6781 // Move folds down
6782 unfold_ranges.push(range_to_move.clone());
6783 for fold in display_map.folds_in_range(
6784 buffer.anchor_before(range_to_move.start)
6785 ..buffer.anchor_after(range_to_move.end),
6786 ) {
6787 let mut start = fold.range.start.to_point(&buffer);
6788 let mut end = fold.range.end.to_point(&buffer);
6789 start.row += row_delta;
6790 end.row += row_delta;
6791 refold_ranges.push((start..end, fold.placeholder.clone()));
6792 }
6793 }
6794 }
6795
6796 // If we didn't move line(s), preserve the existing selections
6797 new_selections.append(&mut contiguous_row_selections);
6798 }
6799
6800 self.transact(cx, |this, cx| {
6801 this.unfold_ranges(unfold_ranges, true, true, cx);
6802 this.buffer.update(cx, |buffer, cx| {
6803 for (range, text) in edits {
6804 buffer.edit([(range, text)], None, cx);
6805 }
6806 });
6807 this.fold_ranges(refold_ranges, true, cx);
6808 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6809 });
6810 }
6811
6812 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6813 let text_layout_details = &self.text_layout_details(cx);
6814 self.transact(cx, |this, cx| {
6815 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6816 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6817 let line_mode = s.line_mode;
6818 s.move_with(|display_map, selection| {
6819 if !selection.is_empty() || line_mode {
6820 return;
6821 }
6822
6823 let mut head = selection.head();
6824 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6825 if head.column() == display_map.line_len(head.row()) {
6826 transpose_offset = display_map
6827 .buffer_snapshot
6828 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6829 }
6830
6831 if transpose_offset == 0 {
6832 return;
6833 }
6834
6835 *head.column_mut() += 1;
6836 head = display_map.clip_point(head, Bias::Right);
6837 let goal = SelectionGoal::HorizontalPosition(
6838 display_map
6839 .x_for_display_point(head, text_layout_details)
6840 .into(),
6841 );
6842 selection.collapse_to(head, goal);
6843
6844 let transpose_start = display_map
6845 .buffer_snapshot
6846 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6847 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6848 let transpose_end = display_map
6849 .buffer_snapshot
6850 .clip_offset(transpose_offset + 1, Bias::Right);
6851 if let Some(ch) =
6852 display_map.buffer_snapshot.chars_at(transpose_start).next()
6853 {
6854 edits.push((transpose_start..transpose_offset, String::new()));
6855 edits.push((transpose_end..transpose_end, ch.to_string()));
6856 }
6857 }
6858 });
6859 edits
6860 });
6861 this.buffer
6862 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6863 let selections = this.selections.all::<usize>(cx);
6864 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6865 s.select(selections);
6866 });
6867 });
6868 }
6869
6870 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6871 self.rewrap_impl(true, cx)
6872 }
6873
6874 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6875 let buffer = self.buffer.read(cx).snapshot(cx);
6876 let selections = self.selections.all::<Point>(cx);
6877 let mut selections = selections.iter().peekable();
6878
6879 let mut edits = Vec::new();
6880 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6881
6882 while let Some(selection) = selections.next() {
6883 let mut start_row = selection.start.row;
6884 let mut end_row = selection.end.row;
6885
6886 // Skip selections that overlap with a range that has already been rewrapped.
6887 let selection_range = start_row..end_row;
6888 if rewrapped_row_ranges
6889 .iter()
6890 .any(|range| range.overlaps(&selection_range))
6891 {
6892 continue;
6893 }
6894
6895 let mut should_rewrap = !only_text;
6896
6897 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6898 match language_scope.language_name().0.as_ref() {
6899 "Markdown" | "Plain Text" => {
6900 should_rewrap = true;
6901 }
6902 _ => {}
6903 }
6904 }
6905
6906 // Since not all lines in the selection may be at the same indent
6907 // level, choose the indent size that is the most common between all
6908 // of the lines.
6909 //
6910 // If there is a tie, we use the deepest indent.
6911 let (indent_size, indent_end) = {
6912 let mut indent_size_occurrences = HashMap::default();
6913 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6914
6915 for row in start_row..=end_row {
6916 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6917 rows_by_indent_size.entry(indent).or_default().push(row);
6918 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6919 }
6920
6921 let indent_size = indent_size_occurrences
6922 .into_iter()
6923 .max_by_key(|(indent, count)| (*count, indent.len))
6924 .map(|(indent, _)| indent)
6925 .unwrap_or_default();
6926 let row = rows_by_indent_size[&indent_size][0];
6927 let indent_end = Point::new(row, indent_size.len);
6928
6929 (indent_size, indent_end)
6930 };
6931
6932 let mut line_prefix = indent_size.chars().collect::<String>();
6933
6934 if let Some(comment_prefix) =
6935 buffer
6936 .language_scope_at(selection.head())
6937 .and_then(|language| {
6938 language
6939 .line_comment_prefixes()
6940 .iter()
6941 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6942 .cloned()
6943 })
6944 {
6945 line_prefix.push_str(&comment_prefix);
6946 should_rewrap = true;
6947 }
6948
6949 if selection.is_empty() {
6950 'expand_upwards: while start_row > 0 {
6951 let prev_row = start_row - 1;
6952 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6953 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6954 {
6955 start_row = prev_row;
6956 } else {
6957 break 'expand_upwards;
6958 }
6959 }
6960
6961 'expand_downwards: while end_row < buffer.max_point().row {
6962 let next_row = end_row + 1;
6963 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6964 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6965 {
6966 end_row = next_row;
6967 } else {
6968 break 'expand_downwards;
6969 }
6970 }
6971 }
6972
6973 if !should_rewrap {
6974 continue;
6975 }
6976
6977 let start = Point::new(start_row, 0);
6978 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6979 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6980 let Some(lines_without_prefixes) = selection_text
6981 .lines()
6982 .map(|line| {
6983 line.strip_prefix(&line_prefix)
6984 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6985 .ok_or_else(|| {
6986 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6987 })
6988 })
6989 .collect::<Result<Vec<_>, _>>()
6990 .log_err()
6991 else {
6992 continue;
6993 };
6994
6995 let unwrapped_text = lines_without_prefixes.join(" ");
6996 let wrap_column = buffer
6997 .settings_at(Point::new(start_row, 0), cx)
6998 .preferred_line_length as usize;
6999 let mut wrapped_text = String::new();
7000 let mut current_line = line_prefix.clone();
7001 for word in unwrapped_text.split_whitespace() {
7002 if current_line.len() + word.len() >= wrap_column {
7003 wrapped_text.push_str(¤t_line);
7004 wrapped_text.push('\n');
7005 current_line.truncate(line_prefix.len());
7006 }
7007
7008 if current_line.len() > line_prefix.len() {
7009 current_line.push(' ');
7010 }
7011
7012 current_line.push_str(word);
7013 }
7014
7015 if !current_line.is_empty() {
7016 wrapped_text.push_str(¤t_line);
7017 }
7018
7019 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
7020 let mut offset = start.to_offset(&buffer);
7021 let mut moved_since_edit = true;
7022
7023 for change in diff.iter_all_changes() {
7024 let value = change.value();
7025 match change.tag() {
7026 ChangeTag::Equal => {
7027 offset += value.len();
7028 moved_since_edit = true;
7029 }
7030 ChangeTag::Delete => {
7031 let start = buffer.anchor_after(offset);
7032 let end = buffer.anchor_before(offset + value.len());
7033
7034 if moved_since_edit {
7035 edits.push((start..end, String::new()));
7036 } else {
7037 edits.last_mut().unwrap().0.end = end;
7038 }
7039
7040 offset += value.len();
7041 moved_since_edit = false;
7042 }
7043 ChangeTag::Insert => {
7044 if moved_since_edit {
7045 let anchor = buffer.anchor_after(offset);
7046 edits.push((anchor..anchor, value.to_string()));
7047 } else {
7048 edits.last_mut().unwrap().1.push_str(value);
7049 }
7050
7051 moved_since_edit = false;
7052 }
7053 }
7054 }
7055
7056 rewrapped_row_ranges.push(start_row..=end_row);
7057 }
7058
7059 self.buffer
7060 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7061 }
7062
7063 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7064 let mut text = String::new();
7065 let buffer = self.buffer.read(cx).snapshot(cx);
7066 let mut selections = self.selections.all::<Point>(cx);
7067 let mut clipboard_selections = Vec::with_capacity(selections.len());
7068 {
7069 let max_point = buffer.max_point();
7070 let mut is_first = true;
7071 for selection in &mut selections {
7072 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7073 if is_entire_line {
7074 selection.start = Point::new(selection.start.row, 0);
7075 if !selection.is_empty() && selection.end.column == 0 {
7076 selection.end = cmp::min(max_point, selection.end);
7077 } else {
7078 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7079 }
7080 selection.goal = SelectionGoal::None;
7081 }
7082 if is_first {
7083 is_first = false;
7084 } else {
7085 text += "\n";
7086 }
7087 let mut len = 0;
7088 for chunk in buffer.text_for_range(selection.start..selection.end) {
7089 text.push_str(chunk);
7090 len += chunk.len();
7091 }
7092 clipboard_selections.push(ClipboardSelection {
7093 len,
7094 is_entire_line,
7095 first_line_indent: buffer
7096 .indent_size_for_line(MultiBufferRow(selection.start.row))
7097 .len,
7098 });
7099 }
7100 }
7101
7102 self.transact(cx, |this, cx| {
7103 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7104 s.select(selections);
7105 });
7106 this.insert("", cx);
7107 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7108 text,
7109 clipboard_selections,
7110 ));
7111 });
7112 }
7113
7114 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7115 let selections = self.selections.all::<Point>(cx);
7116 let buffer = self.buffer.read(cx).read(cx);
7117 let mut text = String::new();
7118
7119 let mut clipboard_selections = Vec::with_capacity(selections.len());
7120 {
7121 let max_point = buffer.max_point();
7122 let mut is_first = true;
7123 for selection in selections.iter() {
7124 let mut start = selection.start;
7125 let mut end = selection.end;
7126 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7127 if is_entire_line {
7128 start = Point::new(start.row, 0);
7129 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7130 }
7131 if is_first {
7132 is_first = false;
7133 } else {
7134 text += "\n";
7135 }
7136 let mut len = 0;
7137 for chunk in buffer.text_for_range(start..end) {
7138 text.push_str(chunk);
7139 len += chunk.len();
7140 }
7141 clipboard_selections.push(ClipboardSelection {
7142 len,
7143 is_entire_line,
7144 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7145 });
7146 }
7147 }
7148
7149 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7150 text,
7151 clipboard_selections,
7152 ));
7153 }
7154
7155 pub fn do_paste(
7156 &mut self,
7157 text: &String,
7158 clipboard_selections: Option<Vec<ClipboardSelection>>,
7159 handle_entire_lines: bool,
7160 cx: &mut ViewContext<Self>,
7161 ) {
7162 if self.read_only(cx) {
7163 return;
7164 }
7165
7166 let clipboard_text = Cow::Borrowed(text);
7167
7168 self.transact(cx, |this, cx| {
7169 if let Some(mut clipboard_selections) = clipboard_selections {
7170 let old_selections = this.selections.all::<usize>(cx);
7171 let all_selections_were_entire_line =
7172 clipboard_selections.iter().all(|s| s.is_entire_line);
7173 let first_selection_indent_column =
7174 clipboard_selections.first().map(|s| s.first_line_indent);
7175 if clipboard_selections.len() != old_selections.len() {
7176 clipboard_selections.drain(..);
7177 }
7178
7179 this.buffer.update(cx, |buffer, cx| {
7180 let snapshot = buffer.read(cx);
7181 let mut start_offset = 0;
7182 let mut edits = Vec::new();
7183 let mut original_indent_columns = Vec::new();
7184 for (ix, selection) in old_selections.iter().enumerate() {
7185 let to_insert;
7186 let entire_line;
7187 let original_indent_column;
7188 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7189 let end_offset = start_offset + clipboard_selection.len;
7190 to_insert = &clipboard_text[start_offset..end_offset];
7191 entire_line = clipboard_selection.is_entire_line;
7192 start_offset = end_offset + 1;
7193 original_indent_column = Some(clipboard_selection.first_line_indent);
7194 } else {
7195 to_insert = clipboard_text.as_str();
7196 entire_line = all_selections_were_entire_line;
7197 original_indent_column = first_selection_indent_column
7198 }
7199
7200 // If the corresponding selection was empty when this slice of the
7201 // clipboard text was written, then the entire line containing the
7202 // selection was copied. If this selection is also currently empty,
7203 // then paste the line before the current line of the buffer.
7204 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7205 let column = selection.start.to_point(&snapshot).column as usize;
7206 let line_start = selection.start - column;
7207 line_start..line_start
7208 } else {
7209 selection.range()
7210 };
7211
7212 edits.push((range, to_insert));
7213 original_indent_columns.extend(original_indent_column);
7214 }
7215 drop(snapshot);
7216
7217 buffer.edit(
7218 edits,
7219 Some(AutoindentMode::Block {
7220 original_indent_columns,
7221 }),
7222 cx,
7223 );
7224 });
7225
7226 let selections = this.selections.all::<usize>(cx);
7227 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7228 } else {
7229 this.insert(&clipboard_text, cx);
7230 }
7231 });
7232 }
7233
7234 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7235 if let Some(item) = cx.read_from_clipboard() {
7236 let entries = item.entries();
7237
7238 match entries.first() {
7239 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7240 // of all the pasted entries.
7241 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7242 .do_paste(
7243 clipboard_string.text(),
7244 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7245 true,
7246 cx,
7247 ),
7248 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7249 }
7250 }
7251 }
7252
7253 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7254 if self.read_only(cx) {
7255 return;
7256 }
7257
7258 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7259 if let Some((selections, _)) =
7260 self.selection_history.transaction(transaction_id).cloned()
7261 {
7262 self.change_selections(None, cx, |s| {
7263 s.select_anchors(selections.to_vec());
7264 });
7265 }
7266 self.request_autoscroll(Autoscroll::fit(), cx);
7267 self.unmark_text(cx);
7268 self.refresh_inline_completion(true, false, cx);
7269 cx.emit(EditorEvent::Edited { transaction_id });
7270 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7271 }
7272 }
7273
7274 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7275 if self.read_only(cx) {
7276 return;
7277 }
7278
7279 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7280 if let Some((_, Some(selections))) =
7281 self.selection_history.transaction(transaction_id).cloned()
7282 {
7283 self.change_selections(None, cx, |s| {
7284 s.select_anchors(selections.to_vec());
7285 });
7286 }
7287 self.request_autoscroll(Autoscroll::fit(), cx);
7288 self.unmark_text(cx);
7289 self.refresh_inline_completion(true, false, cx);
7290 cx.emit(EditorEvent::Edited { transaction_id });
7291 }
7292 }
7293
7294 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7295 self.buffer
7296 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7297 }
7298
7299 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7300 self.buffer
7301 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7302 }
7303
7304 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7305 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7306 let line_mode = s.line_mode;
7307 s.move_with(|map, selection| {
7308 let cursor = if selection.is_empty() && !line_mode {
7309 movement::left(map, selection.start)
7310 } else {
7311 selection.start
7312 };
7313 selection.collapse_to(cursor, SelectionGoal::None);
7314 });
7315 })
7316 }
7317
7318 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7319 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7320 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7321 })
7322 }
7323
7324 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7325 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7326 let line_mode = s.line_mode;
7327 s.move_with(|map, selection| {
7328 let cursor = if selection.is_empty() && !line_mode {
7329 movement::right(map, selection.end)
7330 } else {
7331 selection.end
7332 };
7333 selection.collapse_to(cursor, SelectionGoal::None)
7334 });
7335 })
7336 }
7337
7338 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7339 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7340 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7341 })
7342 }
7343
7344 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7345 if self.take_rename(true, cx).is_some() {
7346 return;
7347 }
7348
7349 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7350 cx.propagate();
7351 return;
7352 }
7353
7354 let text_layout_details = &self.text_layout_details(cx);
7355 let selection_count = self.selections.count();
7356 let first_selection = self.selections.first_anchor();
7357
7358 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7359 let line_mode = s.line_mode;
7360 s.move_with(|map, selection| {
7361 if !selection.is_empty() && !line_mode {
7362 selection.goal = SelectionGoal::None;
7363 }
7364 let (cursor, goal) = movement::up(
7365 map,
7366 selection.start,
7367 selection.goal,
7368 false,
7369 text_layout_details,
7370 );
7371 selection.collapse_to(cursor, goal);
7372 });
7373 });
7374
7375 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7376 {
7377 cx.propagate();
7378 }
7379 }
7380
7381 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7382 if self.take_rename(true, cx).is_some() {
7383 return;
7384 }
7385
7386 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7387 cx.propagate();
7388 return;
7389 }
7390
7391 let text_layout_details = &self.text_layout_details(cx);
7392
7393 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7394 let line_mode = s.line_mode;
7395 s.move_with(|map, selection| {
7396 if !selection.is_empty() && !line_mode {
7397 selection.goal = SelectionGoal::None;
7398 }
7399 let (cursor, goal) = movement::up_by_rows(
7400 map,
7401 selection.start,
7402 action.lines,
7403 selection.goal,
7404 false,
7405 text_layout_details,
7406 );
7407 selection.collapse_to(cursor, goal);
7408 });
7409 })
7410 }
7411
7412 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7413 if self.take_rename(true, cx).is_some() {
7414 return;
7415 }
7416
7417 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7418 cx.propagate();
7419 return;
7420 }
7421
7422 let text_layout_details = &self.text_layout_details(cx);
7423
7424 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7425 let line_mode = s.line_mode;
7426 s.move_with(|map, selection| {
7427 if !selection.is_empty() && !line_mode {
7428 selection.goal = SelectionGoal::None;
7429 }
7430 let (cursor, goal) = movement::down_by_rows(
7431 map,
7432 selection.start,
7433 action.lines,
7434 selection.goal,
7435 false,
7436 text_layout_details,
7437 );
7438 selection.collapse_to(cursor, goal);
7439 });
7440 })
7441 }
7442
7443 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7444 let text_layout_details = &self.text_layout_details(cx);
7445 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7446 s.move_heads_with(|map, head, goal| {
7447 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7448 })
7449 })
7450 }
7451
7452 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7453 let text_layout_details = &self.text_layout_details(cx);
7454 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7455 s.move_heads_with(|map, head, goal| {
7456 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7457 })
7458 })
7459 }
7460
7461 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7462 let Some(row_count) = self.visible_row_count() else {
7463 return;
7464 };
7465
7466 let text_layout_details = &self.text_layout_details(cx);
7467
7468 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7469 s.move_heads_with(|map, head, goal| {
7470 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7471 })
7472 })
7473 }
7474
7475 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7476 if self.take_rename(true, cx).is_some() {
7477 return;
7478 }
7479
7480 if self
7481 .context_menu
7482 .write()
7483 .as_mut()
7484 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7485 .unwrap_or(false)
7486 {
7487 return;
7488 }
7489
7490 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7491 cx.propagate();
7492 return;
7493 }
7494
7495 let Some(row_count) = self.visible_row_count() else {
7496 return;
7497 };
7498
7499 let autoscroll = if action.center_cursor {
7500 Autoscroll::center()
7501 } else {
7502 Autoscroll::fit()
7503 };
7504
7505 let text_layout_details = &self.text_layout_details(cx);
7506
7507 self.change_selections(Some(autoscroll), cx, |s| {
7508 let line_mode = s.line_mode;
7509 s.move_with(|map, selection| {
7510 if !selection.is_empty() && !line_mode {
7511 selection.goal = SelectionGoal::None;
7512 }
7513 let (cursor, goal) = movement::up_by_rows(
7514 map,
7515 selection.end,
7516 row_count,
7517 selection.goal,
7518 false,
7519 text_layout_details,
7520 );
7521 selection.collapse_to(cursor, goal);
7522 });
7523 });
7524 }
7525
7526 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7527 let text_layout_details = &self.text_layout_details(cx);
7528 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7529 s.move_heads_with(|map, head, goal| {
7530 movement::up(map, head, goal, false, text_layout_details)
7531 })
7532 })
7533 }
7534
7535 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7536 self.take_rename(true, cx);
7537
7538 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7539 cx.propagate();
7540 return;
7541 }
7542
7543 let text_layout_details = &self.text_layout_details(cx);
7544 let selection_count = self.selections.count();
7545 let first_selection = self.selections.first_anchor();
7546
7547 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7548 let line_mode = s.line_mode;
7549 s.move_with(|map, selection| {
7550 if !selection.is_empty() && !line_mode {
7551 selection.goal = SelectionGoal::None;
7552 }
7553 let (cursor, goal) = movement::down(
7554 map,
7555 selection.end,
7556 selection.goal,
7557 false,
7558 text_layout_details,
7559 );
7560 selection.collapse_to(cursor, goal);
7561 });
7562 });
7563
7564 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7565 {
7566 cx.propagate();
7567 }
7568 }
7569
7570 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7571 let Some(row_count) = self.visible_row_count() else {
7572 return;
7573 };
7574
7575 let text_layout_details = &self.text_layout_details(cx);
7576
7577 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7578 s.move_heads_with(|map, head, goal| {
7579 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7580 })
7581 })
7582 }
7583
7584 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7585 if self.take_rename(true, cx).is_some() {
7586 return;
7587 }
7588
7589 if self
7590 .context_menu
7591 .write()
7592 .as_mut()
7593 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7594 .unwrap_or(false)
7595 {
7596 return;
7597 }
7598
7599 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7600 cx.propagate();
7601 return;
7602 }
7603
7604 let Some(row_count) = self.visible_row_count() else {
7605 return;
7606 };
7607
7608 let autoscroll = if action.center_cursor {
7609 Autoscroll::center()
7610 } else {
7611 Autoscroll::fit()
7612 };
7613
7614 let text_layout_details = &self.text_layout_details(cx);
7615 self.change_selections(Some(autoscroll), cx, |s| {
7616 let line_mode = s.line_mode;
7617 s.move_with(|map, selection| {
7618 if !selection.is_empty() && !line_mode {
7619 selection.goal = SelectionGoal::None;
7620 }
7621 let (cursor, goal) = movement::down_by_rows(
7622 map,
7623 selection.end,
7624 row_count,
7625 selection.goal,
7626 false,
7627 text_layout_details,
7628 );
7629 selection.collapse_to(cursor, goal);
7630 });
7631 });
7632 }
7633
7634 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7635 let text_layout_details = &self.text_layout_details(cx);
7636 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7637 s.move_heads_with(|map, head, goal| {
7638 movement::down(map, head, goal, false, text_layout_details)
7639 })
7640 });
7641 }
7642
7643 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7644 if let Some(context_menu) = self.context_menu.write().as_mut() {
7645 context_menu.select_first(self.completion_provider.as_deref(), cx);
7646 }
7647 }
7648
7649 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7650 if let Some(context_menu) = self.context_menu.write().as_mut() {
7651 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7652 }
7653 }
7654
7655 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7656 if let Some(context_menu) = self.context_menu.write().as_mut() {
7657 context_menu.select_next(self.completion_provider.as_deref(), cx);
7658 }
7659 }
7660
7661 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7662 if let Some(context_menu) = self.context_menu.write().as_mut() {
7663 context_menu.select_last(self.completion_provider.as_deref(), cx);
7664 }
7665 }
7666
7667 pub fn move_to_previous_word_start(
7668 &mut self,
7669 _: &MoveToPreviousWordStart,
7670 cx: &mut ViewContext<Self>,
7671 ) {
7672 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7673 s.move_cursors_with(|map, head, _| {
7674 (
7675 movement::previous_word_start(map, head),
7676 SelectionGoal::None,
7677 )
7678 });
7679 })
7680 }
7681
7682 pub fn move_to_previous_subword_start(
7683 &mut self,
7684 _: &MoveToPreviousSubwordStart,
7685 cx: &mut ViewContext<Self>,
7686 ) {
7687 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7688 s.move_cursors_with(|map, head, _| {
7689 (
7690 movement::previous_subword_start(map, head),
7691 SelectionGoal::None,
7692 )
7693 });
7694 })
7695 }
7696
7697 pub fn select_to_previous_word_start(
7698 &mut self,
7699 _: &SelectToPreviousWordStart,
7700 cx: &mut ViewContext<Self>,
7701 ) {
7702 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7703 s.move_heads_with(|map, head, _| {
7704 (
7705 movement::previous_word_start(map, head),
7706 SelectionGoal::None,
7707 )
7708 });
7709 })
7710 }
7711
7712 pub fn select_to_previous_subword_start(
7713 &mut self,
7714 _: &SelectToPreviousSubwordStart,
7715 cx: &mut ViewContext<Self>,
7716 ) {
7717 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7718 s.move_heads_with(|map, head, _| {
7719 (
7720 movement::previous_subword_start(map, head),
7721 SelectionGoal::None,
7722 )
7723 });
7724 })
7725 }
7726
7727 pub fn delete_to_previous_word_start(
7728 &mut self,
7729 action: &DeleteToPreviousWordStart,
7730 cx: &mut ViewContext<Self>,
7731 ) {
7732 self.transact(cx, |this, cx| {
7733 this.select_autoclose_pair(cx);
7734 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7735 let line_mode = s.line_mode;
7736 s.move_with(|map, selection| {
7737 if selection.is_empty() && !line_mode {
7738 let cursor = if action.ignore_newlines {
7739 movement::previous_word_start(map, selection.head())
7740 } else {
7741 movement::previous_word_start_or_newline(map, selection.head())
7742 };
7743 selection.set_head(cursor, SelectionGoal::None);
7744 }
7745 });
7746 });
7747 this.insert("", cx);
7748 });
7749 }
7750
7751 pub fn delete_to_previous_subword_start(
7752 &mut self,
7753 _: &DeleteToPreviousSubwordStart,
7754 cx: &mut ViewContext<Self>,
7755 ) {
7756 self.transact(cx, |this, cx| {
7757 this.select_autoclose_pair(cx);
7758 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7759 let line_mode = s.line_mode;
7760 s.move_with(|map, selection| {
7761 if selection.is_empty() && !line_mode {
7762 let cursor = movement::previous_subword_start(map, selection.head());
7763 selection.set_head(cursor, SelectionGoal::None);
7764 }
7765 });
7766 });
7767 this.insert("", cx);
7768 });
7769 }
7770
7771 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7772 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7773 s.move_cursors_with(|map, head, _| {
7774 (movement::next_word_end(map, head), SelectionGoal::None)
7775 });
7776 })
7777 }
7778
7779 pub fn move_to_next_subword_end(
7780 &mut self,
7781 _: &MoveToNextSubwordEnd,
7782 cx: &mut ViewContext<Self>,
7783 ) {
7784 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7785 s.move_cursors_with(|map, head, _| {
7786 (movement::next_subword_end(map, head), SelectionGoal::None)
7787 });
7788 })
7789 }
7790
7791 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7792 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7793 s.move_heads_with(|map, head, _| {
7794 (movement::next_word_end(map, head), SelectionGoal::None)
7795 });
7796 })
7797 }
7798
7799 pub fn select_to_next_subword_end(
7800 &mut self,
7801 _: &SelectToNextSubwordEnd,
7802 cx: &mut ViewContext<Self>,
7803 ) {
7804 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7805 s.move_heads_with(|map, head, _| {
7806 (movement::next_subword_end(map, head), SelectionGoal::None)
7807 });
7808 })
7809 }
7810
7811 pub fn delete_to_next_word_end(
7812 &mut self,
7813 action: &DeleteToNextWordEnd,
7814 cx: &mut ViewContext<Self>,
7815 ) {
7816 self.transact(cx, |this, cx| {
7817 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7818 let line_mode = s.line_mode;
7819 s.move_with(|map, selection| {
7820 if selection.is_empty() && !line_mode {
7821 let cursor = if action.ignore_newlines {
7822 movement::next_word_end(map, selection.head())
7823 } else {
7824 movement::next_word_end_or_newline(map, selection.head())
7825 };
7826 selection.set_head(cursor, SelectionGoal::None);
7827 }
7828 });
7829 });
7830 this.insert("", cx);
7831 });
7832 }
7833
7834 pub fn delete_to_next_subword_end(
7835 &mut self,
7836 _: &DeleteToNextSubwordEnd,
7837 cx: &mut ViewContext<Self>,
7838 ) {
7839 self.transact(cx, |this, cx| {
7840 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7841 s.move_with(|map, selection| {
7842 if selection.is_empty() {
7843 let cursor = movement::next_subword_end(map, selection.head());
7844 selection.set_head(cursor, SelectionGoal::None);
7845 }
7846 });
7847 });
7848 this.insert("", cx);
7849 });
7850 }
7851
7852 pub fn move_to_beginning_of_line(
7853 &mut self,
7854 action: &MoveToBeginningOfLine,
7855 cx: &mut ViewContext<Self>,
7856 ) {
7857 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7858 s.move_cursors_with(|map, head, _| {
7859 (
7860 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7861 SelectionGoal::None,
7862 )
7863 });
7864 })
7865 }
7866
7867 pub fn select_to_beginning_of_line(
7868 &mut self,
7869 action: &SelectToBeginningOfLine,
7870 cx: &mut ViewContext<Self>,
7871 ) {
7872 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7873 s.move_heads_with(|map, head, _| {
7874 (
7875 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7876 SelectionGoal::None,
7877 )
7878 });
7879 });
7880 }
7881
7882 pub fn delete_to_beginning_of_line(
7883 &mut self,
7884 _: &DeleteToBeginningOfLine,
7885 cx: &mut ViewContext<Self>,
7886 ) {
7887 self.transact(cx, |this, cx| {
7888 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7889 s.move_with(|_, selection| {
7890 selection.reversed = true;
7891 });
7892 });
7893
7894 this.select_to_beginning_of_line(
7895 &SelectToBeginningOfLine {
7896 stop_at_soft_wraps: false,
7897 },
7898 cx,
7899 );
7900 this.backspace(&Backspace, cx);
7901 });
7902 }
7903
7904 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7905 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7906 s.move_cursors_with(|map, head, _| {
7907 (
7908 movement::line_end(map, head, action.stop_at_soft_wraps),
7909 SelectionGoal::None,
7910 )
7911 });
7912 })
7913 }
7914
7915 pub fn select_to_end_of_line(
7916 &mut self,
7917 action: &SelectToEndOfLine,
7918 cx: &mut ViewContext<Self>,
7919 ) {
7920 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7921 s.move_heads_with(|map, head, _| {
7922 (
7923 movement::line_end(map, head, action.stop_at_soft_wraps),
7924 SelectionGoal::None,
7925 )
7926 });
7927 })
7928 }
7929
7930 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7931 self.transact(cx, |this, cx| {
7932 this.select_to_end_of_line(
7933 &SelectToEndOfLine {
7934 stop_at_soft_wraps: false,
7935 },
7936 cx,
7937 );
7938 this.delete(&Delete, cx);
7939 });
7940 }
7941
7942 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7943 self.transact(cx, |this, cx| {
7944 this.select_to_end_of_line(
7945 &SelectToEndOfLine {
7946 stop_at_soft_wraps: false,
7947 },
7948 cx,
7949 );
7950 this.cut(&Cut, cx);
7951 });
7952 }
7953
7954 pub fn move_to_start_of_paragraph(
7955 &mut self,
7956 _: &MoveToStartOfParagraph,
7957 cx: &mut ViewContext<Self>,
7958 ) {
7959 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7960 cx.propagate();
7961 return;
7962 }
7963
7964 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7965 s.move_with(|map, selection| {
7966 selection.collapse_to(
7967 movement::start_of_paragraph(map, selection.head(), 1),
7968 SelectionGoal::None,
7969 )
7970 });
7971 })
7972 }
7973
7974 pub fn move_to_end_of_paragraph(
7975 &mut self,
7976 _: &MoveToEndOfParagraph,
7977 cx: &mut ViewContext<Self>,
7978 ) {
7979 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7980 cx.propagate();
7981 return;
7982 }
7983
7984 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7985 s.move_with(|map, selection| {
7986 selection.collapse_to(
7987 movement::end_of_paragraph(map, selection.head(), 1),
7988 SelectionGoal::None,
7989 )
7990 });
7991 })
7992 }
7993
7994 pub fn select_to_start_of_paragraph(
7995 &mut self,
7996 _: &SelectToStartOfParagraph,
7997 cx: &mut ViewContext<Self>,
7998 ) {
7999 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8000 cx.propagate();
8001 return;
8002 }
8003
8004 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8005 s.move_heads_with(|map, head, _| {
8006 (
8007 movement::start_of_paragraph(map, head, 1),
8008 SelectionGoal::None,
8009 )
8010 });
8011 })
8012 }
8013
8014 pub fn select_to_end_of_paragraph(
8015 &mut self,
8016 _: &SelectToEndOfParagraph,
8017 cx: &mut ViewContext<Self>,
8018 ) {
8019 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8020 cx.propagate();
8021 return;
8022 }
8023
8024 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8025 s.move_heads_with(|map, head, _| {
8026 (
8027 movement::end_of_paragraph(map, head, 1),
8028 SelectionGoal::None,
8029 )
8030 });
8031 })
8032 }
8033
8034 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8035 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8036 cx.propagate();
8037 return;
8038 }
8039
8040 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8041 s.select_ranges(vec![0..0]);
8042 });
8043 }
8044
8045 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8046 let mut selection = self.selections.last::<Point>(cx);
8047 selection.set_head(Point::zero(), SelectionGoal::None);
8048
8049 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8050 s.select(vec![selection]);
8051 });
8052 }
8053
8054 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8055 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8056 cx.propagate();
8057 return;
8058 }
8059
8060 let cursor = self.buffer.read(cx).read(cx).len();
8061 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8062 s.select_ranges(vec![cursor..cursor])
8063 });
8064 }
8065
8066 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8067 self.nav_history = nav_history;
8068 }
8069
8070 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8071 self.nav_history.as_ref()
8072 }
8073
8074 fn push_to_nav_history(
8075 &mut self,
8076 cursor_anchor: Anchor,
8077 new_position: Option<Point>,
8078 cx: &mut ViewContext<Self>,
8079 ) {
8080 if let Some(nav_history) = self.nav_history.as_mut() {
8081 let buffer = self.buffer.read(cx).read(cx);
8082 let cursor_position = cursor_anchor.to_point(&buffer);
8083 let scroll_state = self.scroll_manager.anchor();
8084 let scroll_top_row = scroll_state.top_row(&buffer);
8085 drop(buffer);
8086
8087 if let Some(new_position) = new_position {
8088 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8089 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8090 return;
8091 }
8092 }
8093
8094 nav_history.push(
8095 Some(NavigationData {
8096 cursor_anchor,
8097 cursor_position,
8098 scroll_anchor: scroll_state,
8099 scroll_top_row,
8100 }),
8101 cx,
8102 );
8103 }
8104 }
8105
8106 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8107 let buffer = self.buffer.read(cx).snapshot(cx);
8108 let mut selection = self.selections.first::<usize>(cx);
8109 selection.set_head(buffer.len(), SelectionGoal::None);
8110 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8111 s.select(vec![selection]);
8112 });
8113 }
8114
8115 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8116 let end = self.buffer.read(cx).read(cx).len();
8117 self.change_selections(None, cx, |s| {
8118 s.select_ranges(vec![0..end]);
8119 });
8120 }
8121
8122 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8123 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8124 let mut selections = self.selections.all::<Point>(cx);
8125 let max_point = display_map.buffer_snapshot.max_point();
8126 for selection in &mut selections {
8127 let rows = selection.spanned_rows(true, &display_map);
8128 selection.start = Point::new(rows.start.0, 0);
8129 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8130 selection.reversed = false;
8131 }
8132 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8133 s.select(selections);
8134 });
8135 }
8136
8137 pub fn split_selection_into_lines(
8138 &mut self,
8139 _: &SplitSelectionIntoLines,
8140 cx: &mut ViewContext<Self>,
8141 ) {
8142 let mut to_unfold = Vec::new();
8143 let mut new_selection_ranges = Vec::new();
8144 {
8145 let selections = self.selections.all::<Point>(cx);
8146 let buffer = self.buffer.read(cx).read(cx);
8147 for selection in selections {
8148 for row in selection.start.row..selection.end.row {
8149 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8150 new_selection_ranges.push(cursor..cursor);
8151 }
8152 new_selection_ranges.push(selection.end..selection.end);
8153 to_unfold.push(selection.start..selection.end);
8154 }
8155 }
8156 self.unfold_ranges(to_unfold, true, true, cx);
8157 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8158 s.select_ranges(new_selection_ranges);
8159 });
8160 }
8161
8162 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8163 self.add_selection(true, cx);
8164 }
8165
8166 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8167 self.add_selection(false, cx);
8168 }
8169
8170 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8171 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8172 let mut selections = self.selections.all::<Point>(cx);
8173 let text_layout_details = self.text_layout_details(cx);
8174 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8175 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8176 let range = oldest_selection.display_range(&display_map).sorted();
8177
8178 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8179 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8180 let positions = start_x.min(end_x)..start_x.max(end_x);
8181
8182 selections.clear();
8183 let mut stack = Vec::new();
8184 for row in range.start.row().0..=range.end.row().0 {
8185 if let Some(selection) = self.selections.build_columnar_selection(
8186 &display_map,
8187 DisplayRow(row),
8188 &positions,
8189 oldest_selection.reversed,
8190 &text_layout_details,
8191 ) {
8192 stack.push(selection.id);
8193 selections.push(selection);
8194 }
8195 }
8196
8197 if above {
8198 stack.reverse();
8199 }
8200
8201 AddSelectionsState { above, stack }
8202 });
8203
8204 let last_added_selection = *state.stack.last().unwrap();
8205 let mut new_selections = Vec::new();
8206 if above == state.above {
8207 let end_row = if above {
8208 DisplayRow(0)
8209 } else {
8210 display_map.max_point().row()
8211 };
8212
8213 'outer: for selection in selections {
8214 if selection.id == last_added_selection {
8215 let range = selection.display_range(&display_map).sorted();
8216 debug_assert_eq!(range.start.row(), range.end.row());
8217 let mut row = range.start.row();
8218 let positions =
8219 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8220 px(start)..px(end)
8221 } else {
8222 let start_x =
8223 display_map.x_for_display_point(range.start, &text_layout_details);
8224 let end_x =
8225 display_map.x_for_display_point(range.end, &text_layout_details);
8226 start_x.min(end_x)..start_x.max(end_x)
8227 };
8228
8229 while row != end_row {
8230 if above {
8231 row.0 -= 1;
8232 } else {
8233 row.0 += 1;
8234 }
8235
8236 if let Some(new_selection) = self.selections.build_columnar_selection(
8237 &display_map,
8238 row,
8239 &positions,
8240 selection.reversed,
8241 &text_layout_details,
8242 ) {
8243 state.stack.push(new_selection.id);
8244 if above {
8245 new_selections.push(new_selection);
8246 new_selections.push(selection);
8247 } else {
8248 new_selections.push(selection);
8249 new_selections.push(new_selection);
8250 }
8251
8252 continue 'outer;
8253 }
8254 }
8255 }
8256
8257 new_selections.push(selection);
8258 }
8259 } else {
8260 new_selections = selections;
8261 new_selections.retain(|s| s.id != last_added_selection);
8262 state.stack.pop();
8263 }
8264
8265 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8266 s.select(new_selections);
8267 });
8268 if state.stack.len() > 1 {
8269 self.add_selections_state = Some(state);
8270 }
8271 }
8272
8273 pub fn select_next_match_internal(
8274 &mut self,
8275 display_map: &DisplaySnapshot,
8276 replace_newest: bool,
8277 autoscroll: Option<Autoscroll>,
8278 cx: &mut ViewContext<Self>,
8279 ) -> Result<()> {
8280 fn select_next_match_ranges(
8281 this: &mut Editor,
8282 range: Range<usize>,
8283 replace_newest: bool,
8284 auto_scroll: Option<Autoscroll>,
8285 cx: &mut ViewContext<Editor>,
8286 ) {
8287 this.unfold_ranges([range.clone()], false, true, cx);
8288 this.change_selections(auto_scroll, cx, |s| {
8289 if replace_newest {
8290 s.delete(s.newest_anchor().id);
8291 }
8292 s.insert_range(range.clone());
8293 });
8294 }
8295
8296 let buffer = &display_map.buffer_snapshot;
8297 let mut selections = self.selections.all::<usize>(cx);
8298 if let Some(mut select_next_state) = self.select_next_state.take() {
8299 let query = &select_next_state.query;
8300 if !select_next_state.done {
8301 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8302 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8303 let mut next_selected_range = None;
8304
8305 let bytes_after_last_selection =
8306 buffer.bytes_in_range(last_selection.end..buffer.len());
8307 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8308 let query_matches = query
8309 .stream_find_iter(bytes_after_last_selection)
8310 .map(|result| (last_selection.end, result))
8311 .chain(
8312 query
8313 .stream_find_iter(bytes_before_first_selection)
8314 .map(|result| (0, result)),
8315 );
8316
8317 for (start_offset, query_match) in query_matches {
8318 let query_match = query_match.unwrap(); // can only fail due to I/O
8319 let offset_range =
8320 start_offset + query_match.start()..start_offset + query_match.end();
8321 let display_range = offset_range.start.to_display_point(display_map)
8322 ..offset_range.end.to_display_point(display_map);
8323
8324 if !select_next_state.wordwise
8325 || (!movement::is_inside_word(display_map, display_range.start)
8326 && !movement::is_inside_word(display_map, display_range.end))
8327 {
8328 // TODO: This is n^2, because we might check all the selections
8329 if !selections
8330 .iter()
8331 .any(|selection| selection.range().overlaps(&offset_range))
8332 {
8333 next_selected_range = Some(offset_range);
8334 break;
8335 }
8336 }
8337 }
8338
8339 if let Some(next_selected_range) = next_selected_range {
8340 select_next_match_ranges(
8341 self,
8342 next_selected_range,
8343 replace_newest,
8344 autoscroll,
8345 cx,
8346 );
8347 } else {
8348 select_next_state.done = true;
8349 }
8350 }
8351
8352 self.select_next_state = Some(select_next_state);
8353 } else {
8354 let mut only_carets = true;
8355 let mut same_text_selected = true;
8356 let mut selected_text = None;
8357
8358 let mut selections_iter = selections.iter().peekable();
8359 while let Some(selection) = selections_iter.next() {
8360 if selection.start != selection.end {
8361 only_carets = false;
8362 }
8363
8364 if same_text_selected {
8365 if selected_text.is_none() {
8366 selected_text =
8367 Some(buffer.text_for_range(selection.range()).collect::<String>());
8368 }
8369
8370 if let Some(next_selection) = selections_iter.peek() {
8371 if next_selection.range().len() == selection.range().len() {
8372 let next_selected_text = buffer
8373 .text_for_range(next_selection.range())
8374 .collect::<String>();
8375 if Some(next_selected_text) != selected_text {
8376 same_text_selected = false;
8377 selected_text = None;
8378 }
8379 } else {
8380 same_text_selected = false;
8381 selected_text = None;
8382 }
8383 }
8384 }
8385 }
8386
8387 if only_carets {
8388 for selection in &mut selections {
8389 let word_range = movement::surrounding_word(
8390 display_map,
8391 selection.start.to_display_point(display_map),
8392 );
8393 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8394 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8395 selection.goal = SelectionGoal::None;
8396 selection.reversed = false;
8397 select_next_match_ranges(
8398 self,
8399 selection.start..selection.end,
8400 replace_newest,
8401 autoscroll,
8402 cx,
8403 );
8404 }
8405
8406 if selections.len() == 1 {
8407 let selection = selections
8408 .last()
8409 .expect("ensured that there's only one selection");
8410 let query = buffer
8411 .text_for_range(selection.start..selection.end)
8412 .collect::<String>();
8413 let is_empty = query.is_empty();
8414 let select_state = SelectNextState {
8415 query: AhoCorasick::new(&[query])?,
8416 wordwise: true,
8417 done: is_empty,
8418 };
8419 self.select_next_state = Some(select_state);
8420 } else {
8421 self.select_next_state = None;
8422 }
8423 } else if let Some(selected_text) = selected_text {
8424 self.select_next_state = Some(SelectNextState {
8425 query: AhoCorasick::new(&[selected_text])?,
8426 wordwise: false,
8427 done: false,
8428 });
8429 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8430 }
8431 }
8432 Ok(())
8433 }
8434
8435 pub fn select_all_matches(
8436 &mut self,
8437 _action: &SelectAllMatches,
8438 cx: &mut ViewContext<Self>,
8439 ) -> Result<()> {
8440 self.push_to_selection_history();
8441 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8442
8443 self.select_next_match_internal(&display_map, false, None, cx)?;
8444 let Some(select_next_state) = self.select_next_state.as_mut() else {
8445 return Ok(());
8446 };
8447 if select_next_state.done {
8448 return Ok(());
8449 }
8450
8451 let mut new_selections = self.selections.all::<usize>(cx);
8452
8453 let buffer = &display_map.buffer_snapshot;
8454 let query_matches = select_next_state
8455 .query
8456 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8457
8458 for query_match in query_matches {
8459 let query_match = query_match.unwrap(); // can only fail due to I/O
8460 let offset_range = query_match.start()..query_match.end();
8461 let display_range = offset_range.start.to_display_point(&display_map)
8462 ..offset_range.end.to_display_point(&display_map);
8463
8464 if !select_next_state.wordwise
8465 || (!movement::is_inside_word(&display_map, display_range.start)
8466 && !movement::is_inside_word(&display_map, display_range.end))
8467 {
8468 self.selections.change_with(cx, |selections| {
8469 new_selections.push(Selection {
8470 id: selections.new_selection_id(),
8471 start: offset_range.start,
8472 end: offset_range.end,
8473 reversed: false,
8474 goal: SelectionGoal::None,
8475 });
8476 });
8477 }
8478 }
8479
8480 new_selections.sort_by_key(|selection| selection.start);
8481 let mut ix = 0;
8482 while ix + 1 < new_selections.len() {
8483 let current_selection = &new_selections[ix];
8484 let next_selection = &new_selections[ix + 1];
8485 if current_selection.range().overlaps(&next_selection.range()) {
8486 if current_selection.id < next_selection.id {
8487 new_selections.remove(ix + 1);
8488 } else {
8489 new_selections.remove(ix);
8490 }
8491 } else {
8492 ix += 1;
8493 }
8494 }
8495
8496 select_next_state.done = true;
8497 self.unfold_ranges(
8498 new_selections.iter().map(|selection| selection.range()),
8499 false,
8500 false,
8501 cx,
8502 );
8503 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8504 selections.select(new_selections)
8505 });
8506
8507 Ok(())
8508 }
8509
8510 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8511 self.push_to_selection_history();
8512 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8513 self.select_next_match_internal(
8514 &display_map,
8515 action.replace_newest,
8516 Some(Autoscroll::newest()),
8517 cx,
8518 )?;
8519 Ok(())
8520 }
8521
8522 pub fn select_previous(
8523 &mut self,
8524 action: &SelectPrevious,
8525 cx: &mut ViewContext<Self>,
8526 ) -> Result<()> {
8527 self.push_to_selection_history();
8528 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8529 let buffer = &display_map.buffer_snapshot;
8530 let mut selections = self.selections.all::<usize>(cx);
8531 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8532 let query = &select_prev_state.query;
8533 if !select_prev_state.done {
8534 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8535 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8536 let mut next_selected_range = None;
8537 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8538 let bytes_before_last_selection =
8539 buffer.reversed_bytes_in_range(0..last_selection.start);
8540 let bytes_after_first_selection =
8541 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8542 let query_matches = query
8543 .stream_find_iter(bytes_before_last_selection)
8544 .map(|result| (last_selection.start, result))
8545 .chain(
8546 query
8547 .stream_find_iter(bytes_after_first_selection)
8548 .map(|result| (buffer.len(), result)),
8549 );
8550 for (end_offset, query_match) in query_matches {
8551 let query_match = query_match.unwrap(); // can only fail due to I/O
8552 let offset_range =
8553 end_offset - query_match.end()..end_offset - query_match.start();
8554 let display_range = offset_range.start.to_display_point(&display_map)
8555 ..offset_range.end.to_display_point(&display_map);
8556
8557 if !select_prev_state.wordwise
8558 || (!movement::is_inside_word(&display_map, display_range.start)
8559 && !movement::is_inside_word(&display_map, display_range.end))
8560 {
8561 next_selected_range = Some(offset_range);
8562 break;
8563 }
8564 }
8565
8566 if let Some(next_selected_range) = next_selected_range {
8567 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8568 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8569 if action.replace_newest {
8570 s.delete(s.newest_anchor().id);
8571 }
8572 s.insert_range(next_selected_range);
8573 });
8574 } else {
8575 select_prev_state.done = true;
8576 }
8577 }
8578
8579 self.select_prev_state = Some(select_prev_state);
8580 } else {
8581 let mut only_carets = true;
8582 let mut same_text_selected = true;
8583 let mut selected_text = None;
8584
8585 let mut selections_iter = selections.iter().peekable();
8586 while let Some(selection) = selections_iter.next() {
8587 if selection.start != selection.end {
8588 only_carets = false;
8589 }
8590
8591 if same_text_selected {
8592 if selected_text.is_none() {
8593 selected_text =
8594 Some(buffer.text_for_range(selection.range()).collect::<String>());
8595 }
8596
8597 if let Some(next_selection) = selections_iter.peek() {
8598 if next_selection.range().len() == selection.range().len() {
8599 let next_selected_text = buffer
8600 .text_for_range(next_selection.range())
8601 .collect::<String>();
8602 if Some(next_selected_text) != selected_text {
8603 same_text_selected = false;
8604 selected_text = None;
8605 }
8606 } else {
8607 same_text_selected = false;
8608 selected_text = None;
8609 }
8610 }
8611 }
8612 }
8613
8614 if only_carets {
8615 for selection in &mut selections {
8616 let word_range = movement::surrounding_word(
8617 &display_map,
8618 selection.start.to_display_point(&display_map),
8619 );
8620 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8621 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8622 selection.goal = SelectionGoal::None;
8623 selection.reversed = false;
8624 }
8625 if selections.len() == 1 {
8626 let selection = selections
8627 .last()
8628 .expect("ensured that there's only one selection");
8629 let query = buffer
8630 .text_for_range(selection.start..selection.end)
8631 .collect::<String>();
8632 let is_empty = query.is_empty();
8633 let select_state = SelectNextState {
8634 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8635 wordwise: true,
8636 done: is_empty,
8637 };
8638 self.select_prev_state = Some(select_state);
8639 } else {
8640 self.select_prev_state = None;
8641 }
8642
8643 self.unfold_ranges(
8644 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8645 false,
8646 true,
8647 cx,
8648 );
8649 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8650 s.select(selections);
8651 });
8652 } else if let Some(selected_text) = selected_text {
8653 self.select_prev_state = Some(SelectNextState {
8654 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8655 wordwise: false,
8656 done: false,
8657 });
8658 self.select_previous(action, cx)?;
8659 }
8660 }
8661 Ok(())
8662 }
8663
8664 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8665 let text_layout_details = &self.text_layout_details(cx);
8666 self.transact(cx, |this, cx| {
8667 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8668 let mut edits = Vec::new();
8669 let mut selection_edit_ranges = Vec::new();
8670 let mut last_toggled_row = None;
8671 let snapshot = this.buffer.read(cx).read(cx);
8672 let empty_str: Arc<str> = Arc::default();
8673 let mut suffixes_inserted = Vec::new();
8674
8675 fn comment_prefix_range(
8676 snapshot: &MultiBufferSnapshot,
8677 row: MultiBufferRow,
8678 comment_prefix: &str,
8679 comment_prefix_whitespace: &str,
8680 ) -> Range<Point> {
8681 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8682
8683 let mut line_bytes = snapshot
8684 .bytes_in_range(start..snapshot.max_point())
8685 .flatten()
8686 .copied();
8687
8688 // If this line currently begins with the line comment prefix, then record
8689 // the range containing the prefix.
8690 if line_bytes
8691 .by_ref()
8692 .take(comment_prefix.len())
8693 .eq(comment_prefix.bytes())
8694 {
8695 // Include any whitespace that matches the comment prefix.
8696 let matching_whitespace_len = line_bytes
8697 .zip(comment_prefix_whitespace.bytes())
8698 .take_while(|(a, b)| a == b)
8699 .count() as u32;
8700 let end = Point::new(
8701 start.row,
8702 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8703 );
8704 start..end
8705 } else {
8706 start..start
8707 }
8708 }
8709
8710 fn comment_suffix_range(
8711 snapshot: &MultiBufferSnapshot,
8712 row: MultiBufferRow,
8713 comment_suffix: &str,
8714 comment_suffix_has_leading_space: bool,
8715 ) -> Range<Point> {
8716 let end = Point::new(row.0, snapshot.line_len(row));
8717 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8718
8719 let mut line_end_bytes = snapshot
8720 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8721 .flatten()
8722 .copied();
8723
8724 let leading_space_len = if suffix_start_column > 0
8725 && line_end_bytes.next() == Some(b' ')
8726 && comment_suffix_has_leading_space
8727 {
8728 1
8729 } else {
8730 0
8731 };
8732
8733 // If this line currently begins with the line comment prefix, then record
8734 // the range containing the prefix.
8735 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8736 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8737 start..end
8738 } else {
8739 end..end
8740 }
8741 }
8742
8743 // TODO: Handle selections that cross excerpts
8744 for selection in &mut selections {
8745 let start_column = snapshot
8746 .indent_size_for_line(MultiBufferRow(selection.start.row))
8747 .len;
8748 let language = if let Some(language) =
8749 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8750 {
8751 language
8752 } else {
8753 continue;
8754 };
8755
8756 selection_edit_ranges.clear();
8757
8758 // If multiple selections contain a given row, avoid processing that
8759 // row more than once.
8760 let mut start_row = MultiBufferRow(selection.start.row);
8761 if last_toggled_row == Some(start_row) {
8762 start_row = start_row.next_row();
8763 }
8764 let end_row =
8765 if selection.end.row > selection.start.row && selection.end.column == 0 {
8766 MultiBufferRow(selection.end.row - 1)
8767 } else {
8768 MultiBufferRow(selection.end.row)
8769 };
8770 last_toggled_row = Some(end_row);
8771
8772 if start_row > end_row {
8773 continue;
8774 }
8775
8776 // If the language has line comments, toggle those.
8777 let full_comment_prefixes = language.line_comment_prefixes();
8778 if !full_comment_prefixes.is_empty() {
8779 let first_prefix = full_comment_prefixes
8780 .first()
8781 .expect("prefixes is non-empty");
8782 let prefix_trimmed_lengths = full_comment_prefixes
8783 .iter()
8784 .map(|p| p.trim_end_matches(' ').len())
8785 .collect::<SmallVec<[usize; 4]>>();
8786
8787 let mut all_selection_lines_are_comments = true;
8788
8789 for row in start_row.0..=end_row.0 {
8790 let row = MultiBufferRow(row);
8791 if start_row < end_row && snapshot.is_line_blank(row) {
8792 continue;
8793 }
8794
8795 let prefix_range = full_comment_prefixes
8796 .iter()
8797 .zip(prefix_trimmed_lengths.iter().copied())
8798 .map(|(prefix, trimmed_prefix_len)| {
8799 comment_prefix_range(
8800 snapshot.deref(),
8801 row,
8802 &prefix[..trimmed_prefix_len],
8803 &prefix[trimmed_prefix_len..],
8804 )
8805 })
8806 .max_by_key(|range| range.end.column - range.start.column)
8807 .expect("prefixes is non-empty");
8808
8809 if prefix_range.is_empty() {
8810 all_selection_lines_are_comments = false;
8811 }
8812
8813 selection_edit_ranges.push(prefix_range);
8814 }
8815
8816 if all_selection_lines_are_comments {
8817 edits.extend(
8818 selection_edit_ranges
8819 .iter()
8820 .cloned()
8821 .map(|range| (range, empty_str.clone())),
8822 );
8823 } else {
8824 let min_column = selection_edit_ranges
8825 .iter()
8826 .map(|range| range.start.column)
8827 .min()
8828 .unwrap_or(0);
8829 edits.extend(selection_edit_ranges.iter().map(|range| {
8830 let position = Point::new(range.start.row, min_column);
8831 (position..position, first_prefix.clone())
8832 }));
8833 }
8834 } else if let Some((full_comment_prefix, comment_suffix)) =
8835 language.block_comment_delimiters()
8836 {
8837 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8838 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8839 let prefix_range = comment_prefix_range(
8840 snapshot.deref(),
8841 start_row,
8842 comment_prefix,
8843 comment_prefix_whitespace,
8844 );
8845 let suffix_range = comment_suffix_range(
8846 snapshot.deref(),
8847 end_row,
8848 comment_suffix.trim_start_matches(' '),
8849 comment_suffix.starts_with(' '),
8850 );
8851
8852 if prefix_range.is_empty() || suffix_range.is_empty() {
8853 edits.push((
8854 prefix_range.start..prefix_range.start,
8855 full_comment_prefix.clone(),
8856 ));
8857 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8858 suffixes_inserted.push((end_row, comment_suffix.len()));
8859 } else {
8860 edits.push((prefix_range, empty_str.clone()));
8861 edits.push((suffix_range, empty_str.clone()));
8862 }
8863 } else {
8864 continue;
8865 }
8866 }
8867
8868 drop(snapshot);
8869 this.buffer.update(cx, |buffer, cx| {
8870 buffer.edit(edits, None, cx);
8871 });
8872
8873 // Adjust selections so that they end before any comment suffixes that
8874 // were inserted.
8875 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8876 let mut selections = this.selections.all::<Point>(cx);
8877 let snapshot = this.buffer.read(cx).read(cx);
8878 for selection in &mut selections {
8879 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8880 match row.cmp(&MultiBufferRow(selection.end.row)) {
8881 Ordering::Less => {
8882 suffixes_inserted.next();
8883 continue;
8884 }
8885 Ordering::Greater => break,
8886 Ordering::Equal => {
8887 if selection.end.column == snapshot.line_len(row) {
8888 if selection.is_empty() {
8889 selection.start.column -= suffix_len as u32;
8890 }
8891 selection.end.column -= suffix_len as u32;
8892 }
8893 break;
8894 }
8895 }
8896 }
8897 }
8898
8899 drop(snapshot);
8900 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8901
8902 let selections = this.selections.all::<Point>(cx);
8903 let selections_on_single_row = selections.windows(2).all(|selections| {
8904 selections[0].start.row == selections[1].start.row
8905 && selections[0].end.row == selections[1].end.row
8906 && selections[0].start.row == selections[0].end.row
8907 });
8908 let selections_selecting = selections
8909 .iter()
8910 .any(|selection| selection.start != selection.end);
8911 let advance_downwards = action.advance_downwards
8912 && selections_on_single_row
8913 && !selections_selecting
8914 && !matches!(this.mode, EditorMode::SingleLine { .. });
8915
8916 if advance_downwards {
8917 let snapshot = this.buffer.read(cx).snapshot(cx);
8918
8919 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8920 s.move_cursors_with(|display_snapshot, display_point, _| {
8921 let mut point = display_point.to_point(display_snapshot);
8922 point.row += 1;
8923 point = snapshot.clip_point(point, Bias::Left);
8924 let display_point = point.to_display_point(display_snapshot);
8925 let goal = SelectionGoal::HorizontalPosition(
8926 display_snapshot
8927 .x_for_display_point(display_point, text_layout_details)
8928 .into(),
8929 );
8930 (display_point, goal)
8931 })
8932 });
8933 }
8934 });
8935 }
8936
8937 pub fn select_enclosing_symbol(
8938 &mut self,
8939 _: &SelectEnclosingSymbol,
8940 cx: &mut ViewContext<Self>,
8941 ) {
8942 let buffer = self.buffer.read(cx).snapshot(cx);
8943 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8944
8945 fn update_selection(
8946 selection: &Selection<usize>,
8947 buffer_snap: &MultiBufferSnapshot,
8948 ) -> Option<Selection<usize>> {
8949 let cursor = selection.head();
8950 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8951 for symbol in symbols.iter().rev() {
8952 let start = symbol.range.start.to_offset(buffer_snap);
8953 let end = symbol.range.end.to_offset(buffer_snap);
8954 let new_range = start..end;
8955 if start < selection.start || end > selection.end {
8956 return Some(Selection {
8957 id: selection.id,
8958 start: new_range.start,
8959 end: new_range.end,
8960 goal: SelectionGoal::None,
8961 reversed: selection.reversed,
8962 });
8963 }
8964 }
8965 None
8966 }
8967
8968 let mut selected_larger_symbol = false;
8969 let new_selections = old_selections
8970 .iter()
8971 .map(|selection| match update_selection(selection, &buffer) {
8972 Some(new_selection) => {
8973 if new_selection.range() != selection.range() {
8974 selected_larger_symbol = true;
8975 }
8976 new_selection
8977 }
8978 None => selection.clone(),
8979 })
8980 .collect::<Vec<_>>();
8981
8982 if selected_larger_symbol {
8983 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8984 s.select(new_selections);
8985 });
8986 }
8987 }
8988
8989 pub fn select_larger_syntax_node(
8990 &mut self,
8991 _: &SelectLargerSyntaxNode,
8992 cx: &mut ViewContext<Self>,
8993 ) {
8994 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8995 let buffer = self.buffer.read(cx).snapshot(cx);
8996 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8997
8998 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8999 let mut selected_larger_node = false;
9000 let new_selections = old_selections
9001 .iter()
9002 .map(|selection| {
9003 let old_range = selection.start..selection.end;
9004 let mut new_range = old_range.clone();
9005 while let Some(containing_range) =
9006 buffer.range_for_syntax_ancestor(new_range.clone())
9007 {
9008 new_range = containing_range;
9009 if !display_map.intersects_fold(new_range.start)
9010 && !display_map.intersects_fold(new_range.end)
9011 {
9012 break;
9013 }
9014 }
9015
9016 selected_larger_node |= new_range != old_range;
9017 Selection {
9018 id: selection.id,
9019 start: new_range.start,
9020 end: new_range.end,
9021 goal: SelectionGoal::None,
9022 reversed: selection.reversed,
9023 }
9024 })
9025 .collect::<Vec<_>>();
9026
9027 if selected_larger_node {
9028 stack.push(old_selections);
9029 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9030 s.select(new_selections);
9031 });
9032 }
9033 self.select_larger_syntax_node_stack = stack;
9034 }
9035
9036 pub fn select_smaller_syntax_node(
9037 &mut self,
9038 _: &SelectSmallerSyntaxNode,
9039 cx: &mut ViewContext<Self>,
9040 ) {
9041 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9042 if let Some(selections) = stack.pop() {
9043 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9044 s.select(selections.to_vec());
9045 });
9046 }
9047 self.select_larger_syntax_node_stack = stack;
9048 }
9049
9050 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9051 if !EditorSettings::get_global(cx).gutter.runnables {
9052 self.clear_tasks();
9053 return Task::ready(());
9054 }
9055 let project = self.project.clone();
9056 cx.spawn(|this, mut cx| async move {
9057 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9058 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9059 }) else {
9060 return;
9061 };
9062
9063 let Some(project) = project else {
9064 return;
9065 };
9066
9067 let hide_runnables = project
9068 .update(&mut cx, |project, cx| {
9069 // Do not display any test indicators in non-dev server remote projects.
9070 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9071 })
9072 .unwrap_or(true);
9073 if hide_runnables {
9074 return;
9075 }
9076 let new_rows =
9077 cx.background_executor()
9078 .spawn({
9079 let snapshot = display_snapshot.clone();
9080 async move {
9081 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9082 }
9083 })
9084 .await;
9085 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9086
9087 this.update(&mut cx, |this, _| {
9088 this.clear_tasks();
9089 for (key, value) in rows {
9090 this.insert_tasks(key, value);
9091 }
9092 })
9093 .ok();
9094 })
9095 }
9096 fn fetch_runnable_ranges(
9097 snapshot: &DisplaySnapshot,
9098 range: Range<Anchor>,
9099 ) -> Vec<language::RunnableRange> {
9100 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9101 }
9102
9103 fn runnable_rows(
9104 project: Model<Project>,
9105 snapshot: DisplaySnapshot,
9106 runnable_ranges: Vec<RunnableRange>,
9107 mut cx: AsyncWindowContext,
9108 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9109 runnable_ranges
9110 .into_iter()
9111 .filter_map(|mut runnable| {
9112 let tasks = cx
9113 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9114 .ok()?;
9115 if tasks.is_empty() {
9116 return None;
9117 }
9118
9119 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9120
9121 let row = snapshot
9122 .buffer_snapshot
9123 .buffer_line_for_row(MultiBufferRow(point.row))?
9124 .1
9125 .start
9126 .row;
9127
9128 let context_range =
9129 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9130 Some((
9131 (runnable.buffer_id, row),
9132 RunnableTasks {
9133 templates: tasks,
9134 offset: MultiBufferOffset(runnable.run_range.start),
9135 context_range,
9136 column: point.column,
9137 extra_variables: runnable.extra_captures,
9138 },
9139 ))
9140 })
9141 .collect()
9142 }
9143
9144 fn templates_with_tags(
9145 project: &Model<Project>,
9146 runnable: &mut Runnable,
9147 cx: &WindowContext<'_>,
9148 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9149 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9150 let (worktree_id, file) = project
9151 .buffer_for_id(runnable.buffer, cx)
9152 .and_then(|buffer| buffer.read(cx).file())
9153 .map(|file| (file.worktree_id(cx), file.clone()))
9154 .unzip();
9155
9156 (
9157 project.task_store().read(cx).task_inventory().cloned(),
9158 worktree_id,
9159 file,
9160 )
9161 });
9162
9163 let tags = mem::take(&mut runnable.tags);
9164 let mut tags: Vec<_> = tags
9165 .into_iter()
9166 .flat_map(|tag| {
9167 let tag = tag.0.clone();
9168 inventory
9169 .as_ref()
9170 .into_iter()
9171 .flat_map(|inventory| {
9172 inventory.read(cx).list_tasks(
9173 file.clone(),
9174 Some(runnable.language.clone()),
9175 worktree_id,
9176 cx,
9177 )
9178 })
9179 .filter(move |(_, template)| {
9180 template.tags.iter().any(|source_tag| source_tag == &tag)
9181 })
9182 })
9183 .sorted_by_key(|(kind, _)| kind.to_owned())
9184 .collect();
9185 if let Some((leading_tag_source, _)) = tags.first() {
9186 // Strongest source wins; if we have worktree tag binding, prefer that to
9187 // global and language bindings;
9188 // if we have a global binding, prefer that to language binding.
9189 let first_mismatch = tags
9190 .iter()
9191 .position(|(tag_source, _)| tag_source != leading_tag_source);
9192 if let Some(index) = first_mismatch {
9193 tags.truncate(index);
9194 }
9195 }
9196
9197 tags
9198 }
9199
9200 pub fn move_to_enclosing_bracket(
9201 &mut self,
9202 _: &MoveToEnclosingBracket,
9203 cx: &mut ViewContext<Self>,
9204 ) {
9205 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9206 s.move_offsets_with(|snapshot, selection| {
9207 let Some(enclosing_bracket_ranges) =
9208 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9209 else {
9210 return;
9211 };
9212
9213 let mut best_length = usize::MAX;
9214 let mut best_inside = false;
9215 let mut best_in_bracket_range = false;
9216 let mut best_destination = None;
9217 for (open, close) in enclosing_bracket_ranges {
9218 let close = close.to_inclusive();
9219 let length = close.end() - open.start;
9220 let inside = selection.start >= open.end && selection.end <= *close.start();
9221 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9222 || close.contains(&selection.head());
9223
9224 // If best is next to a bracket and current isn't, skip
9225 if !in_bracket_range && best_in_bracket_range {
9226 continue;
9227 }
9228
9229 // Prefer smaller lengths unless best is inside and current isn't
9230 if length > best_length && (best_inside || !inside) {
9231 continue;
9232 }
9233
9234 best_length = length;
9235 best_inside = inside;
9236 best_in_bracket_range = in_bracket_range;
9237 best_destination = Some(
9238 if close.contains(&selection.start) && close.contains(&selection.end) {
9239 if inside {
9240 open.end
9241 } else {
9242 open.start
9243 }
9244 } else if inside {
9245 *close.start()
9246 } else {
9247 *close.end()
9248 },
9249 );
9250 }
9251
9252 if let Some(destination) = best_destination {
9253 selection.collapse_to(destination, SelectionGoal::None);
9254 }
9255 })
9256 });
9257 }
9258
9259 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9260 self.end_selection(cx);
9261 self.selection_history.mode = SelectionHistoryMode::Undoing;
9262 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9263 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9264 self.select_next_state = entry.select_next_state;
9265 self.select_prev_state = entry.select_prev_state;
9266 self.add_selections_state = entry.add_selections_state;
9267 self.request_autoscroll(Autoscroll::newest(), cx);
9268 }
9269 self.selection_history.mode = SelectionHistoryMode::Normal;
9270 }
9271
9272 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9273 self.end_selection(cx);
9274 self.selection_history.mode = SelectionHistoryMode::Redoing;
9275 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9276 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9277 self.select_next_state = entry.select_next_state;
9278 self.select_prev_state = entry.select_prev_state;
9279 self.add_selections_state = entry.add_selections_state;
9280 self.request_autoscroll(Autoscroll::newest(), cx);
9281 }
9282 self.selection_history.mode = SelectionHistoryMode::Normal;
9283 }
9284
9285 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9286 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9287 }
9288
9289 pub fn expand_excerpts_down(
9290 &mut self,
9291 action: &ExpandExcerptsDown,
9292 cx: &mut ViewContext<Self>,
9293 ) {
9294 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9295 }
9296
9297 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9298 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9299 }
9300
9301 pub fn expand_excerpts_for_direction(
9302 &mut self,
9303 lines: u32,
9304 direction: ExpandExcerptDirection,
9305 cx: &mut ViewContext<Self>,
9306 ) {
9307 let selections = self.selections.disjoint_anchors();
9308
9309 let lines = if lines == 0 {
9310 EditorSettings::get_global(cx).expand_excerpt_lines
9311 } else {
9312 lines
9313 };
9314
9315 self.buffer.update(cx, |buffer, cx| {
9316 buffer.expand_excerpts(
9317 selections
9318 .iter()
9319 .map(|selection| selection.head().excerpt_id)
9320 .dedup(),
9321 lines,
9322 direction,
9323 cx,
9324 )
9325 })
9326 }
9327
9328 pub fn expand_excerpt(
9329 &mut self,
9330 excerpt: ExcerptId,
9331 direction: ExpandExcerptDirection,
9332 cx: &mut ViewContext<Self>,
9333 ) {
9334 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9335 self.buffer.update(cx, |buffer, cx| {
9336 buffer.expand_excerpts([excerpt], lines, direction, cx)
9337 })
9338 }
9339
9340 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9341 self.go_to_diagnostic_impl(Direction::Next, cx)
9342 }
9343
9344 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9345 self.go_to_diagnostic_impl(Direction::Prev, cx)
9346 }
9347
9348 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9349 let buffer = self.buffer.read(cx).snapshot(cx);
9350 let selection = self.selections.newest::<usize>(cx);
9351
9352 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9353 if direction == Direction::Next {
9354 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9355 let (group_id, jump_to) = popover.activation_info();
9356 if self.activate_diagnostics(group_id, cx) {
9357 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9358 let mut new_selection = s.newest_anchor().clone();
9359 new_selection.collapse_to(jump_to, SelectionGoal::None);
9360 s.select_anchors(vec![new_selection.clone()]);
9361 });
9362 }
9363 return;
9364 }
9365 }
9366
9367 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9368 active_diagnostics
9369 .primary_range
9370 .to_offset(&buffer)
9371 .to_inclusive()
9372 });
9373 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9374 if active_primary_range.contains(&selection.head()) {
9375 *active_primary_range.start()
9376 } else {
9377 selection.head()
9378 }
9379 } else {
9380 selection.head()
9381 };
9382 let snapshot = self.snapshot(cx);
9383 loop {
9384 let diagnostics = if direction == Direction::Prev {
9385 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9386 } else {
9387 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9388 }
9389 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9390 let group = diagnostics
9391 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9392 // be sorted in a stable way
9393 // skip until we are at current active diagnostic, if it exists
9394 .skip_while(|entry| {
9395 (match direction {
9396 Direction::Prev => entry.range.start >= search_start,
9397 Direction::Next => entry.range.start <= search_start,
9398 }) && self
9399 .active_diagnostics
9400 .as_ref()
9401 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9402 })
9403 .find_map(|entry| {
9404 if entry.diagnostic.is_primary
9405 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9406 && !entry.range.is_empty()
9407 // if we match with the active diagnostic, skip it
9408 && Some(entry.diagnostic.group_id)
9409 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9410 {
9411 Some((entry.range, entry.diagnostic.group_id))
9412 } else {
9413 None
9414 }
9415 });
9416
9417 if let Some((primary_range, group_id)) = group {
9418 if self.activate_diagnostics(group_id, cx) {
9419 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9420 s.select(vec![Selection {
9421 id: selection.id,
9422 start: primary_range.start,
9423 end: primary_range.start,
9424 reversed: false,
9425 goal: SelectionGoal::None,
9426 }]);
9427 });
9428 }
9429 break;
9430 } else {
9431 // Cycle around to the start of the buffer, potentially moving back to the start of
9432 // the currently active diagnostic.
9433 active_primary_range.take();
9434 if direction == Direction::Prev {
9435 if search_start == buffer.len() {
9436 break;
9437 } else {
9438 search_start = buffer.len();
9439 }
9440 } else if search_start == 0 {
9441 break;
9442 } else {
9443 search_start = 0;
9444 }
9445 }
9446 }
9447 }
9448
9449 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9450 let snapshot = self
9451 .display_map
9452 .update(cx, |display_map, cx| display_map.snapshot(cx));
9453 let selection = self.selections.newest::<Point>(cx);
9454 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9455 }
9456
9457 fn go_to_hunk_after_position(
9458 &mut self,
9459 snapshot: &DisplaySnapshot,
9460 position: Point,
9461 cx: &mut ViewContext<'_, Editor>,
9462 ) -> Option<MultiBufferDiffHunk> {
9463 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9464 snapshot,
9465 position,
9466 false,
9467 snapshot
9468 .buffer_snapshot
9469 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9470 cx,
9471 ) {
9472 return Some(hunk);
9473 }
9474
9475 let wrapped_point = Point::zero();
9476 self.go_to_next_hunk_in_direction(
9477 snapshot,
9478 wrapped_point,
9479 true,
9480 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9481 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9482 ),
9483 cx,
9484 )
9485 }
9486
9487 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9488 let snapshot = self
9489 .display_map
9490 .update(cx, |display_map, cx| display_map.snapshot(cx));
9491 let selection = self.selections.newest::<Point>(cx);
9492
9493 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9494 }
9495
9496 fn go_to_hunk_before_position(
9497 &mut self,
9498 snapshot: &DisplaySnapshot,
9499 position: Point,
9500 cx: &mut ViewContext<'_, Editor>,
9501 ) -> Option<MultiBufferDiffHunk> {
9502 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9503 snapshot,
9504 position,
9505 false,
9506 snapshot
9507 .buffer_snapshot
9508 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9509 cx,
9510 ) {
9511 return Some(hunk);
9512 }
9513
9514 let wrapped_point = snapshot.buffer_snapshot.max_point();
9515 self.go_to_next_hunk_in_direction(
9516 snapshot,
9517 wrapped_point,
9518 true,
9519 snapshot
9520 .buffer_snapshot
9521 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9522 cx,
9523 )
9524 }
9525
9526 fn go_to_next_hunk_in_direction(
9527 &mut self,
9528 snapshot: &DisplaySnapshot,
9529 initial_point: Point,
9530 is_wrapped: bool,
9531 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9532 cx: &mut ViewContext<Editor>,
9533 ) -> Option<MultiBufferDiffHunk> {
9534 let display_point = initial_point.to_display_point(snapshot);
9535 let mut hunks = hunks
9536 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9537 .filter(|(display_hunk, _)| {
9538 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9539 })
9540 .dedup();
9541
9542 if let Some((display_hunk, hunk)) = hunks.next() {
9543 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9544 let row = display_hunk.start_display_row();
9545 let point = DisplayPoint::new(row, 0);
9546 s.select_display_ranges([point..point]);
9547 });
9548
9549 Some(hunk)
9550 } else {
9551 None
9552 }
9553 }
9554
9555 pub fn go_to_definition(
9556 &mut self,
9557 _: &GoToDefinition,
9558 cx: &mut ViewContext<Self>,
9559 ) -> Task<Result<Navigated>> {
9560 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9561 cx.spawn(|editor, mut cx| async move {
9562 if definition.await? == Navigated::Yes {
9563 return Ok(Navigated::Yes);
9564 }
9565 match editor.update(&mut cx, |editor, cx| {
9566 editor.find_all_references(&FindAllReferences, cx)
9567 })? {
9568 Some(references) => references.await,
9569 None => Ok(Navigated::No),
9570 }
9571 })
9572 }
9573
9574 pub fn go_to_declaration(
9575 &mut self,
9576 _: &GoToDeclaration,
9577 cx: &mut ViewContext<Self>,
9578 ) -> Task<Result<Navigated>> {
9579 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9580 }
9581
9582 pub fn go_to_declaration_split(
9583 &mut self,
9584 _: &GoToDeclaration,
9585 cx: &mut ViewContext<Self>,
9586 ) -> Task<Result<Navigated>> {
9587 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9588 }
9589
9590 pub fn go_to_implementation(
9591 &mut self,
9592 _: &GoToImplementation,
9593 cx: &mut ViewContext<Self>,
9594 ) -> Task<Result<Navigated>> {
9595 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9596 }
9597
9598 pub fn go_to_implementation_split(
9599 &mut self,
9600 _: &GoToImplementationSplit,
9601 cx: &mut ViewContext<Self>,
9602 ) -> Task<Result<Navigated>> {
9603 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9604 }
9605
9606 pub fn go_to_type_definition(
9607 &mut self,
9608 _: &GoToTypeDefinition,
9609 cx: &mut ViewContext<Self>,
9610 ) -> Task<Result<Navigated>> {
9611 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9612 }
9613
9614 pub fn go_to_definition_split(
9615 &mut self,
9616 _: &GoToDefinitionSplit,
9617 cx: &mut ViewContext<Self>,
9618 ) -> Task<Result<Navigated>> {
9619 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9620 }
9621
9622 pub fn go_to_type_definition_split(
9623 &mut self,
9624 _: &GoToTypeDefinitionSplit,
9625 cx: &mut ViewContext<Self>,
9626 ) -> Task<Result<Navigated>> {
9627 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9628 }
9629
9630 fn go_to_definition_of_kind(
9631 &mut self,
9632 kind: GotoDefinitionKind,
9633 split: bool,
9634 cx: &mut ViewContext<Self>,
9635 ) -> Task<Result<Navigated>> {
9636 let Some(provider) = self.semantics_provider.clone() else {
9637 return Task::ready(Ok(Navigated::No));
9638 };
9639 let buffer = self.buffer.read(cx);
9640 let head = self.selections.newest::<usize>(cx).head();
9641 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9642 text_anchor
9643 } else {
9644 return Task::ready(Ok(Navigated::No));
9645 };
9646
9647 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9648 return Task::ready(Ok(Navigated::No));
9649 };
9650
9651 cx.spawn(|editor, mut cx| async move {
9652 let definitions = definitions.await?;
9653 let navigated = editor
9654 .update(&mut cx, |editor, cx| {
9655 editor.navigate_to_hover_links(
9656 Some(kind),
9657 definitions
9658 .into_iter()
9659 .filter(|location| {
9660 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9661 })
9662 .map(HoverLink::Text)
9663 .collect::<Vec<_>>(),
9664 split,
9665 cx,
9666 )
9667 })?
9668 .await?;
9669 anyhow::Ok(navigated)
9670 })
9671 }
9672
9673 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9674 let position = self.selections.newest_anchor().head();
9675 let Some((buffer, buffer_position)) =
9676 self.buffer.read(cx).text_anchor_for_position(position, cx)
9677 else {
9678 return;
9679 };
9680
9681 cx.spawn(|editor, mut cx| async move {
9682 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9683 editor.update(&mut cx, |_, cx| {
9684 cx.open_url(&url);
9685 })
9686 } else {
9687 Ok(())
9688 }
9689 })
9690 .detach();
9691 }
9692
9693 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9694 let Some(workspace) = self.workspace() else {
9695 return;
9696 };
9697
9698 let position = self.selections.newest_anchor().head();
9699
9700 let Some((buffer, buffer_position)) =
9701 self.buffer.read(cx).text_anchor_for_position(position, cx)
9702 else {
9703 return;
9704 };
9705
9706 let project = self.project.clone();
9707
9708 cx.spawn(|_, mut cx| async move {
9709 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9710
9711 if let Some((_, path)) = result {
9712 workspace
9713 .update(&mut cx, |workspace, cx| {
9714 workspace.open_resolved_path(path, cx)
9715 })?
9716 .await?;
9717 }
9718 anyhow::Ok(())
9719 })
9720 .detach();
9721 }
9722
9723 pub(crate) fn navigate_to_hover_links(
9724 &mut self,
9725 kind: Option<GotoDefinitionKind>,
9726 mut definitions: Vec<HoverLink>,
9727 split: bool,
9728 cx: &mut ViewContext<Editor>,
9729 ) -> Task<Result<Navigated>> {
9730 // If there is one definition, just open it directly
9731 if definitions.len() == 1 {
9732 let definition = definitions.pop().unwrap();
9733
9734 enum TargetTaskResult {
9735 Location(Option<Location>),
9736 AlreadyNavigated,
9737 }
9738
9739 let target_task = match definition {
9740 HoverLink::Text(link) => {
9741 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9742 }
9743 HoverLink::InlayHint(lsp_location, server_id) => {
9744 let computation = self.compute_target_location(lsp_location, server_id, cx);
9745 cx.background_executor().spawn(async move {
9746 let location = computation.await?;
9747 Ok(TargetTaskResult::Location(location))
9748 })
9749 }
9750 HoverLink::Url(url) => {
9751 cx.open_url(&url);
9752 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9753 }
9754 HoverLink::File(path) => {
9755 if let Some(workspace) = self.workspace() {
9756 cx.spawn(|_, mut cx| async move {
9757 workspace
9758 .update(&mut cx, |workspace, cx| {
9759 workspace.open_resolved_path(path, cx)
9760 })?
9761 .await
9762 .map(|_| TargetTaskResult::AlreadyNavigated)
9763 })
9764 } else {
9765 Task::ready(Ok(TargetTaskResult::Location(None)))
9766 }
9767 }
9768 };
9769 cx.spawn(|editor, mut cx| async move {
9770 let target = match target_task.await.context("target resolution task")? {
9771 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9772 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9773 TargetTaskResult::Location(Some(target)) => target,
9774 };
9775
9776 editor.update(&mut cx, |editor, cx| {
9777 let Some(workspace) = editor.workspace() else {
9778 return Navigated::No;
9779 };
9780 let pane = workspace.read(cx).active_pane().clone();
9781
9782 let range = target.range.to_offset(target.buffer.read(cx));
9783 let range = editor.range_for_match(&range);
9784
9785 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9786 let buffer = target.buffer.read(cx);
9787 let range = check_multiline_range(buffer, range);
9788 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9789 s.select_ranges([range]);
9790 });
9791 } else {
9792 cx.window_context().defer(move |cx| {
9793 let target_editor: View<Self> =
9794 workspace.update(cx, |workspace, cx| {
9795 let pane = if split {
9796 workspace.adjacent_pane(cx)
9797 } else {
9798 workspace.active_pane().clone()
9799 };
9800
9801 workspace.open_project_item(
9802 pane,
9803 target.buffer.clone(),
9804 true,
9805 true,
9806 cx,
9807 )
9808 });
9809 target_editor.update(cx, |target_editor, cx| {
9810 // When selecting a definition in a different buffer, disable the nav history
9811 // to avoid creating a history entry at the previous cursor location.
9812 pane.update(cx, |pane, _| pane.disable_history());
9813 let buffer = target.buffer.read(cx);
9814 let range = check_multiline_range(buffer, range);
9815 target_editor.change_selections(
9816 Some(Autoscroll::focused()),
9817 cx,
9818 |s| {
9819 s.select_ranges([range]);
9820 },
9821 );
9822 pane.update(cx, |pane, _| pane.enable_history());
9823 });
9824 });
9825 }
9826 Navigated::Yes
9827 })
9828 })
9829 } else if !definitions.is_empty() {
9830 cx.spawn(|editor, mut cx| async move {
9831 let (title, location_tasks, workspace) = editor
9832 .update(&mut cx, |editor, cx| {
9833 let tab_kind = match kind {
9834 Some(GotoDefinitionKind::Implementation) => "Implementations",
9835 _ => "Definitions",
9836 };
9837 let title = definitions
9838 .iter()
9839 .find_map(|definition| match definition {
9840 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9841 let buffer = origin.buffer.read(cx);
9842 format!(
9843 "{} for {}",
9844 tab_kind,
9845 buffer
9846 .text_for_range(origin.range.clone())
9847 .collect::<String>()
9848 )
9849 }),
9850 HoverLink::InlayHint(_, _) => None,
9851 HoverLink::Url(_) => None,
9852 HoverLink::File(_) => None,
9853 })
9854 .unwrap_or(tab_kind.to_string());
9855 let location_tasks = definitions
9856 .into_iter()
9857 .map(|definition| match definition {
9858 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9859 HoverLink::InlayHint(lsp_location, server_id) => {
9860 editor.compute_target_location(lsp_location, server_id, cx)
9861 }
9862 HoverLink::Url(_) => Task::ready(Ok(None)),
9863 HoverLink::File(_) => Task::ready(Ok(None)),
9864 })
9865 .collect::<Vec<_>>();
9866 (title, location_tasks, editor.workspace().clone())
9867 })
9868 .context("location tasks preparation")?;
9869
9870 let locations = future::join_all(location_tasks)
9871 .await
9872 .into_iter()
9873 .filter_map(|location| location.transpose())
9874 .collect::<Result<_>>()
9875 .context("location tasks")?;
9876
9877 let Some(workspace) = workspace else {
9878 return Ok(Navigated::No);
9879 };
9880 let opened = workspace
9881 .update(&mut cx, |workspace, cx| {
9882 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9883 })
9884 .ok();
9885
9886 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9887 })
9888 } else {
9889 Task::ready(Ok(Navigated::No))
9890 }
9891 }
9892
9893 fn compute_target_location(
9894 &self,
9895 lsp_location: lsp::Location,
9896 server_id: LanguageServerId,
9897 cx: &mut ViewContext<Self>,
9898 ) -> Task<anyhow::Result<Option<Location>>> {
9899 let Some(project) = self.project.clone() else {
9900 return Task::Ready(Some(Ok(None)));
9901 };
9902
9903 cx.spawn(move |editor, mut cx| async move {
9904 let location_task = editor.update(&mut cx, |_, cx| {
9905 project.update(cx, |project, cx| {
9906 let language_server_name = project
9907 .language_server_statuses(cx)
9908 .find(|(id, _)| server_id == *id)
9909 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9910 language_server_name.map(|language_server_name| {
9911 project.open_local_buffer_via_lsp(
9912 lsp_location.uri.clone(),
9913 server_id,
9914 language_server_name,
9915 cx,
9916 )
9917 })
9918 })
9919 })?;
9920 let location = match location_task {
9921 Some(task) => Some({
9922 let target_buffer_handle = task.await.context("open local buffer")?;
9923 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9924 let target_start = target_buffer
9925 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9926 let target_end = target_buffer
9927 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9928 target_buffer.anchor_after(target_start)
9929 ..target_buffer.anchor_before(target_end)
9930 })?;
9931 Location {
9932 buffer: target_buffer_handle,
9933 range,
9934 }
9935 }),
9936 None => None,
9937 };
9938 Ok(location)
9939 })
9940 }
9941
9942 pub fn find_all_references(
9943 &mut self,
9944 _: &FindAllReferences,
9945 cx: &mut ViewContext<Self>,
9946 ) -> Option<Task<Result<Navigated>>> {
9947 let multi_buffer = self.buffer.read(cx);
9948 let selection = self.selections.newest::<usize>(cx);
9949 let head = selection.head();
9950
9951 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9952 let head_anchor = multi_buffer_snapshot.anchor_at(
9953 head,
9954 if head < selection.tail() {
9955 Bias::Right
9956 } else {
9957 Bias::Left
9958 },
9959 );
9960
9961 match self
9962 .find_all_references_task_sources
9963 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9964 {
9965 Ok(_) => {
9966 log::info!(
9967 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9968 );
9969 return None;
9970 }
9971 Err(i) => {
9972 self.find_all_references_task_sources.insert(i, head_anchor);
9973 }
9974 }
9975
9976 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9977 let workspace = self.workspace()?;
9978 let project = workspace.read(cx).project().clone();
9979 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9980 Some(cx.spawn(|editor, mut cx| async move {
9981 let _cleanup = defer({
9982 let mut cx = cx.clone();
9983 move || {
9984 let _ = editor.update(&mut cx, |editor, _| {
9985 if let Ok(i) =
9986 editor
9987 .find_all_references_task_sources
9988 .binary_search_by(|anchor| {
9989 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9990 })
9991 {
9992 editor.find_all_references_task_sources.remove(i);
9993 }
9994 });
9995 }
9996 });
9997
9998 let locations = references.await?;
9999 if locations.is_empty() {
10000 return anyhow::Ok(Navigated::No);
10001 }
10002
10003 workspace.update(&mut cx, |workspace, cx| {
10004 let title = locations
10005 .first()
10006 .as_ref()
10007 .map(|location| {
10008 let buffer = location.buffer.read(cx);
10009 format!(
10010 "References to `{}`",
10011 buffer
10012 .text_for_range(location.range.clone())
10013 .collect::<String>()
10014 )
10015 })
10016 .unwrap();
10017 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10018 Navigated::Yes
10019 })
10020 }))
10021 }
10022
10023 /// Opens a multibuffer with the given project locations in it
10024 pub fn open_locations_in_multibuffer(
10025 workspace: &mut Workspace,
10026 mut locations: Vec<Location>,
10027 title: String,
10028 split: bool,
10029 cx: &mut ViewContext<Workspace>,
10030 ) {
10031 // If there are multiple definitions, open them in a multibuffer
10032 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10033 let mut locations = locations.into_iter().peekable();
10034 let mut ranges_to_highlight = Vec::new();
10035 let capability = workspace.project().read(cx).capability();
10036
10037 let excerpt_buffer = cx.new_model(|cx| {
10038 let mut multibuffer = MultiBuffer::new(capability);
10039 while let Some(location) = locations.next() {
10040 let buffer = location.buffer.read(cx);
10041 let mut ranges_for_buffer = Vec::new();
10042 let range = location.range.to_offset(buffer);
10043 ranges_for_buffer.push(range.clone());
10044
10045 while let Some(next_location) = locations.peek() {
10046 if next_location.buffer == location.buffer {
10047 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10048 locations.next();
10049 } else {
10050 break;
10051 }
10052 }
10053
10054 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10055 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10056 location.buffer.clone(),
10057 ranges_for_buffer,
10058 DEFAULT_MULTIBUFFER_CONTEXT,
10059 cx,
10060 ))
10061 }
10062
10063 multibuffer.with_title(title)
10064 });
10065
10066 let editor = cx.new_view(|cx| {
10067 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10068 });
10069 editor.update(cx, |editor, cx| {
10070 if let Some(first_range) = ranges_to_highlight.first() {
10071 editor.change_selections(None, cx, |selections| {
10072 selections.clear_disjoint();
10073 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10074 });
10075 }
10076 editor.highlight_background::<Self>(
10077 &ranges_to_highlight,
10078 |theme| theme.editor_highlighted_line_background,
10079 cx,
10080 );
10081 });
10082
10083 let item = Box::new(editor);
10084 let item_id = item.item_id();
10085
10086 if split {
10087 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10088 } else {
10089 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10090 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10091 pane.close_current_preview_item(cx)
10092 } else {
10093 None
10094 }
10095 });
10096 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10097 }
10098 workspace.active_pane().update(cx, |pane, cx| {
10099 pane.set_preview_item_id(Some(item_id), cx);
10100 });
10101 }
10102
10103 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10104 use language::ToOffset as _;
10105
10106 let provider = self.semantics_provider.clone()?;
10107 let selection = self.selections.newest_anchor().clone();
10108 let (cursor_buffer, cursor_buffer_position) = self
10109 .buffer
10110 .read(cx)
10111 .text_anchor_for_position(selection.head(), cx)?;
10112 let (tail_buffer, cursor_buffer_position_end) = self
10113 .buffer
10114 .read(cx)
10115 .text_anchor_for_position(selection.tail(), cx)?;
10116 if tail_buffer != cursor_buffer {
10117 return None;
10118 }
10119
10120 let snapshot = cursor_buffer.read(cx).snapshot();
10121 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10122 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10123 let prepare_rename = provider
10124 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10125 .unwrap_or_else(|| Task::ready(Ok(None)));
10126 drop(snapshot);
10127
10128 Some(cx.spawn(|this, mut cx| async move {
10129 let rename_range = if let Some(range) = prepare_rename.await? {
10130 Some(range)
10131 } else {
10132 this.update(&mut cx, |this, cx| {
10133 let buffer = this.buffer.read(cx).snapshot(cx);
10134 let mut buffer_highlights = this
10135 .document_highlights_for_position(selection.head(), &buffer)
10136 .filter(|highlight| {
10137 highlight.start.excerpt_id == selection.head().excerpt_id
10138 && highlight.end.excerpt_id == selection.head().excerpt_id
10139 });
10140 buffer_highlights
10141 .next()
10142 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10143 })?
10144 };
10145 if let Some(rename_range) = rename_range {
10146 this.update(&mut cx, |this, cx| {
10147 let snapshot = cursor_buffer.read(cx).snapshot();
10148 let rename_buffer_range = rename_range.to_offset(&snapshot);
10149 let cursor_offset_in_rename_range =
10150 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10151 let cursor_offset_in_rename_range_end =
10152 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10153
10154 this.take_rename(false, cx);
10155 let buffer = this.buffer.read(cx).read(cx);
10156 let cursor_offset = selection.head().to_offset(&buffer);
10157 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10158 let rename_end = rename_start + rename_buffer_range.len();
10159 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10160 let mut old_highlight_id = None;
10161 let old_name: Arc<str> = buffer
10162 .chunks(rename_start..rename_end, true)
10163 .map(|chunk| {
10164 if old_highlight_id.is_none() {
10165 old_highlight_id = chunk.syntax_highlight_id;
10166 }
10167 chunk.text
10168 })
10169 .collect::<String>()
10170 .into();
10171
10172 drop(buffer);
10173
10174 // Position the selection in the rename editor so that it matches the current selection.
10175 this.show_local_selections = false;
10176 let rename_editor = cx.new_view(|cx| {
10177 let mut editor = Editor::single_line(cx);
10178 editor.buffer.update(cx, |buffer, cx| {
10179 buffer.edit([(0..0, old_name.clone())], None, cx)
10180 });
10181 let rename_selection_range = match cursor_offset_in_rename_range
10182 .cmp(&cursor_offset_in_rename_range_end)
10183 {
10184 Ordering::Equal => {
10185 editor.select_all(&SelectAll, cx);
10186 return editor;
10187 }
10188 Ordering::Less => {
10189 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10190 }
10191 Ordering::Greater => {
10192 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10193 }
10194 };
10195 if rename_selection_range.end > old_name.len() {
10196 editor.select_all(&SelectAll, cx);
10197 } else {
10198 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10199 s.select_ranges([rename_selection_range]);
10200 });
10201 }
10202 editor
10203 });
10204 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10205 if e == &EditorEvent::Focused {
10206 cx.emit(EditorEvent::FocusedIn)
10207 }
10208 })
10209 .detach();
10210
10211 let write_highlights =
10212 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10213 let read_highlights =
10214 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10215 let ranges = write_highlights
10216 .iter()
10217 .flat_map(|(_, ranges)| ranges.iter())
10218 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10219 .cloned()
10220 .collect();
10221
10222 this.highlight_text::<Rename>(
10223 ranges,
10224 HighlightStyle {
10225 fade_out: Some(0.6),
10226 ..Default::default()
10227 },
10228 cx,
10229 );
10230 let rename_focus_handle = rename_editor.focus_handle(cx);
10231 cx.focus(&rename_focus_handle);
10232 let block_id = this.insert_blocks(
10233 [BlockProperties {
10234 style: BlockStyle::Flex,
10235 position: range.start,
10236 height: 1,
10237 render: Box::new({
10238 let rename_editor = rename_editor.clone();
10239 move |cx: &mut BlockContext| {
10240 let mut text_style = cx.editor_style.text.clone();
10241 if let Some(highlight_style) = old_highlight_id
10242 .and_then(|h| h.style(&cx.editor_style.syntax))
10243 {
10244 text_style = text_style.highlight(highlight_style);
10245 }
10246 div()
10247 .pl(cx.anchor_x)
10248 .child(EditorElement::new(
10249 &rename_editor,
10250 EditorStyle {
10251 background: cx.theme().system().transparent,
10252 local_player: cx.editor_style.local_player,
10253 text: text_style,
10254 scrollbar_width: cx.editor_style.scrollbar_width,
10255 syntax: cx.editor_style.syntax.clone(),
10256 status: cx.editor_style.status.clone(),
10257 inlay_hints_style: HighlightStyle {
10258 font_weight: Some(FontWeight::BOLD),
10259 ..make_inlay_hints_style(cx)
10260 },
10261 suggestions_style: HighlightStyle {
10262 color: Some(cx.theme().status().predictive),
10263 ..HighlightStyle::default()
10264 },
10265 ..EditorStyle::default()
10266 },
10267 ))
10268 .into_any_element()
10269 }
10270 }),
10271 disposition: BlockDisposition::Below,
10272 priority: 0,
10273 }],
10274 Some(Autoscroll::fit()),
10275 cx,
10276 )[0];
10277 this.pending_rename = Some(RenameState {
10278 range,
10279 old_name,
10280 editor: rename_editor,
10281 block_id,
10282 });
10283 })?;
10284 }
10285
10286 Ok(())
10287 }))
10288 }
10289
10290 pub fn confirm_rename(
10291 &mut self,
10292 _: &ConfirmRename,
10293 cx: &mut ViewContext<Self>,
10294 ) -> Option<Task<Result<()>>> {
10295 let rename = self.take_rename(false, cx)?;
10296 let workspace = self.workspace()?.downgrade();
10297 let (buffer, start) = self
10298 .buffer
10299 .read(cx)
10300 .text_anchor_for_position(rename.range.start, cx)?;
10301 let (end_buffer, _) = self
10302 .buffer
10303 .read(cx)
10304 .text_anchor_for_position(rename.range.end, cx)?;
10305 if buffer != end_buffer {
10306 return None;
10307 }
10308
10309 let old_name = rename.old_name;
10310 let new_name = rename.editor.read(cx).text(cx);
10311
10312 let rename = self.semantics_provider.as_ref()?.perform_rename(
10313 &buffer,
10314 start,
10315 new_name.clone(),
10316 cx,
10317 )?;
10318
10319 Some(cx.spawn(|editor, mut cx| async move {
10320 let project_transaction = rename.await?;
10321 Self::open_project_transaction(
10322 &editor,
10323 workspace,
10324 project_transaction,
10325 format!("Rename: {} → {}", old_name, new_name),
10326 cx.clone(),
10327 )
10328 .await?;
10329
10330 editor.update(&mut cx, |editor, cx| {
10331 editor.refresh_document_highlights(cx);
10332 })?;
10333 Ok(())
10334 }))
10335 }
10336
10337 fn take_rename(
10338 &mut self,
10339 moving_cursor: bool,
10340 cx: &mut ViewContext<Self>,
10341 ) -> Option<RenameState> {
10342 let rename = self.pending_rename.take()?;
10343 if rename.editor.focus_handle(cx).is_focused(cx) {
10344 cx.focus(&self.focus_handle);
10345 }
10346
10347 self.remove_blocks(
10348 [rename.block_id].into_iter().collect(),
10349 Some(Autoscroll::fit()),
10350 cx,
10351 );
10352 self.clear_highlights::<Rename>(cx);
10353 self.show_local_selections = true;
10354
10355 if moving_cursor {
10356 let rename_editor = rename.editor.read(cx);
10357 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10358
10359 // Update the selection to match the position of the selection inside
10360 // the rename editor.
10361 let snapshot = self.buffer.read(cx).read(cx);
10362 let rename_range = rename.range.to_offset(&snapshot);
10363 let cursor_in_editor = snapshot
10364 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10365 .min(rename_range.end);
10366 drop(snapshot);
10367
10368 self.change_selections(None, cx, |s| {
10369 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10370 });
10371 } else {
10372 self.refresh_document_highlights(cx);
10373 }
10374
10375 Some(rename)
10376 }
10377
10378 pub fn pending_rename(&self) -> Option<&RenameState> {
10379 self.pending_rename.as_ref()
10380 }
10381
10382 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10383 let project = match &self.project {
10384 Some(project) => project.clone(),
10385 None => return None,
10386 };
10387
10388 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10389 }
10390
10391 fn format_selections(
10392 &mut self,
10393 _: &FormatSelections,
10394 cx: &mut ViewContext<Self>,
10395 ) -> Option<Task<Result<()>>> {
10396 let project = match &self.project {
10397 Some(project) => project.clone(),
10398 None => return None,
10399 };
10400
10401 let selections = self
10402 .selections
10403 .all_adjusted(cx)
10404 .into_iter()
10405 .filter(|s| !s.is_empty())
10406 .collect_vec();
10407
10408 Some(self.perform_format(
10409 project,
10410 FormatTrigger::Manual,
10411 FormatTarget::Ranges(selections),
10412 cx,
10413 ))
10414 }
10415
10416 fn perform_format(
10417 &mut self,
10418 project: Model<Project>,
10419 trigger: FormatTrigger,
10420 target: FormatTarget,
10421 cx: &mut ViewContext<Self>,
10422 ) -> Task<Result<()>> {
10423 let buffer = self.buffer().clone();
10424 let mut buffers = buffer.read(cx).all_buffers();
10425 if trigger == FormatTrigger::Save {
10426 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10427 }
10428
10429 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10430 let format = project.update(cx, |project, cx| {
10431 project.format(buffers, true, trigger, target, cx)
10432 });
10433
10434 cx.spawn(|_, mut cx| async move {
10435 let transaction = futures::select_biased! {
10436 () = timeout => {
10437 log::warn!("timed out waiting for formatting");
10438 None
10439 }
10440 transaction = format.log_err().fuse() => transaction,
10441 };
10442
10443 buffer
10444 .update(&mut cx, |buffer, cx| {
10445 if let Some(transaction) = transaction {
10446 if !buffer.is_singleton() {
10447 buffer.push_transaction(&transaction.0, cx);
10448 }
10449 }
10450
10451 cx.notify();
10452 })
10453 .ok();
10454
10455 Ok(())
10456 })
10457 }
10458
10459 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10460 if let Some(project) = self.project.clone() {
10461 self.buffer.update(cx, |multi_buffer, cx| {
10462 project.update(cx, |project, cx| {
10463 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10464 });
10465 })
10466 }
10467 }
10468
10469 fn cancel_language_server_work(
10470 &mut self,
10471 _: &CancelLanguageServerWork,
10472 cx: &mut ViewContext<Self>,
10473 ) {
10474 if let Some(project) = self.project.clone() {
10475 self.buffer.update(cx, |multi_buffer, cx| {
10476 project.update(cx, |project, cx| {
10477 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10478 });
10479 })
10480 }
10481 }
10482
10483 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10484 cx.show_character_palette();
10485 }
10486
10487 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10488 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10489 let buffer = self.buffer.read(cx).snapshot(cx);
10490 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10491 let is_valid = buffer
10492 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10493 .any(|entry| {
10494 entry.diagnostic.is_primary
10495 && !entry.range.is_empty()
10496 && entry.range.start == primary_range_start
10497 && entry.diagnostic.message == active_diagnostics.primary_message
10498 });
10499
10500 if is_valid != active_diagnostics.is_valid {
10501 active_diagnostics.is_valid = is_valid;
10502 let mut new_styles = HashMap::default();
10503 for (block_id, diagnostic) in &active_diagnostics.blocks {
10504 new_styles.insert(
10505 *block_id,
10506 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10507 );
10508 }
10509 self.display_map.update(cx, |display_map, _cx| {
10510 display_map.replace_blocks(new_styles)
10511 });
10512 }
10513 }
10514 }
10515
10516 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10517 self.dismiss_diagnostics(cx);
10518 let snapshot = self.snapshot(cx);
10519 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10520 let buffer = self.buffer.read(cx).snapshot(cx);
10521
10522 let mut primary_range = None;
10523 let mut primary_message = None;
10524 let mut group_end = Point::zero();
10525 let diagnostic_group = buffer
10526 .diagnostic_group::<MultiBufferPoint>(group_id)
10527 .filter_map(|entry| {
10528 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10529 && (entry.range.start.row == entry.range.end.row
10530 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10531 {
10532 return None;
10533 }
10534 if entry.range.end > group_end {
10535 group_end = entry.range.end;
10536 }
10537 if entry.diagnostic.is_primary {
10538 primary_range = Some(entry.range.clone());
10539 primary_message = Some(entry.diagnostic.message.clone());
10540 }
10541 Some(entry)
10542 })
10543 .collect::<Vec<_>>();
10544 let primary_range = primary_range?;
10545 let primary_message = primary_message?;
10546 let primary_range =
10547 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10548
10549 let blocks = display_map
10550 .insert_blocks(
10551 diagnostic_group.iter().map(|entry| {
10552 let diagnostic = entry.diagnostic.clone();
10553 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10554 BlockProperties {
10555 style: BlockStyle::Fixed,
10556 position: buffer.anchor_after(entry.range.start),
10557 height: message_height,
10558 render: diagnostic_block_renderer(diagnostic, None, true, true),
10559 disposition: BlockDisposition::Below,
10560 priority: 0,
10561 }
10562 }),
10563 cx,
10564 )
10565 .into_iter()
10566 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10567 .collect();
10568
10569 Some(ActiveDiagnosticGroup {
10570 primary_range,
10571 primary_message,
10572 group_id,
10573 blocks,
10574 is_valid: true,
10575 })
10576 });
10577 self.active_diagnostics.is_some()
10578 }
10579
10580 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10581 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10582 self.display_map.update(cx, |display_map, cx| {
10583 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10584 });
10585 cx.notify();
10586 }
10587 }
10588
10589 pub fn set_selections_from_remote(
10590 &mut self,
10591 selections: Vec<Selection<Anchor>>,
10592 pending_selection: Option<Selection<Anchor>>,
10593 cx: &mut ViewContext<Self>,
10594 ) {
10595 let old_cursor_position = self.selections.newest_anchor().head();
10596 self.selections.change_with(cx, |s| {
10597 s.select_anchors(selections);
10598 if let Some(pending_selection) = pending_selection {
10599 s.set_pending(pending_selection, SelectMode::Character);
10600 } else {
10601 s.clear_pending();
10602 }
10603 });
10604 self.selections_did_change(false, &old_cursor_position, true, cx);
10605 }
10606
10607 fn push_to_selection_history(&mut self) {
10608 self.selection_history.push(SelectionHistoryEntry {
10609 selections: self.selections.disjoint_anchors(),
10610 select_next_state: self.select_next_state.clone(),
10611 select_prev_state: self.select_prev_state.clone(),
10612 add_selections_state: self.add_selections_state.clone(),
10613 });
10614 }
10615
10616 pub fn transact(
10617 &mut self,
10618 cx: &mut ViewContext<Self>,
10619 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10620 ) -> Option<TransactionId> {
10621 self.start_transaction_at(Instant::now(), cx);
10622 update(self, cx);
10623 self.end_transaction_at(Instant::now(), cx)
10624 }
10625
10626 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10627 self.end_selection(cx);
10628 if let Some(tx_id) = self
10629 .buffer
10630 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10631 {
10632 self.selection_history
10633 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10634 cx.emit(EditorEvent::TransactionBegun {
10635 transaction_id: tx_id,
10636 })
10637 }
10638 }
10639
10640 fn end_transaction_at(
10641 &mut self,
10642 now: Instant,
10643 cx: &mut ViewContext<Self>,
10644 ) -> Option<TransactionId> {
10645 if let Some(transaction_id) = self
10646 .buffer
10647 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10648 {
10649 if let Some((_, end_selections)) =
10650 self.selection_history.transaction_mut(transaction_id)
10651 {
10652 *end_selections = Some(self.selections.disjoint_anchors());
10653 } else {
10654 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10655 }
10656
10657 cx.emit(EditorEvent::Edited { transaction_id });
10658 Some(transaction_id)
10659 } else {
10660 None
10661 }
10662 }
10663
10664 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10665 let selection = self.selections.newest::<Point>(cx);
10666
10667 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10668 let range = if selection.is_empty() {
10669 let point = selection.head().to_display_point(&display_map);
10670 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10671 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10672 .to_point(&display_map);
10673 start..end
10674 } else {
10675 selection.range()
10676 };
10677 if display_map.folds_in_range(range).next().is_some() {
10678 self.unfold_lines(&Default::default(), cx)
10679 } else {
10680 self.fold(&Default::default(), cx)
10681 }
10682 }
10683
10684 pub fn toggle_fold_recursive(
10685 &mut self,
10686 _: &actions::ToggleFoldRecursive,
10687 cx: &mut ViewContext<Self>,
10688 ) {
10689 let selection = self.selections.newest::<Point>(cx);
10690
10691 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10692 let range = if selection.is_empty() {
10693 let point = selection.head().to_display_point(&display_map);
10694 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10695 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10696 .to_point(&display_map);
10697 start..end
10698 } else {
10699 selection.range()
10700 };
10701 if display_map.folds_in_range(range).next().is_some() {
10702 self.unfold_recursive(&Default::default(), cx)
10703 } else {
10704 self.fold_recursive(&Default::default(), cx)
10705 }
10706 }
10707
10708 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10709 let mut fold_ranges = Vec::new();
10710 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10711 let selections = self.selections.all_adjusted(cx);
10712
10713 for selection in selections {
10714 let range = selection.range().sorted();
10715 let buffer_start_row = range.start.row;
10716
10717 if range.start.row != range.end.row {
10718 let mut found = false;
10719 let mut row = range.start.row;
10720 while row <= range.end.row {
10721 if let Some((foldable_range, fold_text)) =
10722 { display_map.foldable_range(MultiBufferRow(row)) }
10723 {
10724 found = true;
10725 row = foldable_range.end.row + 1;
10726 fold_ranges.push((foldable_range, fold_text));
10727 } else {
10728 row += 1
10729 }
10730 }
10731 if found {
10732 continue;
10733 }
10734 }
10735
10736 for row in (0..=range.start.row).rev() {
10737 if let Some((foldable_range, fold_text)) =
10738 display_map.foldable_range(MultiBufferRow(row))
10739 {
10740 if foldable_range.end.row >= buffer_start_row {
10741 fold_ranges.push((foldable_range, fold_text));
10742 if row <= range.start.row {
10743 break;
10744 }
10745 }
10746 }
10747 }
10748 }
10749
10750 self.fold_ranges(fold_ranges, true, cx);
10751 }
10752
10753 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10754 let mut fold_ranges = Vec::new();
10755 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10756
10757 for row in 0..display_map.max_buffer_row().0 {
10758 if let Some((foldable_range, fold_text)) =
10759 display_map.foldable_range(MultiBufferRow(row))
10760 {
10761 fold_ranges.push((foldable_range, fold_text));
10762 }
10763 }
10764
10765 self.fold_ranges(fold_ranges, true, cx);
10766 }
10767
10768 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10769 let mut fold_ranges = Vec::new();
10770 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10771 let selections = self.selections.all_adjusted(cx);
10772
10773 for selection in selections {
10774 let range = selection.range().sorted();
10775 let buffer_start_row = range.start.row;
10776
10777 if range.start.row != range.end.row {
10778 let mut found = false;
10779 for row in range.start.row..=range.end.row {
10780 if let Some((foldable_range, fold_text)) =
10781 { display_map.foldable_range(MultiBufferRow(row)) }
10782 {
10783 found = true;
10784 fold_ranges.push((foldable_range, fold_text));
10785 }
10786 }
10787 if found {
10788 continue;
10789 }
10790 }
10791
10792 for row in (0..=range.start.row).rev() {
10793 if let Some((foldable_range, fold_text)) =
10794 display_map.foldable_range(MultiBufferRow(row))
10795 {
10796 if foldable_range.end.row >= buffer_start_row {
10797 fold_ranges.push((foldable_range, fold_text));
10798 } else {
10799 break;
10800 }
10801 }
10802 }
10803 }
10804
10805 self.fold_ranges(fold_ranges, true, cx);
10806 }
10807
10808 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10809 let buffer_row = fold_at.buffer_row;
10810 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10811
10812 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10813 let autoscroll = self
10814 .selections
10815 .all::<Point>(cx)
10816 .iter()
10817 .any(|selection| fold_range.overlaps(&selection.range()));
10818
10819 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10820 }
10821 }
10822
10823 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10824 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10825 let buffer = &display_map.buffer_snapshot;
10826 let selections = self.selections.all::<Point>(cx);
10827 let ranges = selections
10828 .iter()
10829 .map(|s| {
10830 let range = s.display_range(&display_map).sorted();
10831 let mut start = range.start.to_point(&display_map);
10832 let mut end = range.end.to_point(&display_map);
10833 start.column = 0;
10834 end.column = buffer.line_len(MultiBufferRow(end.row));
10835 start..end
10836 })
10837 .collect::<Vec<_>>();
10838
10839 self.unfold_ranges(ranges, true, true, cx);
10840 }
10841
10842 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10843 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10844 let selections = self.selections.all::<Point>(cx);
10845 let ranges = selections
10846 .iter()
10847 .map(|s| {
10848 let mut range = s.display_range(&display_map).sorted();
10849 *range.start.column_mut() = 0;
10850 *range.end.column_mut() = display_map.line_len(range.end.row());
10851 let start = range.start.to_point(&display_map);
10852 let end = range.end.to_point(&display_map);
10853 start..end
10854 })
10855 .collect::<Vec<_>>();
10856
10857 self.unfold_ranges(ranges, true, true, cx);
10858 }
10859
10860 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10861 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10862
10863 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10864 ..Point::new(
10865 unfold_at.buffer_row.0,
10866 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10867 );
10868
10869 let autoscroll = self
10870 .selections
10871 .all::<Point>(cx)
10872 .iter()
10873 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10874
10875 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10876 }
10877
10878 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10879 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10880 self.unfold_ranges(
10881 [Point::zero()..display_map.max_point().to_point(&display_map)],
10882 true,
10883 true,
10884 cx,
10885 );
10886 }
10887
10888 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10889 let selections = self.selections.all::<Point>(cx);
10890 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10891 let line_mode = self.selections.line_mode;
10892 let ranges = selections.into_iter().map(|s| {
10893 if line_mode {
10894 let start = Point::new(s.start.row, 0);
10895 let end = Point::new(
10896 s.end.row,
10897 display_map
10898 .buffer_snapshot
10899 .line_len(MultiBufferRow(s.end.row)),
10900 );
10901 (start..end, display_map.fold_placeholder.clone())
10902 } else {
10903 (s.start..s.end, display_map.fold_placeholder.clone())
10904 }
10905 });
10906 self.fold_ranges(ranges, true, cx);
10907 }
10908
10909 pub fn fold_ranges<T: ToOffset + Clone>(
10910 &mut self,
10911 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10912 auto_scroll: bool,
10913 cx: &mut ViewContext<Self>,
10914 ) {
10915 let mut fold_ranges = Vec::new();
10916 let mut buffers_affected = HashMap::default();
10917 let multi_buffer = self.buffer().read(cx);
10918 for (fold_range, fold_text) in ranges {
10919 if let Some((_, buffer, _)) =
10920 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10921 {
10922 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10923 };
10924 fold_ranges.push((fold_range, fold_text));
10925 }
10926
10927 let mut ranges = fold_ranges.into_iter().peekable();
10928 if ranges.peek().is_some() {
10929 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10930
10931 if auto_scroll {
10932 self.request_autoscroll(Autoscroll::fit(), cx);
10933 }
10934
10935 for buffer in buffers_affected.into_values() {
10936 self.sync_expanded_diff_hunks(buffer, cx);
10937 }
10938
10939 cx.notify();
10940
10941 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10942 // Clear diagnostics block when folding a range that contains it.
10943 let snapshot = self.snapshot(cx);
10944 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10945 drop(snapshot);
10946 self.active_diagnostics = Some(active_diagnostics);
10947 self.dismiss_diagnostics(cx);
10948 } else {
10949 self.active_diagnostics = Some(active_diagnostics);
10950 }
10951 }
10952
10953 self.scrollbar_marker_state.dirty = true;
10954 }
10955 }
10956
10957 pub fn unfold_ranges<T: ToOffset + Clone>(
10958 &mut self,
10959 ranges: impl IntoIterator<Item = Range<T>>,
10960 inclusive: bool,
10961 auto_scroll: bool,
10962 cx: &mut ViewContext<Self>,
10963 ) {
10964 let mut unfold_ranges = Vec::new();
10965 let mut buffers_affected = HashMap::default();
10966 let multi_buffer = self.buffer().read(cx);
10967 for range in ranges {
10968 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10969 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10970 };
10971 unfold_ranges.push(range);
10972 }
10973
10974 let mut ranges = unfold_ranges.into_iter().peekable();
10975 if ranges.peek().is_some() {
10976 self.display_map
10977 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10978 if auto_scroll {
10979 self.request_autoscroll(Autoscroll::fit(), cx);
10980 }
10981
10982 for buffer in buffers_affected.into_values() {
10983 self.sync_expanded_diff_hunks(buffer, cx);
10984 }
10985
10986 cx.notify();
10987 self.scrollbar_marker_state.dirty = true;
10988 self.active_indent_guides_state.dirty = true;
10989 }
10990 }
10991
10992 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10993 self.display_map.read(cx).fold_placeholder.clone()
10994 }
10995
10996 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10997 if hovered != self.gutter_hovered {
10998 self.gutter_hovered = hovered;
10999 cx.notify();
11000 }
11001 }
11002
11003 pub fn insert_blocks(
11004 &mut self,
11005 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11006 autoscroll: Option<Autoscroll>,
11007 cx: &mut ViewContext<Self>,
11008 ) -> Vec<CustomBlockId> {
11009 let blocks = self
11010 .display_map
11011 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11012 if let Some(autoscroll) = autoscroll {
11013 self.request_autoscroll(autoscroll, cx);
11014 }
11015 cx.notify();
11016 blocks
11017 }
11018
11019 pub fn resize_blocks(
11020 &mut self,
11021 heights: HashMap<CustomBlockId, u32>,
11022 autoscroll: Option<Autoscroll>,
11023 cx: &mut ViewContext<Self>,
11024 ) {
11025 self.display_map
11026 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11027 if let Some(autoscroll) = autoscroll {
11028 self.request_autoscroll(autoscroll, cx);
11029 }
11030 cx.notify();
11031 }
11032
11033 pub fn replace_blocks(
11034 &mut self,
11035 renderers: HashMap<CustomBlockId, RenderBlock>,
11036 autoscroll: Option<Autoscroll>,
11037 cx: &mut ViewContext<Self>,
11038 ) {
11039 self.display_map
11040 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11041 if let Some(autoscroll) = autoscroll {
11042 self.request_autoscroll(autoscroll, cx);
11043 }
11044 cx.notify();
11045 }
11046
11047 pub fn remove_blocks(
11048 &mut self,
11049 block_ids: HashSet<CustomBlockId>,
11050 autoscroll: Option<Autoscroll>,
11051 cx: &mut ViewContext<Self>,
11052 ) {
11053 self.display_map.update(cx, |display_map, cx| {
11054 display_map.remove_blocks(block_ids, cx)
11055 });
11056 if let Some(autoscroll) = autoscroll {
11057 self.request_autoscroll(autoscroll, cx);
11058 }
11059 cx.notify();
11060 }
11061
11062 pub fn row_for_block(
11063 &self,
11064 block_id: CustomBlockId,
11065 cx: &mut ViewContext<Self>,
11066 ) -> Option<DisplayRow> {
11067 self.display_map
11068 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11069 }
11070
11071 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11072 self.focused_block = Some(focused_block);
11073 }
11074
11075 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11076 self.focused_block.take()
11077 }
11078
11079 pub fn insert_creases(
11080 &mut self,
11081 creases: impl IntoIterator<Item = Crease>,
11082 cx: &mut ViewContext<Self>,
11083 ) -> Vec<CreaseId> {
11084 self.display_map
11085 .update(cx, |map, cx| map.insert_creases(creases, cx))
11086 }
11087
11088 pub fn remove_creases(
11089 &mut self,
11090 ids: impl IntoIterator<Item = CreaseId>,
11091 cx: &mut ViewContext<Self>,
11092 ) {
11093 self.display_map
11094 .update(cx, |map, cx| map.remove_creases(ids, cx));
11095 }
11096
11097 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11098 self.display_map
11099 .update(cx, |map, cx| map.snapshot(cx))
11100 .longest_row()
11101 }
11102
11103 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11104 self.display_map
11105 .update(cx, |map, cx| map.snapshot(cx))
11106 .max_point()
11107 }
11108
11109 pub fn text(&self, cx: &AppContext) -> String {
11110 self.buffer.read(cx).read(cx).text()
11111 }
11112
11113 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11114 let text = self.text(cx);
11115 let text = text.trim();
11116
11117 if text.is_empty() {
11118 return None;
11119 }
11120
11121 Some(text.to_string())
11122 }
11123
11124 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11125 self.transact(cx, |this, cx| {
11126 this.buffer
11127 .read(cx)
11128 .as_singleton()
11129 .expect("you can only call set_text on editors for singleton buffers")
11130 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11131 });
11132 }
11133
11134 pub fn display_text(&self, cx: &mut AppContext) -> String {
11135 self.display_map
11136 .update(cx, |map, cx| map.snapshot(cx))
11137 .text()
11138 }
11139
11140 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11141 let mut wrap_guides = smallvec::smallvec![];
11142
11143 if self.show_wrap_guides == Some(false) {
11144 return wrap_guides;
11145 }
11146
11147 let settings = self.buffer.read(cx).settings_at(0, cx);
11148 if settings.show_wrap_guides {
11149 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11150 wrap_guides.push((soft_wrap as usize, true));
11151 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11152 wrap_guides.push((soft_wrap as usize, true));
11153 }
11154 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11155 }
11156
11157 wrap_guides
11158 }
11159
11160 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11161 let settings = self.buffer.read(cx).settings_at(0, cx);
11162 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11163 match mode {
11164 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11165 SoftWrap::None
11166 }
11167 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11168 language_settings::SoftWrap::PreferredLineLength => {
11169 SoftWrap::Column(settings.preferred_line_length)
11170 }
11171 language_settings::SoftWrap::Bounded => {
11172 SoftWrap::Bounded(settings.preferred_line_length)
11173 }
11174 }
11175 }
11176
11177 pub fn set_soft_wrap_mode(
11178 &mut self,
11179 mode: language_settings::SoftWrap,
11180 cx: &mut ViewContext<Self>,
11181 ) {
11182 self.soft_wrap_mode_override = Some(mode);
11183 cx.notify();
11184 }
11185
11186 pub fn set_text_style_refinement(&mut self, style: TextStyleRefinement) {
11187 self.text_style_refinement = Some(style);
11188 }
11189
11190 /// called by the Element so we know what style we were most recently rendered with.
11191 pub(crate) fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11192 let rem_size = cx.rem_size();
11193 self.display_map.update(cx, |map, cx| {
11194 map.set_font(
11195 style.text.font(),
11196 style.text.font_size.to_pixels(rem_size),
11197 cx,
11198 )
11199 });
11200 self.style = Some(style);
11201 }
11202
11203 pub fn style(&self) -> Option<&EditorStyle> {
11204 self.style.as_ref()
11205 }
11206
11207 // Called by the element. This method is not designed to be called outside of the editor
11208 // element's layout code because it does not notify when rewrapping is computed synchronously.
11209 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11210 self.display_map
11211 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11212 }
11213
11214 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11215 if self.soft_wrap_mode_override.is_some() {
11216 self.soft_wrap_mode_override.take();
11217 } else {
11218 let soft_wrap = match self.soft_wrap_mode(cx) {
11219 SoftWrap::GitDiff => return,
11220 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11221 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11222 language_settings::SoftWrap::None
11223 }
11224 };
11225 self.soft_wrap_mode_override = Some(soft_wrap);
11226 }
11227 cx.notify();
11228 }
11229
11230 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11231 let Some(workspace) = self.workspace() else {
11232 return;
11233 };
11234 let fs = workspace.read(cx).app_state().fs.clone();
11235 let current_show = TabBarSettings::get_global(cx).show;
11236 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11237 setting.show = Some(!current_show);
11238 });
11239 }
11240
11241 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11242 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11243 self.buffer
11244 .read(cx)
11245 .settings_at(0, cx)
11246 .indent_guides
11247 .enabled
11248 });
11249 self.show_indent_guides = Some(!currently_enabled);
11250 cx.notify();
11251 }
11252
11253 fn should_show_indent_guides(&self) -> Option<bool> {
11254 self.show_indent_guides
11255 }
11256
11257 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11258 let mut editor_settings = EditorSettings::get_global(cx).clone();
11259 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11260 EditorSettings::override_global(editor_settings, cx);
11261 }
11262
11263 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11264 self.use_relative_line_numbers
11265 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11266 }
11267
11268 pub fn toggle_relative_line_numbers(
11269 &mut self,
11270 _: &ToggleRelativeLineNumbers,
11271 cx: &mut ViewContext<Self>,
11272 ) {
11273 let is_relative = self.should_use_relative_line_numbers(cx);
11274 self.set_relative_line_number(Some(!is_relative), cx)
11275 }
11276
11277 pub fn set_relative_line_number(
11278 &mut self,
11279 is_relative: Option<bool>,
11280 cx: &mut ViewContext<Self>,
11281 ) {
11282 self.use_relative_line_numbers = is_relative;
11283 cx.notify();
11284 }
11285
11286 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11287 self.show_gutter = show_gutter;
11288 cx.notify();
11289 }
11290
11291 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11292 self.show_line_numbers = Some(show_line_numbers);
11293 cx.notify();
11294 }
11295
11296 pub fn set_show_git_diff_gutter(
11297 &mut self,
11298 show_git_diff_gutter: bool,
11299 cx: &mut ViewContext<Self>,
11300 ) {
11301 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11302 cx.notify();
11303 }
11304
11305 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11306 self.show_code_actions = Some(show_code_actions);
11307 cx.notify();
11308 }
11309
11310 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11311 self.show_runnables = Some(show_runnables);
11312 cx.notify();
11313 }
11314
11315 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11316 if self.display_map.read(cx).masked != masked {
11317 self.display_map.update(cx, |map, _| map.masked = masked);
11318 }
11319 cx.notify()
11320 }
11321
11322 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11323 self.show_wrap_guides = Some(show_wrap_guides);
11324 cx.notify();
11325 }
11326
11327 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11328 self.show_indent_guides = Some(show_indent_guides);
11329 cx.notify();
11330 }
11331
11332 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11333 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11334 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11335 if let Some(dir) = file.abs_path(cx).parent() {
11336 return Some(dir.to_owned());
11337 }
11338 }
11339
11340 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11341 return Some(project_path.path.to_path_buf());
11342 }
11343 }
11344
11345 None
11346 }
11347
11348 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11349 self.active_excerpt(cx)?
11350 .1
11351 .read(cx)
11352 .file()
11353 .and_then(|f| f.as_local())
11354 }
11355
11356 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11357 if let Some(target) = self.target_file(cx) {
11358 cx.reveal_path(&target.abs_path(cx));
11359 }
11360 }
11361
11362 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11363 if let Some(file) = self.target_file(cx) {
11364 if let Some(path) = file.abs_path(cx).to_str() {
11365 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11366 }
11367 }
11368 }
11369
11370 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11371 if let Some(file) = self.target_file(cx) {
11372 if let Some(path) = file.path().to_str() {
11373 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11374 }
11375 }
11376 }
11377
11378 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11379 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11380
11381 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11382 self.start_git_blame(true, cx);
11383 }
11384
11385 cx.notify();
11386 }
11387
11388 pub fn toggle_git_blame_inline(
11389 &mut self,
11390 _: &ToggleGitBlameInline,
11391 cx: &mut ViewContext<Self>,
11392 ) {
11393 self.toggle_git_blame_inline_internal(true, cx);
11394 cx.notify();
11395 }
11396
11397 pub fn git_blame_inline_enabled(&self) -> bool {
11398 self.git_blame_inline_enabled
11399 }
11400
11401 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11402 self.show_selection_menu = self
11403 .show_selection_menu
11404 .map(|show_selections_menu| !show_selections_menu)
11405 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11406
11407 cx.notify();
11408 }
11409
11410 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11411 self.show_selection_menu
11412 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11413 }
11414
11415 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11416 if let Some(project) = self.project.as_ref() {
11417 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11418 return;
11419 };
11420
11421 if buffer.read(cx).file().is_none() {
11422 return;
11423 }
11424
11425 let focused = self.focus_handle(cx).contains_focused(cx);
11426
11427 let project = project.clone();
11428 let blame =
11429 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11430 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11431 self.blame = Some(blame);
11432 }
11433 }
11434
11435 fn toggle_git_blame_inline_internal(
11436 &mut self,
11437 user_triggered: bool,
11438 cx: &mut ViewContext<Self>,
11439 ) {
11440 if self.git_blame_inline_enabled {
11441 self.git_blame_inline_enabled = false;
11442 self.show_git_blame_inline = false;
11443 self.show_git_blame_inline_delay_task.take();
11444 } else {
11445 self.git_blame_inline_enabled = true;
11446 self.start_git_blame_inline(user_triggered, cx);
11447 }
11448
11449 cx.notify();
11450 }
11451
11452 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11453 self.start_git_blame(user_triggered, cx);
11454
11455 if ProjectSettings::get_global(cx)
11456 .git
11457 .inline_blame_delay()
11458 .is_some()
11459 {
11460 self.start_inline_blame_timer(cx);
11461 } else {
11462 self.show_git_blame_inline = true
11463 }
11464 }
11465
11466 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11467 self.blame.as_ref()
11468 }
11469
11470 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11471 self.show_git_blame_gutter && self.has_blame_entries(cx)
11472 }
11473
11474 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11475 self.show_git_blame_inline
11476 && self.focus_handle.is_focused(cx)
11477 && !self.newest_selection_head_on_empty_line(cx)
11478 && self.has_blame_entries(cx)
11479 }
11480
11481 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11482 self.blame()
11483 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11484 }
11485
11486 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11487 let cursor_anchor = self.selections.newest_anchor().head();
11488
11489 let snapshot = self.buffer.read(cx).snapshot(cx);
11490 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11491
11492 snapshot.line_len(buffer_row) == 0
11493 }
11494
11495 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11496 let buffer_and_selection = maybe!({
11497 let selection = self.selections.newest::<Point>(cx);
11498 let selection_range = selection.range();
11499
11500 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11501 (buffer, selection_range.start.row..selection_range.end.row)
11502 } else {
11503 let buffer_ranges = self
11504 .buffer()
11505 .read(cx)
11506 .range_to_buffer_ranges(selection_range, cx);
11507
11508 let (buffer, range, _) = if selection.reversed {
11509 buffer_ranges.first()
11510 } else {
11511 buffer_ranges.last()
11512 }?;
11513
11514 let snapshot = buffer.read(cx).snapshot();
11515 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11516 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11517 (buffer.clone(), selection)
11518 };
11519
11520 Some((buffer, selection))
11521 });
11522
11523 let Some((buffer, selection)) = buffer_and_selection else {
11524 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11525 };
11526
11527 let Some(project) = self.project.as_ref() else {
11528 return Task::ready(Err(anyhow!("editor does not have project")));
11529 };
11530
11531 project.update(cx, |project, cx| {
11532 project.get_permalink_to_line(&buffer, selection, cx)
11533 })
11534 }
11535
11536 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11537 let permalink_task = self.get_permalink_to_line(cx);
11538 let workspace = self.workspace();
11539
11540 cx.spawn(|_, mut cx| async move {
11541 match permalink_task.await {
11542 Ok(permalink) => {
11543 cx.update(|cx| {
11544 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11545 })
11546 .ok();
11547 }
11548 Err(err) => {
11549 let message = format!("Failed to copy permalink: {err}");
11550
11551 Err::<(), anyhow::Error>(err).log_err();
11552
11553 if let Some(workspace) = workspace {
11554 workspace
11555 .update(&mut cx, |workspace, cx| {
11556 struct CopyPermalinkToLine;
11557
11558 workspace.show_toast(
11559 Toast::new(
11560 NotificationId::unique::<CopyPermalinkToLine>(),
11561 message,
11562 ),
11563 cx,
11564 )
11565 })
11566 .ok();
11567 }
11568 }
11569 }
11570 })
11571 .detach();
11572 }
11573
11574 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11575 if let Some(file) = self.target_file(cx) {
11576 if let Some(path) = file.path().to_str() {
11577 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11578 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11579 }
11580 }
11581 }
11582
11583 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11584 let permalink_task = self.get_permalink_to_line(cx);
11585 let workspace = self.workspace();
11586
11587 cx.spawn(|_, mut cx| async move {
11588 match permalink_task.await {
11589 Ok(permalink) => {
11590 cx.update(|cx| {
11591 cx.open_url(permalink.as_ref());
11592 })
11593 .ok();
11594 }
11595 Err(err) => {
11596 let message = format!("Failed to open permalink: {err}");
11597
11598 Err::<(), anyhow::Error>(err).log_err();
11599
11600 if let Some(workspace) = workspace {
11601 workspace
11602 .update(&mut cx, |workspace, cx| {
11603 struct OpenPermalinkToLine;
11604
11605 workspace.show_toast(
11606 Toast::new(
11607 NotificationId::unique::<OpenPermalinkToLine>(),
11608 message,
11609 ),
11610 cx,
11611 )
11612 })
11613 .ok();
11614 }
11615 }
11616 }
11617 })
11618 .detach();
11619 }
11620
11621 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11622 /// last highlight added will be used.
11623 ///
11624 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11625 pub fn highlight_rows<T: 'static>(
11626 &mut self,
11627 range: Range<Anchor>,
11628 color: Hsla,
11629 should_autoscroll: bool,
11630 cx: &mut ViewContext<Self>,
11631 ) {
11632 let snapshot = self.buffer().read(cx).snapshot(cx);
11633 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11634 let ix = row_highlights.binary_search_by(|highlight| {
11635 Ordering::Equal
11636 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11637 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11638 });
11639
11640 if let Err(mut ix) = ix {
11641 let index = post_inc(&mut self.highlight_order);
11642
11643 // If this range intersects with the preceding highlight, then merge it with
11644 // the preceding highlight. Otherwise insert a new highlight.
11645 let mut merged = false;
11646 if ix > 0 {
11647 let prev_highlight = &mut row_highlights[ix - 1];
11648 if prev_highlight
11649 .range
11650 .end
11651 .cmp(&range.start, &snapshot)
11652 .is_ge()
11653 {
11654 ix -= 1;
11655 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11656 prev_highlight.range.end = range.end;
11657 }
11658 merged = true;
11659 prev_highlight.index = index;
11660 prev_highlight.color = color;
11661 prev_highlight.should_autoscroll = should_autoscroll;
11662 }
11663 }
11664
11665 if !merged {
11666 row_highlights.insert(
11667 ix,
11668 RowHighlight {
11669 range: range.clone(),
11670 index,
11671 color,
11672 should_autoscroll,
11673 },
11674 );
11675 }
11676
11677 // If any of the following highlights intersect with this one, merge them.
11678 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11679 let highlight = &row_highlights[ix];
11680 if next_highlight
11681 .range
11682 .start
11683 .cmp(&highlight.range.end, &snapshot)
11684 .is_le()
11685 {
11686 if next_highlight
11687 .range
11688 .end
11689 .cmp(&highlight.range.end, &snapshot)
11690 .is_gt()
11691 {
11692 row_highlights[ix].range.end = next_highlight.range.end;
11693 }
11694 row_highlights.remove(ix + 1);
11695 } else {
11696 break;
11697 }
11698 }
11699 }
11700 }
11701
11702 /// Remove any highlighted row ranges of the given type that intersect the
11703 /// given ranges.
11704 pub fn remove_highlighted_rows<T: 'static>(
11705 &mut self,
11706 ranges_to_remove: Vec<Range<Anchor>>,
11707 cx: &mut ViewContext<Self>,
11708 ) {
11709 let snapshot = self.buffer().read(cx).snapshot(cx);
11710 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11711 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11712 row_highlights.retain(|highlight| {
11713 while let Some(range_to_remove) = ranges_to_remove.peek() {
11714 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11715 Ordering::Less | Ordering::Equal => {
11716 ranges_to_remove.next();
11717 }
11718 Ordering::Greater => {
11719 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11720 Ordering::Less | Ordering::Equal => {
11721 return false;
11722 }
11723 Ordering::Greater => break,
11724 }
11725 }
11726 }
11727 }
11728
11729 true
11730 })
11731 }
11732
11733 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11734 pub fn clear_row_highlights<T: 'static>(&mut self) {
11735 self.highlighted_rows.remove(&TypeId::of::<T>());
11736 }
11737
11738 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11739 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11740 self.highlighted_rows
11741 .get(&TypeId::of::<T>())
11742 .map_or(&[] as &[_], |vec| vec.as_slice())
11743 .iter()
11744 .map(|highlight| (highlight.range.clone(), highlight.color))
11745 }
11746
11747 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11748 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11749 /// Allows to ignore certain kinds of highlights.
11750 pub fn highlighted_display_rows(
11751 &mut self,
11752 cx: &mut WindowContext,
11753 ) -> BTreeMap<DisplayRow, Hsla> {
11754 let snapshot = self.snapshot(cx);
11755 let mut used_highlight_orders = HashMap::default();
11756 self.highlighted_rows
11757 .iter()
11758 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11759 .fold(
11760 BTreeMap::<DisplayRow, Hsla>::new(),
11761 |mut unique_rows, highlight| {
11762 let start = highlight.range.start.to_display_point(&snapshot);
11763 let end = highlight.range.end.to_display_point(&snapshot);
11764 let start_row = start.row().0;
11765 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11766 && end.column() == 0
11767 {
11768 end.row().0.saturating_sub(1)
11769 } else {
11770 end.row().0
11771 };
11772 for row in start_row..=end_row {
11773 let used_index =
11774 used_highlight_orders.entry(row).or_insert(highlight.index);
11775 if highlight.index >= *used_index {
11776 *used_index = highlight.index;
11777 unique_rows.insert(DisplayRow(row), highlight.color);
11778 }
11779 }
11780 unique_rows
11781 },
11782 )
11783 }
11784
11785 pub fn highlighted_display_row_for_autoscroll(
11786 &self,
11787 snapshot: &DisplaySnapshot,
11788 ) -> Option<DisplayRow> {
11789 self.highlighted_rows
11790 .values()
11791 .flat_map(|highlighted_rows| highlighted_rows.iter())
11792 .filter_map(|highlight| {
11793 if highlight.should_autoscroll {
11794 Some(highlight.range.start.to_display_point(snapshot).row())
11795 } else {
11796 None
11797 }
11798 })
11799 .min()
11800 }
11801
11802 pub fn set_search_within_ranges(
11803 &mut self,
11804 ranges: &[Range<Anchor>],
11805 cx: &mut ViewContext<Self>,
11806 ) {
11807 self.highlight_background::<SearchWithinRange>(
11808 ranges,
11809 |colors| colors.editor_document_highlight_read_background,
11810 cx,
11811 )
11812 }
11813
11814 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11815 self.breadcrumb_header = Some(new_header);
11816 }
11817
11818 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11819 self.clear_background_highlights::<SearchWithinRange>(cx);
11820 }
11821
11822 pub fn highlight_background<T: 'static>(
11823 &mut self,
11824 ranges: &[Range<Anchor>],
11825 color_fetcher: fn(&ThemeColors) -> Hsla,
11826 cx: &mut ViewContext<Self>,
11827 ) {
11828 self.background_highlights
11829 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11830 self.scrollbar_marker_state.dirty = true;
11831 cx.notify();
11832 }
11833
11834 pub fn clear_background_highlights<T: 'static>(
11835 &mut self,
11836 cx: &mut ViewContext<Self>,
11837 ) -> Option<BackgroundHighlight> {
11838 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11839 if !text_highlights.1.is_empty() {
11840 self.scrollbar_marker_state.dirty = true;
11841 cx.notify();
11842 }
11843 Some(text_highlights)
11844 }
11845
11846 pub fn highlight_gutter<T: 'static>(
11847 &mut self,
11848 ranges: &[Range<Anchor>],
11849 color_fetcher: fn(&AppContext) -> Hsla,
11850 cx: &mut ViewContext<Self>,
11851 ) {
11852 self.gutter_highlights
11853 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11854 cx.notify();
11855 }
11856
11857 pub fn clear_gutter_highlights<T: 'static>(
11858 &mut self,
11859 cx: &mut ViewContext<Self>,
11860 ) -> Option<GutterHighlight> {
11861 cx.notify();
11862 self.gutter_highlights.remove(&TypeId::of::<T>())
11863 }
11864
11865 #[cfg(feature = "test-support")]
11866 pub fn all_text_background_highlights(
11867 &mut self,
11868 cx: &mut ViewContext<Self>,
11869 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11870 let snapshot = self.snapshot(cx);
11871 let buffer = &snapshot.buffer_snapshot;
11872 let start = buffer.anchor_before(0);
11873 let end = buffer.anchor_after(buffer.len());
11874 let theme = cx.theme().colors();
11875 self.background_highlights_in_range(start..end, &snapshot, theme)
11876 }
11877
11878 #[cfg(feature = "test-support")]
11879 pub fn search_background_highlights(
11880 &mut self,
11881 cx: &mut ViewContext<Self>,
11882 ) -> Vec<Range<Point>> {
11883 let snapshot = self.buffer().read(cx).snapshot(cx);
11884
11885 let highlights = self
11886 .background_highlights
11887 .get(&TypeId::of::<items::BufferSearchHighlights>());
11888
11889 if let Some((_color, ranges)) = highlights {
11890 ranges
11891 .iter()
11892 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11893 .collect_vec()
11894 } else {
11895 vec![]
11896 }
11897 }
11898
11899 fn document_highlights_for_position<'a>(
11900 &'a self,
11901 position: Anchor,
11902 buffer: &'a MultiBufferSnapshot,
11903 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11904 let read_highlights = self
11905 .background_highlights
11906 .get(&TypeId::of::<DocumentHighlightRead>())
11907 .map(|h| &h.1);
11908 let write_highlights = self
11909 .background_highlights
11910 .get(&TypeId::of::<DocumentHighlightWrite>())
11911 .map(|h| &h.1);
11912 let left_position = position.bias_left(buffer);
11913 let right_position = position.bias_right(buffer);
11914 read_highlights
11915 .into_iter()
11916 .chain(write_highlights)
11917 .flat_map(move |ranges| {
11918 let start_ix = match ranges.binary_search_by(|probe| {
11919 let cmp = probe.end.cmp(&left_position, buffer);
11920 if cmp.is_ge() {
11921 Ordering::Greater
11922 } else {
11923 Ordering::Less
11924 }
11925 }) {
11926 Ok(i) | Err(i) => i,
11927 };
11928
11929 ranges[start_ix..]
11930 .iter()
11931 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11932 })
11933 }
11934
11935 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11936 self.background_highlights
11937 .get(&TypeId::of::<T>())
11938 .map_or(false, |(_, highlights)| !highlights.is_empty())
11939 }
11940
11941 pub fn background_highlights_in_range(
11942 &self,
11943 search_range: Range<Anchor>,
11944 display_snapshot: &DisplaySnapshot,
11945 theme: &ThemeColors,
11946 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11947 let mut results = Vec::new();
11948 for (color_fetcher, ranges) in self.background_highlights.values() {
11949 let color = color_fetcher(theme);
11950 let start_ix = match ranges.binary_search_by(|probe| {
11951 let cmp = probe
11952 .end
11953 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11954 if cmp.is_gt() {
11955 Ordering::Greater
11956 } else {
11957 Ordering::Less
11958 }
11959 }) {
11960 Ok(i) | Err(i) => i,
11961 };
11962 for range in &ranges[start_ix..] {
11963 if range
11964 .start
11965 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11966 .is_ge()
11967 {
11968 break;
11969 }
11970
11971 let start = range.start.to_display_point(display_snapshot);
11972 let end = range.end.to_display_point(display_snapshot);
11973 results.push((start..end, color))
11974 }
11975 }
11976 results
11977 }
11978
11979 pub fn background_highlight_row_ranges<T: 'static>(
11980 &self,
11981 search_range: Range<Anchor>,
11982 display_snapshot: &DisplaySnapshot,
11983 count: usize,
11984 ) -> Vec<RangeInclusive<DisplayPoint>> {
11985 let mut results = Vec::new();
11986 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11987 return vec![];
11988 };
11989
11990 let start_ix = match ranges.binary_search_by(|probe| {
11991 let cmp = probe
11992 .end
11993 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11994 if cmp.is_gt() {
11995 Ordering::Greater
11996 } else {
11997 Ordering::Less
11998 }
11999 }) {
12000 Ok(i) | Err(i) => i,
12001 };
12002 let mut push_region = |start: Option<Point>, end: Option<Point>| {
12003 if let (Some(start_display), Some(end_display)) = (start, end) {
12004 results.push(
12005 start_display.to_display_point(display_snapshot)
12006 ..=end_display.to_display_point(display_snapshot),
12007 );
12008 }
12009 };
12010 let mut start_row: Option<Point> = None;
12011 let mut end_row: Option<Point> = None;
12012 if ranges.len() > count {
12013 return Vec::new();
12014 }
12015 for range in &ranges[start_ix..] {
12016 if range
12017 .start
12018 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12019 .is_ge()
12020 {
12021 break;
12022 }
12023 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12024 if let Some(current_row) = &end_row {
12025 if end.row == current_row.row {
12026 continue;
12027 }
12028 }
12029 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12030 if start_row.is_none() {
12031 assert_eq!(end_row, None);
12032 start_row = Some(start);
12033 end_row = Some(end);
12034 continue;
12035 }
12036 if let Some(current_end) = end_row.as_mut() {
12037 if start.row > current_end.row + 1 {
12038 push_region(start_row, end_row);
12039 start_row = Some(start);
12040 end_row = Some(end);
12041 } else {
12042 // Merge two hunks.
12043 *current_end = end;
12044 }
12045 } else {
12046 unreachable!();
12047 }
12048 }
12049 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12050 push_region(start_row, end_row);
12051 results
12052 }
12053
12054 pub fn gutter_highlights_in_range(
12055 &self,
12056 search_range: Range<Anchor>,
12057 display_snapshot: &DisplaySnapshot,
12058 cx: &AppContext,
12059 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12060 let mut results = Vec::new();
12061 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12062 let color = color_fetcher(cx);
12063 let start_ix = match ranges.binary_search_by(|probe| {
12064 let cmp = probe
12065 .end
12066 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12067 if cmp.is_gt() {
12068 Ordering::Greater
12069 } else {
12070 Ordering::Less
12071 }
12072 }) {
12073 Ok(i) | Err(i) => i,
12074 };
12075 for range in &ranges[start_ix..] {
12076 if range
12077 .start
12078 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12079 .is_ge()
12080 {
12081 break;
12082 }
12083
12084 let start = range.start.to_display_point(display_snapshot);
12085 let end = range.end.to_display_point(display_snapshot);
12086 results.push((start..end, color))
12087 }
12088 }
12089 results
12090 }
12091
12092 /// Get the text ranges corresponding to the redaction query
12093 pub fn redacted_ranges(
12094 &self,
12095 search_range: Range<Anchor>,
12096 display_snapshot: &DisplaySnapshot,
12097 cx: &WindowContext,
12098 ) -> Vec<Range<DisplayPoint>> {
12099 display_snapshot
12100 .buffer_snapshot
12101 .redacted_ranges(search_range, |file| {
12102 if let Some(file) = file {
12103 file.is_private()
12104 && EditorSettings::get(
12105 Some(SettingsLocation {
12106 worktree_id: file.worktree_id(cx),
12107 path: file.path().as_ref(),
12108 }),
12109 cx,
12110 )
12111 .redact_private_values
12112 } else {
12113 false
12114 }
12115 })
12116 .map(|range| {
12117 range.start.to_display_point(display_snapshot)
12118 ..range.end.to_display_point(display_snapshot)
12119 })
12120 .collect()
12121 }
12122
12123 pub fn highlight_text<T: 'static>(
12124 &mut self,
12125 ranges: Vec<Range<Anchor>>,
12126 style: HighlightStyle,
12127 cx: &mut ViewContext<Self>,
12128 ) {
12129 self.display_map.update(cx, |map, _| {
12130 map.highlight_text(TypeId::of::<T>(), ranges, style)
12131 });
12132 cx.notify();
12133 }
12134
12135 pub(crate) fn highlight_inlays<T: 'static>(
12136 &mut self,
12137 highlights: Vec<InlayHighlight>,
12138 style: HighlightStyle,
12139 cx: &mut ViewContext<Self>,
12140 ) {
12141 self.display_map.update(cx, |map, _| {
12142 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12143 });
12144 cx.notify();
12145 }
12146
12147 pub fn text_highlights<'a, T: 'static>(
12148 &'a self,
12149 cx: &'a AppContext,
12150 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12151 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12152 }
12153
12154 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12155 let cleared = self
12156 .display_map
12157 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12158 if cleared {
12159 cx.notify();
12160 }
12161 }
12162
12163 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12164 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12165 && self.focus_handle.is_focused(cx)
12166 }
12167
12168 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12169 self.show_cursor_when_unfocused = is_enabled;
12170 cx.notify();
12171 }
12172
12173 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12174 cx.notify();
12175 }
12176
12177 fn on_buffer_event(
12178 &mut self,
12179 multibuffer: Model<MultiBuffer>,
12180 event: &multi_buffer::Event,
12181 cx: &mut ViewContext<Self>,
12182 ) {
12183 match event {
12184 multi_buffer::Event::Edited {
12185 singleton_buffer_edited,
12186 } => {
12187 self.scrollbar_marker_state.dirty = true;
12188 self.active_indent_guides_state.dirty = true;
12189 self.refresh_active_diagnostics(cx);
12190 self.refresh_code_actions(cx);
12191 if self.has_active_inline_completion(cx) {
12192 self.update_visible_inline_completion(cx);
12193 }
12194 cx.emit(EditorEvent::BufferEdited);
12195 cx.emit(SearchEvent::MatchesInvalidated);
12196 if *singleton_buffer_edited {
12197 if let Some(project) = &self.project {
12198 let project = project.read(cx);
12199 #[allow(clippy::mutable_key_type)]
12200 let languages_affected = multibuffer
12201 .read(cx)
12202 .all_buffers()
12203 .into_iter()
12204 .filter_map(|buffer| {
12205 let buffer = buffer.read(cx);
12206 let language = buffer.language()?;
12207 if project.is_local()
12208 && project.language_servers_for_buffer(buffer, cx).count() == 0
12209 {
12210 None
12211 } else {
12212 Some(language)
12213 }
12214 })
12215 .cloned()
12216 .collect::<HashSet<_>>();
12217 if !languages_affected.is_empty() {
12218 self.refresh_inlay_hints(
12219 InlayHintRefreshReason::BufferEdited(languages_affected),
12220 cx,
12221 );
12222 }
12223 }
12224 }
12225
12226 let Some(project) = &self.project else { return };
12227 let (telemetry, is_via_ssh) = {
12228 let project = project.read(cx);
12229 let telemetry = project.client().telemetry().clone();
12230 let is_via_ssh = project.is_via_ssh();
12231 (telemetry, is_via_ssh)
12232 };
12233 refresh_linked_ranges(self, cx);
12234 telemetry.log_edit_event("editor", is_via_ssh);
12235 }
12236 multi_buffer::Event::ExcerptsAdded {
12237 buffer,
12238 predecessor,
12239 excerpts,
12240 } => {
12241 self.tasks_update_task = Some(self.refresh_runnables(cx));
12242 cx.emit(EditorEvent::ExcerptsAdded {
12243 buffer: buffer.clone(),
12244 predecessor: *predecessor,
12245 excerpts: excerpts.clone(),
12246 });
12247 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12248 }
12249 multi_buffer::Event::ExcerptsRemoved { ids } => {
12250 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12251 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12252 }
12253 multi_buffer::Event::ExcerptsEdited { ids } => {
12254 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12255 }
12256 multi_buffer::Event::ExcerptsExpanded { ids } => {
12257 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12258 }
12259 multi_buffer::Event::Reparsed(buffer_id) => {
12260 self.tasks_update_task = Some(self.refresh_runnables(cx));
12261
12262 cx.emit(EditorEvent::Reparsed(*buffer_id));
12263 }
12264 multi_buffer::Event::LanguageChanged(buffer_id) => {
12265 linked_editing_ranges::refresh_linked_ranges(self, cx);
12266 cx.emit(EditorEvent::Reparsed(*buffer_id));
12267 cx.notify();
12268 }
12269 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12270 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12271 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12272 cx.emit(EditorEvent::TitleChanged)
12273 }
12274 multi_buffer::Event::DiffBaseChanged => {
12275 self.scrollbar_marker_state.dirty = true;
12276 cx.emit(EditorEvent::DiffBaseChanged);
12277 cx.notify();
12278 }
12279 multi_buffer::Event::DiffUpdated { buffer } => {
12280 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12281 cx.notify();
12282 }
12283 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12284 multi_buffer::Event::DiagnosticsUpdated => {
12285 self.refresh_active_diagnostics(cx);
12286 self.scrollbar_marker_state.dirty = true;
12287 cx.notify();
12288 }
12289 _ => {}
12290 };
12291 }
12292
12293 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12294 cx.notify();
12295 }
12296
12297 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12298 self.tasks_update_task = Some(self.refresh_runnables(cx));
12299 self.refresh_inline_completion(true, false, cx);
12300 self.refresh_inlay_hints(
12301 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12302 self.selections.newest_anchor().head(),
12303 &self.buffer.read(cx).snapshot(cx),
12304 cx,
12305 )),
12306 cx,
12307 );
12308
12309 let old_cursor_shape = self.cursor_shape;
12310
12311 {
12312 let editor_settings = EditorSettings::get_global(cx);
12313 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12314 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12315 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12316 }
12317
12318 if old_cursor_shape != self.cursor_shape {
12319 cx.emit(EditorEvent::CursorShapeChanged);
12320 }
12321
12322 let project_settings = ProjectSettings::get_global(cx);
12323 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12324
12325 if self.mode == EditorMode::Full {
12326 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12327 if self.git_blame_inline_enabled != inline_blame_enabled {
12328 self.toggle_git_blame_inline_internal(false, cx);
12329 }
12330 }
12331
12332 cx.notify();
12333 }
12334
12335 pub fn set_searchable(&mut self, searchable: bool) {
12336 self.searchable = searchable;
12337 }
12338
12339 pub fn searchable(&self) -> bool {
12340 self.searchable
12341 }
12342
12343 fn open_proposed_changes_editor(
12344 &mut self,
12345 _: &OpenProposedChangesEditor,
12346 cx: &mut ViewContext<Self>,
12347 ) {
12348 let Some(workspace) = self.workspace() else {
12349 cx.propagate();
12350 return;
12351 };
12352
12353 let buffer = self.buffer.read(cx);
12354 let mut new_selections_by_buffer = HashMap::default();
12355 for selection in self.selections.all::<usize>(cx) {
12356 for (buffer, range, _) in
12357 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12358 {
12359 let mut range = range.to_point(buffer.read(cx));
12360 range.start.column = 0;
12361 range.end.column = buffer.read(cx).line_len(range.end.row);
12362 new_selections_by_buffer
12363 .entry(buffer)
12364 .or_insert(Vec::new())
12365 .push(range)
12366 }
12367 }
12368
12369 let proposed_changes_buffers = new_selections_by_buffer
12370 .into_iter()
12371 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12372 .collect::<Vec<_>>();
12373 let proposed_changes_editor = cx.new_view(|cx| {
12374 ProposedChangesEditor::new(
12375 "Proposed changes",
12376 proposed_changes_buffers,
12377 self.project.clone(),
12378 cx,
12379 )
12380 });
12381
12382 cx.window_context().defer(move |cx| {
12383 workspace.update(cx, |workspace, cx| {
12384 workspace.active_pane().update(cx, |pane, cx| {
12385 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12386 });
12387 });
12388 });
12389 }
12390
12391 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12392 self.open_excerpts_common(true, cx)
12393 }
12394
12395 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12396 self.open_excerpts_common(false, cx)
12397 }
12398
12399 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12400 let buffer = self.buffer.read(cx);
12401 if buffer.is_singleton() {
12402 cx.propagate();
12403 return;
12404 }
12405
12406 let Some(workspace) = self.workspace() else {
12407 cx.propagate();
12408 return;
12409 };
12410
12411 let mut new_selections_by_buffer = HashMap::default();
12412 for selection in self.selections.all::<usize>(cx) {
12413 for (mut buffer_handle, mut range, _) in
12414 buffer.range_to_buffer_ranges(selection.range(), cx)
12415 {
12416 // When editing branch buffers, jump to the corresponding location
12417 // in their base buffer.
12418 let buffer = buffer_handle.read(cx);
12419 if let Some(base_buffer) = buffer.diff_base_buffer() {
12420 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12421 buffer_handle = base_buffer;
12422 }
12423
12424 if selection.reversed {
12425 mem::swap(&mut range.start, &mut range.end);
12426 }
12427 new_selections_by_buffer
12428 .entry(buffer_handle)
12429 .or_insert(Vec::new())
12430 .push(range)
12431 }
12432 }
12433
12434 // We defer the pane interaction because we ourselves are a workspace item
12435 // and activating a new item causes the pane to call a method on us reentrantly,
12436 // which panics if we're on the stack.
12437 cx.window_context().defer(move |cx| {
12438 workspace.update(cx, |workspace, cx| {
12439 let pane = if split {
12440 workspace.adjacent_pane(cx)
12441 } else {
12442 workspace.active_pane().clone()
12443 };
12444
12445 for (buffer, ranges) in new_selections_by_buffer {
12446 let editor =
12447 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12448 editor.update(cx, |editor, cx| {
12449 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12450 s.select_ranges(ranges);
12451 });
12452 });
12453 }
12454 })
12455 });
12456 }
12457
12458 fn jump(
12459 &mut self,
12460 path: ProjectPath,
12461 position: Point,
12462 anchor: language::Anchor,
12463 offset_from_top: u32,
12464 cx: &mut ViewContext<Self>,
12465 ) {
12466 let workspace = self.workspace();
12467 cx.spawn(|_, mut cx| async move {
12468 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12469 let editor = workspace.update(&mut cx, |workspace, cx| {
12470 // Reset the preview item id before opening the new item
12471 workspace.active_pane().update(cx, |pane, cx| {
12472 pane.set_preview_item_id(None, cx);
12473 });
12474 workspace.open_path_preview(path, None, true, true, cx)
12475 })?;
12476 let editor = editor
12477 .await?
12478 .downcast::<Editor>()
12479 .ok_or_else(|| anyhow!("opened item was not an editor"))?
12480 .downgrade();
12481 editor.update(&mut cx, |editor, cx| {
12482 let buffer = editor
12483 .buffer()
12484 .read(cx)
12485 .as_singleton()
12486 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12487 let buffer = buffer.read(cx);
12488 let cursor = if buffer.can_resolve(&anchor) {
12489 language::ToPoint::to_point(&anchor, buffer)
12490 } else {
12491 buffer.clip_point(position, Bias::Left)
12492 };
12493
12494 let nav_history = editor.nav_history.take();
12495 editor.change_selections(
12496 Some(Autoscroll::top_relative(offset_from_top as usize)),
12497 cx,
12498 |s| {
12499 s.select_ranges([cursor..cursor]);
12500 },
12501 );
12502 editor.nav_history = nav_history;
12503
12504 anyhow::Ok(())
12505 })??;
12506
12507 anyhow::Ok(())
12508 })
12509 .detach_and_log_err(cx);
12510 }
12511
12512 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12513 let snapshot = self.buffer.read(cx).read(cx);
12514 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12515 Some(
12516 ranges
12517 .iter()
12518 .map(move |range| {
12519 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12520 })
12521 .collect(),
12522 )
12523 }
12524
12525 fn selection_replacement_ranges(
12526 &self,
12527 range: Range<OffsetUtf16>,
12528 cx: &AppContext,
12529 ) -> Vec<Range<OffsetUtf16>> {
12530 let selections = self.selections.all::<OffsetUtf16>(cx);
12531 let newest_selection = selections
12532 .iter()
12533 .max_by_key(|selection| selection.id)
12534 .unwrap();
12535 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12536 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12537 let snapshot = self.buffer.read(cx).read(cx);
12538 selections
12539 .into_iter()
12540 .map(|mut selection| {
12541 selection.start.0 =
12542 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12543 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12544 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12545 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12546 })
12547 .collect()
12548 }
12549
12550 fn report_editor_event(
12551 &self,
12552 operation: &'static str,
12553 file_extension: Option<String>,
12554 cx: &AppContext,
12555 ) {
12556 if cfg!(any(test, feature = "test-support")) {
12557 return;
12558 }
12559
12560 let Some(project) = &self.project else { return };
12561
12562 // If None, we are in a file without an extension
12563 let file = self
12564 .buffer
12565 .read(cx)
12566 .as_singleton()
12567 .and_then(|b| b.read(cx).file());
12568 let file_extension = file_extension.or(file
12569 .as_ref()
12570 .and_then(|file| Path::new(file.file_name(cx)).extension())
12571 .and_then(|e| e.to_str())
12572 .map(|a| a.to_string()));
12573
12574 let vim_mode = cx
12575 .global::<SettingsStore>()
12576 .raw_user_settings()
12577 .get("vim_mode")
12578 == Some(&serde_json::Value::Bool(true));
12579
12580 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12581 == language::language_settings::InlineCompletionProvider::Copilot;
12582 let copilot_enabled_for_language = self
12583 .buffer
12584 .read(cx)
12585 .settings_at(0, cx)
12586 .show_inline_completions;
12587
12588 let project = project.read(cx);
12589 let telemetry = project.client().telemetry().clone();
12590 telemetry.report_editor_event(
12591 file_extension,
12592 vim_mode,
12593 operation,
12594 copilot_enabled,
12595 copilot_enabled_for_language,
12596 project.is_via_ssh(),
12597 )
12598 }
12599
12600 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12601 /// with each line being an array of {text, highlight} objects.
12602 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12603 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12604 return;
12605 };
12606
12607 #[derive(Serialize)]
12608 struct Chunk<'a> {
12609 text: String,
12610 highlight: Option<&'a str>,
12611 }
12612
12613 let snapshot = buffer.read(cx).snapshot();
12614 let range = self
12615 .selected_text_range(false, cx)
12616 .and_then(|selection| {
12617 if selection.range.is_empty() {
12618 None
12619 } else {
12620 Some(selection.range)
12621 }
12622 })
12623 .unwrap_or_else(|| 0..snapshot.len());
12624
12625 let chunks = snapshot.chunks(range, true);
12626 let mut lines = Vec::new();
12627 let mut line: VecDeque<Chunk> = VecDeque::new();
12628
12629 let Some(style) = self.style.as_ref() else {
12630 return;
12631 };
12632
12633 for chunk in chunks {
12634 let highlight = chunk
12635 .syntax_highlight_id
12636 .and_then(|id| id.name(&style.syntax));
12637 let mut chunk_lines = chunk.text.split('\n').peekable();
12638 while let Some(text) = chunk_lines.next() {
12639 let mut merged_with_last_token = false;
12640 if let Some(last_token) = line.back_mut() {
12641 if last_token.highlight == highlight {
12642 last_token.text.push_str(text);
12643 merged_with_last_token = true;
12644 }
12645 }
12646
12647 if !merged_with_last_token {
12648 line.push_back(Chunk {
12649 text: text.into(),
12650 highlight,
12651 });
12652 }
12653
12654 if chunk_lines.peek().is_some() {
12655 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12656 line.pop_front();
12657 }
12658 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12659 line.pop_back();
12660 }
12661
12662 lines.push(mem::take(&mut line));
12663 }
12664 }
12665 }
12666
12667 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12668 return;
12669 };
12670 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12671 }
12672
12673 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12674 &self.inlay_hint_cache
12675 }
12676
12677 pub fn replay_insert_event(
12678 &mut self,
12679 text: &str,
12680 relative_utf16_range: Option<Range<isize>>,
12681 cx: &mut ViewContext<Self>,
12682 ) {
12683 if !self.input_enabled {
12684 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12685 return;
12686 }
12687 if let Some(relative_utf16_range) = relative_utf16_range {
12688 let selections = self.selections.all::<OffsetUtf16>(cx);
12689 self.change_selections(None, cx, |s| {
12690 let new_ranges = selections.into_iter().map(|range| {
12691 let start = OffsetUtf16(
12692 range
12693 .head()
12694 .0
12695 .saturating_add_signed(relative_utf16_range.start),
12696 );
12697 let end = OffsetUtf16(
12698 range
12699 .head()
12700 .0
12701 .saturating_add_signed(relative_utf16_range.end),
12702 );
12703 start..end
12704 });
12705 s.select_ranges(new_ranges);
12706 });
12707 }
12708
12709 self.handle_input(text, cx);
12710 }
12711
12712 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12713 let Some(provider) = self.semantics_provider.as_ref() else {
12714 return false;
12715 };
12716
12717 let mut supports = false;
12718 self.buffer().read(cx).for_each_buffer(|buffer| {
12719 supports |= provider.supports_inlay_hints(buffer, cx);
12720 });
12721 supports
12722 }
12723
12724 pub fn focus(&self, cx: &mut WindowContext) {
12725 cx.focus(&self.focus_handle)
12726 }
12727
12728 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12729 self.focus_handle.is_focused(cx)
12730 }
12731
12732 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12733 cx.emit(EditorEvent::Focused);
12734
12735 if let Some(descendant) = self
12736 .last_focused_descendant
12737 .take()
12738 .and_then(|descendant| descendant.upgrade())
12739 {
12740 cx.focus(&descendant);
12741 } else {
12742 if let Some(blame) = self.blame.as_ref() {
12743 blame.update(cx, GitBlame::focus)
12744 }
12745
12746 self.blink_manager.update(cx, BlinkManager::enable);
12747 self.show_cursor_names(cx);
12748 self.buffer.update(cx, |buffer, cx| {
12749 buffer.finalize_last_transaction(cx);
12750 if self.leader_peer_id.is_none() {
12751 buffer.set_active_selections(
12752 &self.selections.disjoint_anchors(),
12753 self.selections.line_mode,
12754 self.cursor_shape,
12755 cx,
12756 );
12757 }
12758 });
12759 }
12760 }
12761
12762 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12763 cx.emit(EditorEvent::FocusedIn)
12764 }
12765
12766 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12767 if event.blurred != self.focus_handle {
12768 self.last_focused_descendant = Some(event.blurred);
12769 }
12770 }
12771
12772 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12773 self.blink_manager.update(cx, BlinkManager::disable);
12774 self.buffer
12775 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12776
12777 if let Some(blame) = self.blame.as_ref() {
12778 blame.update(cx, GitBlame::blur)
12779 }
12780 if !self.hover_state.focused(cx) {
12781 hide_hover(self, cx);
12782 }
12783
12784 self.hide_context_menu(cx);
12785 cx.emit(EditorEvent::Blurred);
12786 cx.notify();
12787 }
12788
12789 pub fn register_action<A: Action>(
12790 &mut self,
12791 listener: impl Fn(&A, &mut WindowContext) + 'static,
12792 ) -> Subscription {
12793 let id = self.next_editor_action_id.post_inc();
12794 let listener = Arc::new(listener);
12795 self.editor_actions.borrow_mut().insert(
12796 id,
12797 Box::new(move |cx| {
12798 let cx = cx.window_context();
12799 let listener = listener.clone();
12800 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12801 let action = action.downcast_ref().unwrap();
12802 if phase == DispatchPhase::Bubble {
12803 listener(action, cx)
12804 }
12805 })
12806 }),
12807 );
12808
12809 let editor_actions = self.editor_actions.clone();
12810 Subscription::new(move || {
12811 editor_actions.borrow_mut().remove(&id);
12812 })
12813 }
12814
12815 pub fn file_header_size(&self) -> u32 {
12816 FILE_HEADER_HEIGHT
12817 }
12818
12819 pub fn revert(
12820 &mut self,
12821 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12822 cx: &mut ViewContext<Self>,
12823 ) {
12824 self.buffer().update(cx, |multi_buffer, cx| {
12825 for (buffer_id, changes) in revert_changes {
12826 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12827 buffer.update(cx, |buffer, cx| {
12828 buffer.edit(
12829 changes.into_iter().map(|(range, text)| {
12830 (range, text.to_string().map(Arc::<str>::from))
12831 }),
12832 None,
12833 cx,
12834 );
12835 });
12836 }
12837 }
12838 });
12839 self.change_selections(None, cx, |selections| selections.refresh());
12840 }
12841
12842 pub fn to_pixel_point(
12843 &mut self,
12844 source: multi_buffer::Anchor,
12845 editor_snapshot: &EditorSnapshot,
12846 cx: &mut ViewContext<Self>,
12847 ) -> Option<gpui::Point<Pixels>> {
12848 let source_point = source.to_display_point(editor_snapshot);
12849 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12850 }
12851
12852 pub fn display_to_pixel_point(
12853 &mut self,
12854 source: DisplayPoint,
12855 editor_snapshot: &EditorSnapshot,
12856 cx: &mut ViewContext<Self>,
12857 ) -> Option<gpui::Point<Pixels>> {
12858 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12859 let text_layout_details = self.text_layout_details(cx);
12860 let scroll_top = text_layout_details
12861 .scroll_anchor
12862 .scroll_position(editor_snapshot)
12863 .y;
12864
12865 if source.row().as_f32() < scroll_top.floor() {
12866 return None;
12867 }
12868 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12869 let source_y = line_height * (source.row().as_f32() - scroll_top);
12870 Some(gpui::Point::new(source_x, source_y))
12871 }
12872
12873 pub fn has_active_completions_menu(&self) -> bool {
12874 self.context_menu.read().as_ref().map_or(false, |menu| {
12875 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12876 })
12877 }
12878
12879 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12880 self.addons
12881 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12882 }
12883
12884 pub fn unregister_addon<T: Addon>(&mut self) {
12885 self.addons.remove(&std::any::TypeId::of::<T>());
12886 }
12887
12888 pub fn addon<T: Addon>(&self) -> Option<&T> {
12889 let type_id = std::any::TypeId::of::<T>();
12890 self.addons
12891 .get(&type_id)
12892 .and_then(|item| item.to_any().downcast_ref::<T>())
12893 }
12894}
12895
12896fn hunks_for_selections(
12897 multi_buffer_snapshot: &MultiBufferSnapshot,
12898 selections: &[Selection<Anchor>],
12899) -> Vec<MultiBufferDiffHunk> {
12900 let buffer_rows_for_selections = selections.iter().map(|selection| {
12901 let head = selection.head();
12902 let tail = selection.tail();
12903 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12904 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12905 if start > end {
12906 end..start
12907 } else {
12908 start..end
12909 }
12910 });
12911
12912 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12913}
12914
12915pub fn hunks_for_rows(
12916 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12917 multi_buffer_snapshot: &MultiBufferSnapshot,
12918) -> Vec<MultiBufferDiffHunk> {
12919 let mut hunks = Vec::new();
12920 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12921 HashMap::default();
12922 for selected_multi_buffer_rows in rows {
12923 let query_rows =
12924 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12925 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12926 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12927 // when the caret is just above or just below the deleted hunk.
12928 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12929 let related_to_selection = if allow_adjacent {
12930 hunk.row_range.overlaps(&query_rows)
12931 || hunk.row_range.start == query_rows.end
12932 || hunk.row_range.end == query_rows.start
12933 } else {
12934 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12935 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12936 hunk.row_range.overlaps(&selected_multi_buffer_rows)
12937 || selected_multi_buffer_rows.end == hunk.row_range.start
12938 };
12939 if related_to_selection {
12940 if !processed_buffer_rows
12941 .entry(hunk.buffer_id)
12942 .or_default()
12943 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12944 {
12945 continue;
12946 }
12947 hunks.push(hunk);
12948 }
12949 }
12950 }
12951
12952 hunks
12953}
12954
12955pub trait CollaborationHub {
12956 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12957 fn user_participant_indices<'a>(
12958 &self,
12959 cx: &'a AppContext,
12960 ) -> &'a HashMap<u64, ParticipantIndex>;
12961 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12962}
12963
12964impl CollaborationHub for Model<Project> {
12965 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12966 self.read(cx).collaborators()
12967 }
12968
12969 fn user_participant_indices<'a>(
12970 &self,
12971 cx: &'a AppContext,
12972 ) -> &'a HashMap<u64, ParticipantIndex> {
12973 self.read(cx).user_store().read(cx).participant_indices()
12974 }
12975
12976 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12977 let this = self.read(cx);
12978 let user_ids = this.collaborators().values().map(|c| c.user_id);
12979 this.user_store().read_with(cx, |user_store, cx| {
12980 user_store.participant_names(user_ids, cx)
12981 })
12982 }
12983}
12984
12985pub trait SemanticsProvider {
12986 fn hover(
12987 &self,
12988 buffer: &Model<Buffer>,
12989 position: text::Anchor,
12990 cx: &mut AppContext,
12991 ) -> Option<Task<Vec<project::Hover>>>;
12992
12993 fn inlay_hints(
12994 &self,
12995 buffer_handle: Model<Buffer>,
12996 range: Range<text::Anchor>,
12997 cx: &mut AppContext,
12998 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
12999
13000 fn resolve_inlay_hint(
13001 &self,
13002 hint: InlayHint,
13003 buffer_handle: Model<Buffer>,
13004 server_id: LanguageServerId,
13005 cx: &mut AppContext,
13006 ) -> Option<Task<anyhow::Result<InlayHint>>>;
13007
13008 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13009
13010 fn document_highlights(
13011 &self,
13012 buffer: &Model<Buffer>,
13013 position: text::Anchor,
13014 cx: &mut AppContext,
13015 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13016
13017 fn definitions(
13018 &self,
13019 buffer: &Model<Buffer>,
13020 position: text::Anchor,
13021 kind: GotoDefinitionKind,
13022 cx: &mut AppContext,
13023 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13024
13025 fn range_for_rename(
13026 &self,
13027 buffer: &Model<Buffer>,
13028 position: text::Anchor,
13029 cx: &mut AppContext,
13030 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13031
13032 fn perform_rename(
13033 &self,
13034 buffer: &Model<Buffer>,
13035 position: text::Anchor,
13036 new_name: String,
13037 cx: &mut AppContext,
13038 ) -> Option<Task<Result<ProjectTransaction>>>;
13039}
13040
13041pub trait CompletionProvider {
13042 fn completions(
13043 &self,
13044 buffer: &Model<Buffer>,
13045 buffer_position: text::Anchor,
13046 trigger: CompletionContext,
13047 cx: &mut ViewContext<Editor>,
13048 ) -> Task<Result<Vec<Completion>>>;
13049
13050 fn resolve_completions(
13051 &self,
13052 buffer: Model<Buffer>,
13053 completion_indices: Vec<usize>,
13054 completions: Arc<RwLock<Box<[Completion]>>>,
13055 cx: &mut ViewContext<Editor>,
13056 ) -> Task<Result<bool>>;
13057
13058 fn apply_additional_edits_for_completion(
13059 &self,
13060 buffer: Model<Buffer>,
13061 completion: Completion,
13062 push_to_history: bool,
13063 cx: &mut ViewContext<Editor>,
13064 ) -> Task<Result<Option<language::Transaction>>>;
13065
13066 fn is_completion_trigger(
13067 &self,
13068 buffer: &Model<Buffer>,
13069 position: language::Anchor,
13070 text: &str,
13071 trigger_in_words: bool,
13072 cx: &mut ViewContext<Editor>,
13073 ) -> bool;
13074
13075 fn sort_completions(&self) -> bool {
13076 true
13077 }
13078}
13079
13080pub trait CodeActionProvider {
13081 fn code_actions(
13082 &self,
13083 buffer: &Model<Buffer>,
13084 range: Range<text::Anchor>,
13085 cx: &mut WindowContext,
13086 ) -> Task<Result<Vec<CodeAction>>>;
13087
13088 fn apply_code_action(
13089 &self,
13090 buffer_handle: Model<Buffer>,
13091 action: CodeAction,
13092 excerpt_id: ExcerptId,
13093 push_to_history: bool,
13094 cx: &mut WindowContext,
13095 ) -> Task<Result<ProjectTransaction>>;
13096}
13097
13098impl CodeActionProvider for Model<Project> {
13099 fn code_actions(
13100 &self,
13101 buffer: &Model<Buffer>,
13102 range: Range<text::Anchor>,
13103 cx: &mut WindowContext,
13104 ) -> Task<Result<Vec<CodeAction>>> {
13105 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13106 }
13107
13108 fn apply_code_action(
13109 &self,
13110 buffer_handle: Model<Buffer>,
13111 action: CodeAction,
13112 _excerpt_id: ExcerptId,
13113 push_to_history: bool,
13114 cx: &mut WindowContext,
13115 ) -> Task<Result<ProjectTransaction>> {
13116 self.update(cx, |project, cx| {
13117 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13118 })
13119 }
13120}
13121
13122fn snippet_completions(
13123 project: &Project,
13124 buffer: &Model<Buffer>,
13125 buffer_position: text::Anchor,
13126 cx: &mut AppContext,
13127) -> Vec<Completion> {
13128 let language = buffer.read(cx).language_at(buffer_position);
13129 let language_name = language.as_ref().map(|language| language.lsp_id());
13130 let snippet_store = project.snippets().read(cx);
13131 let snippets = snippet_store.snippets_for(language_name, cx);
13132
13133 if snippets.is_empty() {
13134 return vec![];
13135 }
13136 let snapshot = buffer.read(cx).text_snapshot();
13137 let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13138
13139 let scope = language.map(|language| language.default_scope());
13140 let classifier = CharClassifier::new(scope).for_completion(true);
13141 let mut last_word = chars
13142 .take_while(|c| classifier.is_word(*c))
13143 .collect::<String>();
13144 last_word = last_word.chars().rev().collect();
13145 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13146 let to_lsp = |point: &text::Anchor| {
13147 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13148 point_to_lsp(end)
13149 };
13150 let lsp_end = to_lsp(&buffer_position);
13151 snippets
13152 .into_iter()
13153 .filter_map(|snippet| {
13154 let matching_prefix = snippet
13155 .prefix
13156 .iter()
13157 .find(|prefix| prefix.starts_with(&last_word))?;
13158 let start = as_offset - last_word.len();
13159 let start = snapshot.anchor_before(start);
13160 let range = start..buffer_position;
13161 let lsp_start = to_lsp(&start);
13162 let lsp_range = lsp::Range {
13163 start: lsp_start,
13164 end: lsp_end,
13165 };
13166 Some(Completion {
13167 old_range: range,
13168 new_text: snippet.body.clone(),
13169 label: CodeLabel {
13170 text: matching_prefix.clone(),
13171 runs: vec![],
13172 filter_range: 0..matching_prefix.len(),
13173 },
13174 server_id: LanguageServerId(usize::MAX),
13175 documentation: snippet.description.clone().map(Documentation::SingleLine),
13176 lsp_completion: lsp::CompletionItem {
13177 label: snippet.prefix.first().unwrap().clone(),
13178 kind: Some(CompletionItemKind::SNIPPET),
13179 label_details: snippet.description.as_ref().map(|description| {
13180 lsp::CompletionItemLabelDetails {
13181 detail: Some(description.clone()),
13182 description: None,
13183 }
13184 }),
13185 insert_text_format: Some(InsertTextFormat::SNIPPET),
13186 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13187 lsp::InsertReplaceEdit {
13188 new_text: snippet.body.clone(),
13189 insert: lsp_range,
13190 replace: lsp_range,
13191 },
13192 )),
13193 filter_text: Some(snippet.body.clone()),
13194 sort_text: Some(char::MAX.to_string()),
13195 ..Default::default()
13196 },
13197 confirm: None,
13198 })
13199 })
13200 .collect()
13201}
13202
13203impl CompletionProvider for Model<Project> {
13204 fn completions(
13205 &self,
13206 buffer: &Model<Buffer>,
13207 buffer_position: text::Anchor,
13208 options: CompletionContext,
13209 cx: &mut ViewContext<Editor>,
13210 ) -> Task<Result<Vec<Completion>>> {
13211 self.update(cx, |project, cx| {
13212 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13213 let project_completions = project.completions(buffer, buffer_position, options, cx);
13214 cx.background_executor().spawn(async move {
13215 let mut completions = project_completions.await?;
13216 //let snippets = snippets.into_iter().;
13217 completions.extend(snippets);
13218 Ok(completions)
13219 })
13220 })
13221 }
13222
13223 fn resolve_completions(
13224 &self,
13225 buffer: Model<Buffer>,
13226 completion_indices: Vec<usize>,
13227 completions: Arc<RwLock<Box<[Completion]>>>,
13228 cx: &mut ViewContext<Editor>,
13229 ) -> Task<Result<bool>> {
13230 self.update(cx, |project, cx| {
13231 project.resolve_completions(buffer, completion_indices, completions, cx)
13232 })
13233 }
13234
13235 fn apply_additional_edits_for_completion(
13236 &self,
13237 buffer: Model<Buffer>,
13238 completion: Completion,
13239 push_to_history: bool,
13240 cx: &mut ViewContext<Editor>,
13241 ) -> Task<Result<Option<language::Transaction>>> {
13242 self.update(cx, |project, cx| {
13243 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13244 })
13245 }
13246
13247 fn is_completion_trigger(
13248 &self,
13249 buffer: &Model<Buffer>,
13250 position: language::Anchor,
13251 text: &str,
13252 trigger_in_words: bool,
13253 cx: &mut ViewContext<Editor>,
13254 ) -> bool {
13255 if !EditorSettings::get_global(cx).show_completions_on_input {
13256 return false;
13257 }
13258
13259 let mut chars = text.chars();
13260 let char = if let Some(char) = chars.next() {
13261 char
13262 } else {
13263 return false;
13264 };
13265 if chars.next().is_some() {
13266 return false;
13267 }
13268
13269 let buffer = buffer.read(cx);
13270 let classifier = buffer
13271 .snapshot()
13272 .char_classifier_at(position)
13273 .for_completion(true);
13274 if trigger_in_words && classifier.is_word(char) {
13275 return true;
13276 }
13277
13278 buffer
13279 .completion_triggers()
13280 .iter()
13281 .any(|string| string == text)
13282 }
13283}
13284
13285impl SemanticsProvider for Model<Project> {
13286 fn hover(
13287 &self,
13288 buffer: &Model<Buffer>,
13289 position: text::Anchor,
13290 cx: &mut AppContext,
13291 ) -> Option<Task<Vec<project::Hover>>> {
13292 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13293 }
13294
13295 fn document_highlights(
13296 &self,
13297 buffer: &Model<Buffer>,
13298 position: text::Anchor,
13299 cx: &mut AppContext,
13300 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13301 Some(self.update(cx, |project, cx| {
13302 project.document_highlights(buffer, position, cx)
13303 }))
13304 }
13305
13306 fn definitions(
13307 &self,
13308 buffer: &Model<Buffer>,
13309 position: text::Anchor,
13310 kind: GotoDefinitionKind,
13311 cx: &mut AppContext,
13312 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13313 Some(self.update(cx, |project, cx| match kind {
13314 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13315 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13316 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13317 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13318 }))
13319 }
13320
13321 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13322 // TODO: make this work for remote projects
13323 self.read(cx)
13324 .language_servers_for_buffer(buffer.read(cx), cx)
13325 .any(
13326 |(_, server)| match server.capabilities().inlay_hint_provider {
13327 Some(lsp::OneOf::Left(enabled)) => enabled,
13328 Some(lsp::OneOf::Right(_)) => true,
13329 None => false,
13330 },
13331 )
13332 }
13333
13334 fn inlay_hints(
13335 &self,
13336 buffer_handle: Model<Buffer>,
13337 range: Range<text::Anchor>,
13338 cx: &mut AppContext,
13339 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13340 Some(self.update(cx, |project, cx| {
13341 project.inlay_hints(buffer_handle, range, cx)
13342 }))
13343 }
13344
13345 fn resolve_inlay_hint(
13346 &self,
13347 hint: InlayHint,
13348 buffer_handle: Model<Buffer>,
13349 server_id: LanguageServerId,
13350 cx: &mut AppContext,
13351 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13352 Some(self.update(cx, |project, cx| {
13353 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13354 }))
13355 }
13356
13357 fn range_for_rename(
13358 &self,
13359 buffer: &Model<Buffer>,
13360 position: text::Anchor,
13361 cx: &mut AppContext,
13362 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13363 Some(self.update(cx, |project, cx| {
13364 project.prepare_rename(buffer.clone(), position, cx)
13365 }))
13366 }
13367
13368 fn perform_rename(
13369 &self,
13370 buffer: &Model<Buffer>,
13371 position: text::Anchor,
13372 new_name: String,
13373 cx: &mut AppContext,
13374 ) -> Option<Task<Result<ProjectTransaction>>> {
13375 Some(self.update(cx, |project, cx| {
13376 project.perform_rename(buffer.clone(), position, new_name, cx)
13377 }))
13378 }
13379}
13380
13381fn inlay_hint_settings(
13382 location: Anchor,
13383 snapshot: &MultiBufferSnapshot,
13384 cx: &mut ViewContext<'_, Editor>,
13385) -> InlayHintSettings {
13386 let file = snapshot.file_at(location);
13387 let language = snapshot.language_at(location).map(|l| l.name());
13388 language_settings(language, file, cx).inlay_hints
13389}
13390
13391fn consume_contiguous_rows(
13392 contiguous_row_selections: &mut Vec<Selection<Point>>,
13393 selection: &Selection<Point>,
13394 display_map: &DisplaySnapshot,
13395 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13396) -> (MultiBufferRow, MultiBufferRow) {
13397 contiguous_row_selections.push(selection.clone());
13398 let start_row = MultiBufferRow(selection.start.row);
13399 let mut end_row = ending_row(selection, display_map);
13400
13401 while let Some(next_selection) = selections.peek() {
13402 if next_selection.start.row <= end_row.0 {
13403 end_row = ending_row(next_selection, display_map);
13404 contiguous_row_selections.push(selections.next().unwrap().clone());
13405 } else {
13406 break;
13407 }
13408 }
13409 (start_row, end_row)
13410}
13411
13412fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13413 if next_selection.end.column > 0 || next_selection.is_empty() {
13414 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13415 } else {
13416 MultiBufferRow(next_selection.end.row)
13417 }
13418}
13419
13420impl EditorSnapshot {
13421 pub fn remote_selections_in_range<'a>(
13422 &'a self,
13423 range: &'a Range<Anchor>,
13424 collaboration_hub: &dyn CollaborationHub,
13425 cx: &'a AppContext,
13426 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13427 let participant_names = collaboration_hub.user_names(cx);
13428 let participant_indices = collaboration_hub.user_participant_indices(cx);
13429 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13430 let collaborators_by_replica_id = collaborators_by_peer_id
13431 .iter()
13432 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13433 .collect::<HashMap<_, _>>();
13434 self.buffer_snapshot
13435 .selections_in_range(range, false)
13436 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13437 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13438 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13439 let user_name = participant_names.get(&collaborator.user_id).cloned();
13440 Some(RemoteSelection {
13441 replica_id,
13442 selection,
13443 cursor_shape,
13444 line_mode,
13445 participant_index,
13446 peer_id: collaborator.peer_id,
13447 user_name,
13448 })
13449 })
13450 }
13451
13452 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13453 self.display_snapshot.buffer_snapshot.language_at(position)
13454 }
13455
13456 pub fn is_focused(&self) -> bool {
13457 self.is_focused
13458 }
13459
13460 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13461 self.placeholder_text.as_ref()
13462 }
13463
13464 pub fn scroll_position(&self) -> gpui::Point<f32> {
13465 self.scroll_anchor.scroll_position(&self.display_snapshot)
13466 }
13467
13468 fn gutter_dimensions(
13469 &self,
13470 font_id: FontId,
13471 font_size: Pixels,
13472 em_width: Pixels,
13473 em_advance: Pixels,
13474 max_line_number_width: Pixels,
13475 cx: &AppContext,
13476 ) -> GutterDimensions {
13477 if !self.show_gutter {
13478 return GutterDimensions::default();
13479 }
13480 let descent = cx.text_system().descent(font_id, font_size);
13481
13482 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13483 matches!(
13484 ProjectSettings::get_global(cx).git.git_gutter,
13485 Some(GitGutterSetting::TrackedFiles)
13486 )
13487 });
13488 let gutter_settings = EditorSettings::get_global(cx).gutter;
13489 let show_line_numbers = self
13490 .show_line_numbers
13491 .unwrap_or(gutter_settings.line_numbers);
13492 let line_gutter_width = if show_line_numbers {
13493 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13494 let min_width_for_number_on_gutter = em_advance * 4.0;
13495 max_line_number_width.max(min_width_for_number_on_gutter)
13496 } else {
13497 0.0.into()
13498 };
13499
13500 let show_code_actions = self
13501 .show_code_actions
13502 .unwrap_or(gutter_settings.code_actions);
13503
13504 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13505
13506 let git_blame_entries_width =
13507 self.git_blame_gutter_max_author_length
13508 .map(|max_author_length| {
13509 // Length of the author name, but also space for the commit hash,
13510 // the spacing and the timestamp.
13511 let max_char_count = max_author_length
13512 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13513 + 7 // length of commit sha
13514 + 14 // length of max relative timestamp ("60 minutes ago")
13515 + 4; // gaps and margins
13516
13517 em_advance * max_char_count
13518 });
13519
13520 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13521 left_padding += if show_code_actions || show_runnables {
13522 em_width * 3.0
13523 } else if show_git_gutter && show_line_numbers {
13524 em_width * 2.0
13525 } else if show_git_gutter || show_line_numbers {
13526 em_width
13527 } else {
13528 px(0.)
13529 };
13530
13531 let right_padding = if gutter_settings.folds && show_line_numbers {
13532 em_width * 4.0
13533 } else if gutter_settings.folds {
13534 em_width * 3.0
13535 } else if show_line_numbers {
13536 em_width
13537 } else {
13538 px(0.)
13539 };
13540
13541 GutterDimensions {
13542 left_padding,
13543 right_padding,
13544 width: line_gutter_width + left_padding + right_padding,
13545 margin: -descent,
13546 git_blame_entries_width,
13547 }
13548 }
13549
13550 pub fn render_fold_toggle(
13551 &self,
13552 buffer_row: MultiBufferRow,
13553 row_contains_cursor: bool,
13554 editor: View<Editor>,
13555 cx: &mut WindowContext,
13556 ) -> Option<AnyElement> {
13557 let folded = self.is_line_folded(buffer_row);
13558
13559 if let Some(crease) = self
13560 .crease_snapshot
13561 .query_row(buffer_row, &self.buffer_snapshot)
13562 {
13563 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13564 if folded {
13565 editor.update(cx, |editor, cx| {
13566 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13567 });
13568 } else {
13569 editor.update(cx, |editor, cx| {
13570 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13571 });
13572 }
13573 });
13574
13575 Some((crease.render_toggle)(
13576 buffer_row,
13577 folded,
13578 toggle_callback,
13579 cx,
13580 ))
13581 } else if folded
13582 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13583 {
13584 Some(
13585 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13586 .selected(folded)
13587 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13588 if folded {
13589 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13590 } else {
13591 this.fold_at(&FoldAt { buffer_row }, cx);
13592 }
13593 }))
13594 .into_any_element(),
13595 )
13596 } else {
13597 None
13598 }
13599 }
13600
13601 pub fn render_crease_trailer(
13602 &self,
13603 buffer_row: MultiBufferRow,
13604 cx: &mut WindowContext,
13605 ) -> Option<AnyElement> {
13606 let folded = self.is_line_folded(buffer_row);
13607 let crease = self
13608 .crease_snapshot
13609 .query_row(buffer_row, &self.buffer_snapshot)?;
13610 Some((crease.render_trailer)(buffer_row, folded, cx))
13611 }
13612}
13613
13614impl Deref for EditorSnapshot {
13615 type Target = DisplaySnapshot;
13616
13617 fn deref(&self) -> &Self::Target {
13618 &self.display_snapshot
13619 }
13620}
13621
13622#[derive(Clone, Debug, PartialEq, Eq)]
13623pub enum EditorEvent {
13624 InputIgnored {
13625 text: Arc<str>,
13626 },
13627 InputHandled {
13628 utf16_range_to_replace: Option<Range<isize>>,
13629 text: Arc<str>,
13630 },
13631 ExcerptsAdded {
13632 buffer: Model<Buffer>,
13633 predecessor: ExcerptId,
13634 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13635 },
13636 ExcerptsRemoved {
13637 ids: Vec<ExcerptId>,
13638 },
13639 ExcerptsEdited {
13640 ids: Vec<ExcerptId>,
13641 },
13642 ExcerptsExpanded {
13643 ids: Vec<ExcerptId>,
13644 },
13645 BufferEdited,
13646 Edited {
13647 transaction_id: clock::Lamport,
13648 },
13649 Reparsed(BufferId),
13650 Focused,
13651 FocusedIn,
13652 Blurred,
13653 DirtyChanged,
13654 Saved,
13655 TitleChanged,
13656 DiffBaseChanged,
13657 SelectionsChanged {
13658 local: bool,
13659 },
13660 ScrollPositionChanged {
13661 local: bool,
13662 autoscroll: bool,
13663 },
13664 Closed,
13665 TransactionUndone {
13666 transaction_id: clock::Lamport,
13667 },
13668 TransactionBegun {
13669 transaction_id: clock::Lamport,
13670 },
13671 Reloaded,
13672 CursorShapeChanged,
13673}
13674
13675impl EventEmitter<EditorEvent> for Editor {}
13676
13677impl FocusableView for Editor {
13678 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13679 self.focus_handle.clone()
13680 }
13681}
13682
13683impl Render for Editor {
13684 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13685 let settings = ThemeSettings::get_global(cx);
13686
13687 let mut text_style = match self.mode {
13688 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13689 color: cx.theme().colors().editor_foreground,
13690 font_family: settings.ui_font.family.clone(),
13691 font_features: settings.ui_font.features.clone(),
13692 font_fallbacks: settings.ui_font.fallbacks.clone(),
13693 font_size: rems(0.875).into(),
13694 font_weight: settings.ui_font.weight,
13695 line_height: relative(settings.buffer_line_height.value()),
13696 ..Default::default()
13697 },
13698 EditorMode::Full => TextStyle {
13699 color: cx.theme().colors().editor_foreground,
13700 font_family: settings.buffer_font.family.clone(),
13701 font_features: settings.buffer_font.features.clone(),
13702 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13703 font_size: settings.buffer_font_size(cx).into(),
13704 font_weight: settings.buffer_font.weight,
13705 line_height: relative(settings.buffer_line_height.value()),
13706 ..Default::default()
13707 },
13708 };
13709 if let Some(text_style_refinement) = &self.text_style_refinement {
13710 text_style.refine(text_style_refinement)
13711 }
13712
13713 let background = match self.mode {
13714 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13715 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13716 EditorMode::Full => cx.theme().colors().editor_background,
13717 };
13718
13719 EditorElement::new(
13720 cx.view(),
13721 EditorStyle {
13722 background,
13723 local_player: cx.theme().players().local(),
13724 text: text_style,
13725 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13726 syntax: cx.theme().syntax().clone(),
13727 status: cx.theme().status().clone(),
13728 inlay_hints_style: make_inlay_hints_style(cx),
13729 suggestions_style: HighlightStyle {
13730 color: Some(cx.theme().status().predictive),
13731 ..HighlightStyle::default()
13732 },
13733 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13734 },
13735 )
13736 }
13737}
13738
13739impl ViewInputHandler for Editor {
13740 fn text_for_range(
13741 &mut self,
13742 range_utf16: Range<usize>,
13743 cx: &mut ViewContext<Self>,
13744 ) -> Option<String> {
13745 Some(
13746 self.buffer
13747 .read(cx)
13748 .read(cx)
13749 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13750 .collect(),
13751 )
13752 }
13753
13754 fn selected_text_range(
13755 &mut self,
13756 ignore_disabled_input: bool,
13757 cx: &mut ViewContext<Self>,
13758 ) -> Option<UTF16Selection> {
13759 // Prevent the IME menu from appearing when holding down an alphabetic key
13760 // while input is disabled.
13761 if !ignore_disabled_input && !self.input_enabled {
13762 return None;
13763 }
13764
13765 let selection = self.selections.newest::<OffsetUtf16>(cx);
13766 let range = selection.range();
13767
13768 Some(UTF16Selection {
13769 range: range.start.0..range.end.0,
13770 reversed: selection.reversed,
13771 })
13772 }
13773
13774 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13775 let snapshot = self.buffer.read(cx).read(cx);
13776 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13777 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13778 }
13779
13780 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13781 self.clear_highlights::<InputComposition>(cx);
13782 self.ime_transaction.take();
13783 }
13784
13785 fn replace_text_in_range(
13786 &mut self,
13787 range_utf16: Option<Range<usize>>,
13788 text: &str,
13789 cx: &mut ViewContext<Self>,
13790 ) {
13791 if !self.input_enabled {
13792 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13793 return;
13794 }
13795
13796 self.transact(cx, |this, cx| {
13797 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13798 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13799 Some(this.selection_replacement_ranges(range_utf16, cx))
13800 } else {
13801 this.marked_text_ranges(cx)
13802 };
13803
13804 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13805 let newest_selection_id = this.selections.newest_anchor().id;
13806 this.selections
13807 .all::<OffsetUtf16>(cx)
13808 .iter()
13809 .zip(ranges_to_replace.iter())
13810 .find_map(|(selection, range)| {
13811 if selection.id == newest_selection_id {
13812 Some(
13813 (range.start.0 as isize - selection.head().0 as isize)
13814 ..(range.end.0 as isize - selection.head().0 as isize),
13815 )
13816 } else {
13817 None
13818 }
13819 })
13820 });
13821
13822 cx.emit(EditorEvent::InputHandled {
13823 utf16_range_to_replace: range_to_replace,
13824 text: text.into(),
13825 });
13826
13827 if let Some(new_selected_ranges) = new_selected_ranges {
13828 this.change_selections(None, cx, |selections| {
13829 selections.select_ranges(new_selected_ranges)
13830 });
13831 this.backspace(&Default::default(), cx);
13832 }
13833
13834 this.handle_input(text, cx);
13835 });
13836
13837 if let Some(transaction) = self.ime_transaction {
13838 self.buffer.update(cx, |buffer, cx| {
13839 buffer.group_until_transaction(transaction, cx);
13840 });
13841 }
13842
13843 self.unmark_text(cx);
13844 }
13845
13846 fn replace_and_mark_text_in_range(
13847 &mut self,
13848 range_utf16: Option<Range<usize>>,
13849 text: &str,
13850 new_selected_range_utf16: Option<Range<usize>>,
13851 cx: &mut ViewContext<Self>,
13852 ) {
13853 if !self.input_enabled {
13854 return;
13855 }
13856
13857 let transaction = self.transact(cx, |this, cx| {
13858 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13859 let snapshot = this.buffer.read(cx).read(cx);
13860 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13861 for marked_range in &mut marked_ranges {
13862 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13863 marked_range.start.0 += relative_range_utf16.start;
13864 marked_range.start =
13865 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13866 marked_range.end =
13867 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13868 }
13869 }
13870 Some(marked_ranges)
13871 } else if let Some(range_utf16) = range_utf16 {
13872 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13873 Some(this.selection_replacement_ranges(range_utf16, cx))
13874 } else {
13875 None
13876 };
13877
13878 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13879 let newest_selection_id = this.selections.newest_anchor().id;
13880 this.selections
13881 .all::<OffsetUtf16>(cx)
13882 .iter()
13883 .zip(ranges_to_replace.iter())
13884 .find_map(|(selection, range)| {
13885 if selection.id == newest_selection_id {
13886 Some(
13887 (range.start.0 as isize - selection.head().0 as isize)
13888 ..(range.end.0 as isize - selection.head().0 as isize),
13889 )
13890 } else {
13891 None
13892 }
13893 })
13894 });
13895
13896 cx.emit(EditorEvent::InputHandled {
13897 utf16_range_to_replace: range_to_replace,
13898 text: text.into(),
13899 });
13900
13901 if let Some(ranges) = ranges_to_replace {
13902 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13903 }
13904
13905 let marked_ranges = {
13906 let snapshot = this.buffer.read(cx).read(cx);
13907 this.selections
13908 .disjoint_anchors()
13909 .iter()
13910 .map(|selection| {
13911 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13912 })
13913 .collect::<Vec<_>>()
13914 };
13915
13916 if text.is_empty() {
13917 this.unmark_text(cx);
13918 } else {
13919 this.highlight_text::<InputComposition>(
13920 marked_ranges.clone(),
13921 HighlightStyle {
13922 underline: Some(UnderlineStyle {
13923 thickness: px(1.),
13924 color: None,
13925 wavy: false,
13926 }),
13927 ..Default::default()
13928 },
13929 cx,
13930 );
13931 }
13932
13933 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13934 let use_autoclose = this.use_autoclose;
13935 let use_auto_surround = this.use_auto_surround;
13936 this.set_use_autoclose(false);
13937 this.set_use_auto_surround(false);
13938 this.handle_input(text, cx);
13939 this.set_use_autoclose(use_autoclose);
13940 this.set_use_auto_surround(use_auto_surround);
13941
13942 if let Some(new_selected_range) = new_selected_range_utf16 {
13943 let snapshot = this.buffer.read(cx).read(cx);
13944 let new_selected_ranges = marked_ranges
13945 .into_iter()
13946 .map(|marked_range| {
13947 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13948 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13949 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13950 snapshot.clip_offset_utf16(new_start, Bias::Left)
13951 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13952 })
13953 .collect::<Vec<_>>();
13954
13955 drop(snapshot);
13956 this.change_selections(None, cx, |selections| {
13957 selections.select_ranges(new_selected_ranges)
13958 });
13959 }
13960 });
13961
13962 self.ime_transaction = self.ime_transaction.or(transaction);
13963 if let Some(transaction) = self.ime_transaction {
13964 self.buffer.update(cx, |buffer, cx| {
13965 buffer.group_until_transaction(transaction, cx);
13966 });
13967 }
13968
13969 if self.text_highlights::<InputComposition>(cx).is_none() {
13970 self.ime_transaction.take();
13971 }
13972 }
13973
13974 fn bounds_for_range(
13975 &mut self,
13976 range_utf16: Range<usize>,
13977 element_bounds: gpui::Bounds<Pixels>,
13978 cx: &mut ViewContext<Self>,
13979 ) -> Option<gpui::Bounds<Pixels>> {
13980 let text_layout_details = self.text_layout_details(cx);
13981 let style = &text_layout_details.editor_style;
13982 let font_id = cx.text_system().resolve_font(&style.text.font());
13983 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13984 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13985
13986 let em_width = cx
13987 .text_system()
13988 .typographic_bounds(font_id, font_size, 'm')
13989 .unwrap()
13990 .size
13991 .width;
13992
13993 let snapshot = self.snapshot(cx);
13994 let scroll_position = snapshot.scroll_position();
13995 let scroll_left = scroll_position.x * em_width;
13996
13997 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13998 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13999 + self.gutter_dimensions.width;
14000 let y = line_height * (start.row().as_f32() - scroll_position.y);
14001
14002 Some(Bounds {
14003 origin: element_bounds.origin + point(x, y),
14004 size: size(em_width, line_height),
14005 })
14006 }
14007}
14008
14009trait SelectionExt {
14010 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14011 fn spanned_rows(
14012 &self,
14013 include_end_if_at_line_start: bool,
14014 map: &DisplaySnapshot,
14015 ) -> Range<MultiBufferRow>;
14016}
14017
14018impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14019 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14020 let start = self
14021 .start
14022 .to_point(&map.buffer_snapshot)
14023 .to_display_point(map);
14024 let end = self
14025 .end
14026 .to_point(&map.buffer_snapshot)
14027 .to_display_point(map);
14028 if self.reversed {
14029 end..start
14030 } else {
14031 start..end
14032 }
14033 }
14034
14035 fn spanned_rows(
14036 &self,
14037 include_end_if_at_line_start: bool,
14038 map: &DisplaySnapshot,
14039 ) -> Range<MultiBufferRow> {
14040 let start = self.start.to_point(&map.buffer_snapshot);
14041 let mut end = self.end.to_point(&map.buffer_snapshot);
14042 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14043 end.row -= 1;
14044 }
14045
14046 let buffer_start = map.prev_line_boundary(start).0;
14047 let buffer_end = map.next_line_boundary(end).0;
14048 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14049 }
14050}
14051
14052impl<T: InvalidationRegion> InvalidationStack<T> {
14053 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14054 where
14055 S: Clone + ToOffset,
14056 {
14057 while let Some(region) = self.last() {
14058 let all_selections_inside_invalidation_ranges =
14059 if selections.len() == region.ranges().len() {
14060 selections
14061 .iter()
14062 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14063 .all(|(selection, invalidation_range)| {
14064 let head = selection.head().to_offset(buffer);
14065 invalidation_range.start <= head && invalidation_range.end >= head
14066 })
14067 } else {
14068 false
14069 };
14070
14071 if all_selections_inside_invalidation_ranges {
14072 break;
14073 } else {
14074 self.pop();
14075 }
14076 }
14077 }
14078}
14079
14080impl<T> Default for InvalidationStack<T> {
14081 fn default() -> Self {
14082 Self(Default::default())
14083 }
14084}
14085
14086impl<T> Deref for InvalidationStack<T> {
14087 type Target = Vec<T>;
14088
14089 fn deref(&self) -> &Self::Target {
14090 &self.0
14091 }
14092}
14093
14094impl<T> DerefMut for InvalidationStack<T> {
14095 fn deref_mut(&mut self) -> &mut Self::Target {
14096 &mut self.0
14097 }
14098}
14099
14100impl InvalidationRegion for SnippetState {
14101 fn ranges(&self) -> &[Range<Anchor>] {
14102 &self.ranges[self.active_index]
14103 }
14104}
14105
14106pub fn diagnostic_block_renderer(
14107 diagnostic: Diagnostic,
14108 max_message_rows: Option<u8>,
14109 allow_closing: bool,
14110 _is_valid: bool,
14111) -> RenderBlock {
14112 let (text_without_backticks, code_ranges) =
14113 highlight_diagnostic_message(&diagnostic, max_message_rows);
14114
14115 Box::new(move |cx: &mut BlockContext| {
14116 let group_id: SharedString = cx.block_id.to_string().into();
14117
14118 let mut text_style = cx.text_style().clone();
14119 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14120 let theme_settings = ThemeSettings::get_global(cx);
14121 text_style.font_family = theme_settings.buffer_font.family.clone();
14122 text_style.font_style = theme_settings.buffer_font.style;
14123 text_style.font_features = theme_settings.buffer_font.features.clone();
14124 text_style.font_weight = theme_settings.buffer_font.weight;
14125
14126 let multi_line_diagnostic = diagnostic.message.contains('\n');
14127
14128 let buttons = |diagnostic: &Diagnostic| {
14129 if multi_line_diagnostic {
14130 v_flex()
14131 } else {
14132 h_flex()
14133 }
14134 .when(allow_closing, |div| {
14135 div.children(diagnostic.is_primary.then(|| {
14136 IconButton::new("close-block", IconName::XCircle)
14137 .icon_color(Color::Muted)
14138 .size(ButtonSize::Compact)
14139 .style(ButtonStyle::Transparent)
14140 .visible_on_hover(group_id.clone())
14141 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14142 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14143 }))
14144 })
14145 .child(
14146 IconButton::new("copy-block", IconName::Copy)
14147 .icon_color(Color::Muted)
14148 .size(ButtonSize::Compact)
14149 .style(ButtonStyle::Transparent)
14150 .visible_on_hover(group_id.clone())
14151 .on_click({
14152 let message = diagnostic.message.clone();
14153 move |_click, cx| {
14154 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14155 }
14156 })
14157 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14158 )
14159 };
14160
14161 let icon_size = buttons(&diagnostic)
14162 .into_any_element()
14163 .layout_as_root(AvailableSpace::min_size(), cx);
14164
14165 h_flex()
14166 .id(cx.block_id)
14167 .group(group_id.clone())
14168 .relative()
14169 .size_full()
14170 .pl(cx.gutter_dimensions.width)
14171 .w(cx.max_width + cx.gutter_dimensions.width)
14172 .child(
14173 div()
14174 .flex()
14175 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14176 .flex_shrink(),
14177 )
14178 .child(buttons(&diagnostic))
14179 .child(div().flex().flex_shrink_0().child(
14180 StyledText::new(text_without_backticks.clone()).with_highlights(
14181 &text_style,
14182 code_ranges.iter().map(|range| {
14183 (
14184 range.clone(),
14185 HighlightStyle {
14186 font_weight: Some(FontWeight::BOLD),
14187 ..Default::default()
14188 },
14189 )
14190 }),
14191 ),
14192 ))
14193 .into_any_element()
14194 })
14195}
14196
14197pub fn highlight_diagnostic_message(
14198 diagnostic: &Diagnostic,
14199 mut max_message_rows: Option<u8>,
14200) -> (SharedString, Vec<Range<usize>>) {
14201 let mut text_without_backticks = String::new();
14202 let mut code_ranges = Vec::new();
14203
14204 if let Some(source) = &diagnostic.source {
14205 text_without_backticks.push_str(source);
14206 code_ranges.push(0..source.len());
14207 text_without_backticks.push_str(": ");
14208 }
14209
14210 let mut prev_offset = 0;
14211 let mut in_code_block = false;
14212 let has_row_limit = max_message_rows.is_some();
14213 let mut newline_indices = diagnostic
14214 .message
14215 .match_indices('\n')
14216 .filter(|_| has_row_limit)
14217 .map(|(ix, _)| ix)
14218 .fuse()
14219 .peekable();
14220
14221 for (quote_ix, _) in diagnostic
14222 .message
14223 .match_indices('`')
14224 .chain([(diagnostic.message.len(), "")])
14225 {
14226 let mut first_newline_ix = None;
14227 let mut last_newline_ix = None;
14228 while let Some(newline_ix) = newline_indices.peek() {
14229 if *newline_ix < quote_ix {
14230 if first_newline_ix.is_none() {
14231 first_newline_ix = Some(*newline_ix);
14232 }
14233 last_newline_ix = Some(*newline_ix);
14234
14235 if let Some(rows_left) = &mut max_message_rows {
14236 if *rows_left == 0 {
14237 break;
14238 } else {
14239 *rows_left -= 1;
14240 }
14241 }
14242 let _ = newline_indices.next();
14243 } else {
14244 break;
14245 }
14246 }
14247 let prev_len = text_without_backticks.len();
14248 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14249 text_without_backticks.push_str(new_text);
14250 if in_code_block {
14251 code_ranges.push(prev_len..text_without_backticks.len());
14252 }
14253 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14254 in_code_block = !in_code_block;
14255 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14256 text_without_backticks.push_str("...");
14257 break;
14258 }
14259 }
14260
14261 (text_without_backticks.into(), code_ranges)
14262}
14263
14264fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14265 match severity {
14266 DiagnosticSeverity::ERROR => colors.error,
14267 DiagnosticSeverity::WARNING => colors.warning,
14268 DiagnosticSeverity::INFORMATION => colors.info,
14269 DiagnosticSeverity::HINT => colors.info,
14270 _ => colors.ignored,
14271 }
14272}
14273
14274pub fn styled_runs_for_code_label<'a>(
14275 label: &'a CodeLabel,
14276 syntax_theme: &'a theme::SyntaxTheme,
14277) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14278 let fade_out = HighlightStyle {
14279 fade_out: Some(0.35),
14280 ..Default::default()
14281 };
14282
14283 let mut prev_end = label.filter_range.end;
14284 label
14285 .runs
14286 .iter()
14287 .enumerate()
14288 .flat_map(move |(ix, (range, highlight_id))| {
14289 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14290 style
14291 } else {
14292 return Default::default();
14293 };
14294 let mut muted_style = style;
14295 muted_style.highlight(fade_out);
14296
14297 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14298 if range.start >= label.filter_range.end {
14299 if range.start > prev_end {
14300 runs.push((prev_end..range.start, fade_out));
14301 }
14302 runs.push((range.clone(), muted_style));
14303 } else if range.end <= label.filter_range.end {
14304 runs.push((range.clone(), style));
14305 } else {
14306 runs.push((range.start..label.filter_range.end, style));
14307 runs.push((label.filter_range.end..range.end, muted_style));
14308 }
14309 prev_end = cmp::max(prev_end, range.end);
14310
14311 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14312 runs.push((prev_end..label.text.len(), fade_out));
14313 }
14314
14315 runs
14316 })
14317}
14318
14319pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14320 let mut prev_index = 0;
14321 let mut prev_codepoint: Option<char> = None;
14322 text.char_indices()
14323 .chain([(text.len(), '\0')])
14324 .filter_map(move |(index, codepoint)| {
14325 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14326 let is_boundary = index == text.len()
14327 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14328 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14329 if is_boundary {
14330 let chunk = &text[prev_index..index];
14331 prev_index = index;
14332 Some(chunk)
14333 } else {
14334 None
14335 }
14336 })
14337}
14338
14339pub trait RangeToAnchorExt: Sized {
14340 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14341
14342 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14343 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14344 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14345 }
14346}
14347
14348impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14349 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14350 let start_offset = self.start.to_offset(snapshot);
14351 let end_offset = self.end.to_offset(snapshot);
14352 if start_offset == end_offset {
14353 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14354 } else {
14355 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14356 }
14357 }
14358}
14359
14360pub trait RowExt {
14361 fn as_f32(&self) -> f32;
14362
14363 fn next_row(&self) -> Self;
14364
14365 fn previous_row(&self) -> Self;
14366
14367 fn minus(&self, other: Self) -> u32;
14368}
14369
14370impl RowExt for DisplayRow {
14371 fn as_f32(&self) -> f32 {
14372 self.0 as f32
14373 }
14374
14375 fn next_row(&self) -> Self {
14376 Self(self.0 + 1)
14377 }
14378
14379 fn previous_row(&self) -> Self {
14380 Self(self.0.saturating_sub(1))
14381 }
14382
14383 fn minus(&self, other: Self) -> u32 {
14384 self.0 - other.0
14385 }
14386}
14387
14388impl RowExt for MultiBufferRow {
14389 fn as_f32(&self) -> f32 {
14390 self.0 as f32
14391 }
14392
14393 fn next_row(&self) -> Self {
14394 Self(self.0 + 1)
14395 }
14396
14397 fn previous_row(&self) -> Self {
14398 Self(self.0.saturating_sub(1))
14399 }
14400
14401 fn minus(&self, other: Self) -> u32 {
14402 self.0 - other.0
14403 }
14404}
14405
14406trait RowRangeExt {
14407 type Row;
14408
14409 fn len(&self) -> usize;
14410
14411 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14412}
14413
14414impl RowRangeExt for Range<MultiBufferRow> {
14415 type Row = MultiBufferRow;
14416
14417 fn len(&self) -> usize {
14418 (self.end.0 - self.start.0) as usize
14419 }
14420
14421 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14422 (self.start.0..self.end.0).map(MultiBufferRow)
14423 }
14424}
14425
14426impl RowRangeExt for Range<DisplayRow> {
14427 type Row = DisplayRow;
14428
14429 fn len(&self) -> usize {
14430 (self.end.0 - self.start.0) as usize
14431 }
14432
14433 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14434 (self.start.0..self.end.0).map(DisplayRow)
14435 }
14436}
14437
14438fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14439 if hunk.diff_base_byte_range.is_empty() {
14440 DiffHunkStatus::Added
14441 } else if hunk.row_range.is_empty() {
14442 DiffHunkStatus::Removed
14443 } else {
14444 DiffHunkStatus::Modified
14445 }
14446}
14447
14448/// If select range has more than one line, we
14449/// just point the cursor to range.start.
14450fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14451 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14452 range
14453 } else {
14454 range.start..range.start
14455 }
14456}