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;
51use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
52pub(crate) use actions::*;
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use debounced_delay::DebouncedDelay;
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
65};
66pub use editor_settings_controls::*;
67use element::LineWithInvisibles;
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use futures::{future, FutureExt};
72use fuzzy::{StringMatch, StringMatchCandidate};
73use git::blame::GitBlame;
74use gpui::{
75 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
76 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
77 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
78 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
79 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
80 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
81 UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
82 VisualContext, WeakFocusHandle, WeakView, WindowContext,
83};
84use highlight_matching_bracket::refresh_matching_bracket_highlights;
85use hover_popover::{hide_hover, HoverState};
86pub(crate) use hunk_diff::HoveredHunk;
87use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
88use indent_guides::ActiveIndentGuidesState;
89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
90pub use inline_completion_provider::*;
91pub use items::MAX_TAB_TITLE_LEN;
92use itertools::Itertools;
93use language::{
94 language_settings::{self, all_language_settings, InlayHintSettings},
95 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
96 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
97 Point, Selection, SelectionGoal, TransactionId,
98};
99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
100use linked_editing_ranges::refresh_linked_ranges;
101pub use proposed_changes_editor::{
102 ProposedChangesBuffer, ProposedChangesEditor, ProposedChangesEditorToolbar,
103};
104use similar::{ChangeTag, TextDiff};
105use task::{ResolvedTask, TaskTemplate, TaskVariables};
106
107use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
108pub use lsp::CompletionContext;
109use lsp::{
110 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
111 LanguageServerId,
112};
113use mouse_context_menu::MouseContextMenu;
114use movement::TextLayoutDetails;
115pub use multi_buffer::{
116 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
117 ToPoint,
118};
119use multi_buffer::{
120 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
121};
122use ordered_float::OrderedFloat;
123use parking_lot::{Mutex, RwLock};
124use project::{
125 lsp_store::FormatTrigger,
126 project_settings::{GitGutterSetting, ProjectSettings},
127 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
128 LocationLink, Project, ProjectPath, ProjectTransaction, TaskSourceKind,
129};
130use rand::prelude::*;
131use rpc::{proto::*, ErrorExt};
132use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
133use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
134use serde::{Deserialize, Serialize};
135use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
136use smallvec::SmallVec;
137use snippet::Snippet;
138use std::{
139 any::TypeId,
140 borrow::Cow,
141 cell::RefCell,
142 cmp::{self, Ordering, Reverse},
143 mem,
144 num::NonZeroU32,
145 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
146 path::{Path, PathBuf},
147 rc::Rc,
148 sync::Arc,
149 time::{Duration, Instant},
150};
151pub use sum_tree::Bias;
152use sum_tree::TreeMap;
153use text::{BufferId, OffsetUtf16, Rope};
154use theme::{
155 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
156 ThemeColors, ThemeSettings,
157};
158use ui::{
159 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
160 ListItem, Popover, PopoverMenuHandle, Tooltip,
161};
162use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
163use workspace::item::{ItemHandle, PreviewTabsSettings};
164use workspace::notifications::{DetachAndPromptErr, NotificationId};
165use workspace::{
166 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
167};
168use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
169
170use crate::hover_links::find_url;
171use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
172
173pub const FILE_HEADER_HEIGHT: u32 = 1;
174pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
175pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
176pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
177const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
178const MAX_LINE_LEN: usize = 1024;
179const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
180const MAX_SELECTION_HISTORY_LEN: usize = 1024;
181pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
182#[doc(hidden)]
183pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
184#[doc(hidden)]
185pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
186
187pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
188pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
189
190pub fn render_parsed_markdown(
191 element_id: impl Into<ElementId>,
192 parsed: &language::ParsedMarkdown,
193 editor_style: &EditorStyle,
194 workspace: Option<WeakView<Workspace>>,
195 cx: &mut WindowContext,
196) -> InteractiveText {
197 let code_span_background_color = cx
198 .theme()
199 .colors()
200 .editor_document_highlight_read_background;
201
202 let highlights = gpui::combine_highlights(
203 parsed.highlights.iter().filter_map(|(range, highlight)| {
204 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
205 Some((range.clone(), highlight))
206 }),
207 parsed
208 .regions
209 .iter()
210 .zip(&parsed.region_ranges)
211 .filter_map(|(region, range)| {
212 if region.code {
213 Some((
214 range.clone(),
215 HighlightStyle {
216 background_color: Some(code_span_background_color),
217 ..Default::default()
218 },
219 ))
220 } else {
221 None
222 }
223 }),
224 );
225
226 let mut links = Vec::new();
227 let mut link_ranges = Vec::new();
228 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
229 if let Some(link) = region.link.clone() {
230 links.push(link);
231 link_ranges.push(range.clone());
232 }
233 }
234
235 InteractiveText::new(
236 element_id,
237 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
238 )
239 .on_click(link_ranges, move |clicked_range_ix, cx| {
240 match &links[clicked_range_ix] {
241 markdown::Link::Web { url } => cx.open_url(url),
242 markdown::Link::Path { path } => {
243 if let Some(workspace) = &workspace {
244 _ = workspace.update(cx, |workspace, cx| {
245 workspace.open_abs_path(path.clone(), false, cx).detach();
246 });
247 }
248 }
249 }
250 })
251}
252
253#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
254pub(crate) enum InlayId {
255 Suggestion(usize),
256 Hint(usize),
257}
258
259impl InlayId {
260 fn id(&self) -> usize {
261 match self {
262 Self::Suggestion(id) => *id,
263 Self::Hint(id) => *id,
264 }
265 }
266}
267
268enum DiffRowHighlight {}
269enum DocumentHighlightRead {}
270enum DocumentHighlightWrite {}
271enum InputComposition {}
272
273#[derive(Copy, Clone, PartialEq, Eq)]
274pub enum Direction {
275 Prev,
276 Next,
277}
278
279#[derive(Debug, Copy, Clone, PartialEq, Eq)]
280pub enum Navigated {
281 Yes,
282 No,
283}
284
285impl Navigated {
286 pub fn from_bool(yes: bool) -> Navigated {
287 if yes {
288 Navigated::Yes
289 } else {
290 Navigated::No
291 }
292 }
293}
294
295pub fn init_settings(cx: &mut AppContext) {
296 EditorSettings::register(cx);
297}
298
299pub fn init(cx: &mut AppContext) {
300 init_settings(cx);
301
302 workspace::register_project_item::<Editor>(cx);
303 workspace::FollowableViewRegistry::register::<Editor>(cx);
304 workspace::register_serializable_item::<Editor>(cx);
305
306 cx.observe_new_views(
307 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
308 workspace.register_action(Editor::new_file);
309 workspace.register_action(Editor::new_file_vertical);
310 workspace.register_action(Editor::new_file_horizontal);
311 },
312 )
313 .detach();
314
315 cx.on_action(move |_: &workspace::NewFile, cx| {
316 let app_state = workspace::AppState::global(cx);
317 if let Some(app_state) = app_state.upgrade() {
318 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
319 Editor::new_file(workspace, &Default::default(), cx)
320 })
321 .detach();
322 }
323 });
324 cx.on_action(move |_: &workspace::NewWindow, cx| {
325 let app_state = workspace::AppState::global(cx);
326 if let Some(app_state) = app_state.upgrade() {
327 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
328 Editor::new_file(workspace, &Default::default(), cx)
329 })
330 .detach();
331 }
332 });
333}
334
335pub struct SearchWithinRange;
336
337trait InvalidationRegion {
338 fn ranges(&self) -> &[Range<Anchor>];
339}
340
341#[derive(Clone, Debug, PartialEq)]
342pub enum SelectPhase {
343 Begin {
344 position: DisplayPoint,
345 add: bool,
346 click_count: usize,
347 },
348 BeginColumnar {
349 position: DisplayPoint,
350 reset: bool,
351 goal_column: u32,
352 },
353 Extend {
354 position: DisplayPoint,
355 click_count: usize,
356 },
357 Update {
358 position: DisplayPoint,
359 goal_column: u32,
360 scroll_delta: gpui::Point<f32>,
361 },
362 End,
363}
364
365#[derive(Clone, Debug)]
366pub enum SelectMode {
367 Character,
368 Word(Range<Anchor>),
369 Line(Range<Anchor>),
370 All,
371}
372
373#[derive(Copy, Clone, PartialEq, Eq, Debug)]
374pub enum EditorMode {
375 SingleLine { auto_width: bool },
376 AutoHeight { max_lines: usize },
377 Full,
378}
379
380#[derive(Copy, Clone, Debug)]
381pub enum SoftWrap {
382 /// Prefer not to wrap at all.
383 ///
384 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
385 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
386 GitDiff,
387 /// Prefer a single line generally, unless an overly long line is encountered.
388 None,
389 /// Soft wrap lines that exceed the editor width.
390 EditorWidth,
391 /// Soft wrap lines at the preferred line length.
392 Column(u32),
393 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
394 Bounded(u32),
395}
396
397#[derive(Clone)]
398pub struct EditorStyle {
399 pub background: Hsla,
400 pub local_player: PlayerColor,
401 pub text: TextStyle,
402 pub scrollbar_width: Pixels,
403 pub syntax: Arc<SyntaxTheme>,
404 pub status: StatusColors,
405 pub inlay_hints_style: HighlightStyle,
406 pub suggestions_style: HighlightStyle,
407 pub unnecessary_code_fade: f32,
408}
409
410impl Default for EditorStyle {
411 fn default() -> Self {
412 Self {
413 background: Hsla::default(),
414 local_player: PlayerColor::default(),
415 text: TextStyle::default(),
416 scrollbar_width: Pixels::default(),
417 syntax: Default::default(),
418 // HACK: Status colors don't have a real default.
419 // We should look into removing the status colors from the editor
420 // style and retrieve them directly from the theme.
421 status: StatusColors::dark(),
422 inlay_hints_style: HighlightStyle::default(),
423 suggestions_style: HighlightStyle::default(),
424 unnecessary_code_fade: Default::default(),
425 }
426 }
427}
428
429pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
430 let show_background = all_language_settings(None, cx)
431 .language(None)
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 project: Option<Model<Project>>,
550 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
551 completion_provider: Option<Box<dyn CompletionProvider>>,
552 collaboration_hub: Option<Box<dyn CollaborationHub>>,
553 blink_manager: Model<BlinkManager>,
554 show_cursor_names: bool,
555 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
556 pub show_local_selections: bool,
557 mode: EditorMode,
558 show_breadcrumbs: bool,
559 show_gutter: bool,
560 show_line_numbers: Option<bool>,
561 use_relative_line_numbers: Option<bool>,
562 show_git_diff_gutter: Option<bool>,
563 show_code_actions: Option<bool>,
564 show_runnables: Option<bool>,
565 show_wrap_guides: Option<bool>,
566 show_indent_guides: Option<bool>,
567 placeholder_text: Option<Arc<str>>,
568 highlight_order: usize,
569 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
570 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
571 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
572 scrollbar_marker_state: ScrollbarMarkerState,
573 active_indent_guides_state: ActiveIndentGuidesState,
574 nav_history: Option<ItemNavHistory>,
575 context_menu: RwLock<Option<ContextMenu>>,
576 mouse_context_menu: Option<MouseContextMenu>,
577 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
578 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
579 signature_help_state: SignatureHelpState,
580 auto_signature_help: Option<bool>,
581 find_all_references_task_sources: Vec<Anchor>,
582 next_completion_id: CompletionId,
583 completion_documentation_pre_resolve_debounce: DebouncedDelay,
584 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
585 code_actions_task: Option<Task<Result<()>>>,
586 document_highlights_task: Option<Task<()>>,
587 linked_editing_range_task: Option<Task<Option<()>>>,
588 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
589 pending_rename: Option<RenameState>,
590 searchable: bool,
591 cursor_shape: CursorShape,
592 current_line_highlight: Option<CurrentLineHighlight>,
593 collapse_matches: bool,
594 autoindent_mode: Option<AutoindentMode>,
595 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
596 input_enabled: bool,
597 use_modal_editing: bool,
598 read_only: bool,
599 leader_peer_id: Option<PeerId>,
600 remote_id: Option<ViewId>,
601 hover_state: HoverState,
602 gutter_hovered: bool,
603 hovered_link_state: Option<HoveredLinkState>,
604 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
605 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
606 active_inline_completion: Option<CompletionState>,
607 // enable_inline_completions is a switch that Vim can use to disable
608 // inline completions based on its mode.
609 enable_inline_completions: bool,
610 show_inline_completions_override: Option<bool>,
611 inlay_hint_cache: InlayHintCache,
612 expanded_hunks: ExpandedHunks,
613 next_inlay_id: usize,
614 _subscriptions: Vec<Subscription>,
615 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
616 gutter_dimensions: GutterDimensions,
617 style: Option<EditorStyle>,
618 next_editor_action_id: EditorActionId,
619 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
620 use_autoclose: bool,
621 use_auto_surround: bool,
622 auto_replace_emoji_shortcode: bool,
623 show_git_blame_gutter: bool,
624 show_git_blame_inline: bool,
625 show_git_blame_inline_delay_task: Option<Task<()>>,
626 git_blame_inline_enabled: bool,
627 serialize_dirty_buffers: bool,
628 show_selection_menu: Option<bool>,
629 blame: Option<Model<GitBlame>>,
630 blame_subscription: Option<Subscription>,
631 custom_context_menu: Option<
632 Box<
633 dyn 'static
634 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
635 >,
636 >,
637 last_bounds: Option<Bounds<Pixels>>,
638 expect_bounds_change: Option<Bounds<Pixels>>,
639 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
640 tasks_update_task: Option<Task<()>>,
641 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
642 file_header_size: u32,
643 breadcrumb_header: Option<String>,
644 focused_block: Option<FocusedBlock>,
645 next_scroll_position: NextScrollCursorCenterTopBottom,
646 addons: HashMap<TypeId, Box<dyn Addon>>,
647 _scroll_cursor_center_top_bottom_task: Task<()>,
648}
649
650#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
651enum NextScrollCursorCenterTopBottom {
652 #[default]
653 Center,
654 Top,
655 Bottom,
656}
657
658impl NextScrollCursorCenterTopBottom {
659 fn next(&self) -> Self {
660 match self {
661 Self::Center => Self::Top,
662 Self::Top => Self::Bottom,
663 Self::Bottom => Self::Center,
664 }
665 }
666}
667
668#[derive(Clone)]
669pub struct EditorSnapshot {
670 pub mode: EditorMode,
671 show_gutter: bool,
672 show_line_numbers: Option<bool>,
673 show_git_diff_gutter: Option<bool>,
674 show_code_actions: Option<bool>,
675 show_runnables: Option<bool>,
676 git_blame_gutter_max_author_length: Option<usize>,
677 pub display_snapshot: DisplaySnapshot,
678 pub placeholder_text: Option<Arc<str>>,
679 is_focused: bool,
680 scroll_anchor: ScrollAnchor,
681 ongoing_scroll: OngoingScroll,
682 current_line_highlight: CurrentLineHighlight,
683 gutter_hovered: bool,
684}
685
686const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
687
688#[derive(Default, Debug, Clone, Copy)]
689pub struct GutterDimensions {
690 pub left_padding: Pixels,
691 pub right_padding: Pixels,
692 pub width: Pixels,
693 pub margin: Pixels,
694 pub git_blame_entries_width: Option<Pixels>,
695}
696
697impl GutterDimensions {
698 /// The full width of the space taken up by the gutter.
699 pub fn full_width(&self) -> Pixels {
700 self.margin + self.width
701 }
702
703 /// The width of the space reserved for the fold indicators,
704 /// use alongside 'justify_end' and `gutter_width` to
705 /// right align content with the line numbers
706 pub fn fold_area_width(&self) -> Pixels {
707 self.margin + self.right_padding
708 }
709}
710
711#[derive(Debug)]
712pub struct RemoteSelection {
713 pub replica_id: ReplicaId,
714 pub selection: Selection<Anchor>,
715 pub cursor_shape: CursorShape,
716 pub peer_id: PeerId,
717 pub line_mode: bool,
718 pub participant_index: Option<ParticipantIndex>,
719 pub user_name: Option<SharedString>,
720}
721
722#[derive(Clone, Debug)]
723struct SelectionHistoryEntry {
724 selections: Arc<[Selection<Anchor>]>,
725 select_next_state: Option<SelectNextState>,
726 select_prev_state: Option<SelectNextState>,
727 add_selections_state: Option<AddSelectionsState>,
728}
729
730enum SelectionHistoryMode {
731 Normal,
732 Undoing,
733 Redoing,
734}
735
736#[derive(Clone, PartialEq, Eq, Hash)]
737struct HoveredCursor {
738 replica_id: u16,
739 selection_id: usize,
740}
741
742impl Default for SelectionHistoryMode {
743 fn default() -> Self {
744 Self::Normal
745 }
746}
747
748#[derive(Default)]
749struct SelectionHistory {
750 #[allow(clippy::type_complexity)]
751 selections_by_transaction:
752 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
753 mode: SelectionHistoryMode,
754 undo_stack: VecDeque<SelectionHistoryEntry>,
755 redo_stack: VecDeque<SelectionHistoryEntry>,
756}
757
758impl SelectionHistory {
759 fn insert_transaction(
760 &mut self,
761 transaction_id: TransactionId,
762 selections: Arc<[Selection<Anchor>]>,
763 ) {
764 self.selections_by_transaction
765 .insert(transaction_id, (selections, None));
766 }
767
768 #[allow(clippy::type_complexity)]
769 fn transaction(
770 &self,
771 transaction_id: TransactionId,
772 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
773 self.selections_by_transaction.get(&transaction_id)
774 }
775
776 #[allow(clippy::type_complexity)]
777 fn transaction_mut(
778 &mut self,
779 transaction_id: TransactionId,
780 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
781 self.selections_by_transaction.get_mut(&transaction_id)
782 }
783
784 fn push(&mut self, entry: SelectionHistoryEntry) {
785 if !entry.selections.is_empty() {
786 match self.mode {
787 SelectionHistoryMode::Normal => {
788 self.push_undo(entry);
789 self.redo_stack.clear();
790 }
791 SelectionHistoryMode::Undoing => self.push_redo(entry),
792 SelectionHistoryMode::Redoing => self.push_undo(entry),
793 }
794 }
795 }
796
797 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
798 if self
799 .undo_stack
800 .back()
801 .map_or(true, |e| e.selections != entry.selections)
802 {
803 self.undo_stack.push_back(entry);
804 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
805 self.undo_stack.pop_front();
806 }
807 }
808 }
809
810 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
811 if self
812 .redo_stack
813 .back()
814 .map_or(true, |e| e.selections != entry.selections)
815 {
816 self.redo_stack.push_back(entry);
817 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
818 self.redo_stack.pop_front();
819 }
820 }
821 }
822}
823
824struct RowHighlight {
825 index: usize,
826 range: Range<Anchor>,
827 color: Hsla,
828 should_autoscroll: bool,
829}
830
831#[derive(Clone, Debug)]
832struct AddSelectionsState {
833 above: bool,
834 stack: Vec<usize>,
835}
836
837#[derive(Clone)]
838struct SelectNextState {
839 query: AhoCorasick,
840 wordwise: bool,
841 done: bool,
842}
843
844impl std::fmt::Debug for SelectNextState {
845 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
846 f.debug_struct(std::any::type_name::<Self>())
847 .field("wordwise", &self.wordwise)
848 .field("done", &self.done)
849 .finish()
850 }
851}
852
853#[derive(Debug)]
854struct AutocloseRegion {
855 selection_id: usize,
856 range: Range<Anchor>,
857 pair: BracketPair,
858}
859
860#[derive(Debug)]
861struct SnippetState {
862 ranges: Vec<Vec<Range<Anchor>>>,
863 active_index: usize,
864}
865
866#[doc(hidden)]
867pub struct RenameState {
868 pub range: Range<Anchor>,
869 pub old_name: Arc<str>,
870 pub editor: View<Editor>,
871 block_id: CustomBlockId,
872}
873
874struct InvalidationStack<T>(Vec<T>);
875
876struct RegisteredInlineCompletionProvider {
877 provider: Arc<dyn InlineCompletionProviderHandle>,
878 _subscription: Subscription,
879}
880
881enum ContextMenu {
882 Completions(CompletionsMenu),
883 CodeActions(CodeActionsMenu),
884}
885
886impl ContextMenu {
887 fn select_first(
888 &mut self,
889 provider: Option<&dyn CompletionProvider>,
890 cx: &mut ViewContext<Editor>,
891 ) -> bool {
892 if self.visible() {
893 match self {
894 ContextMenu::Completions(menu) => menu.select_first(provider, cx),
895 ContextMenu::CodeActions(menu) => menu.select_first(cx),
896 }
897 true
898 } else {
899 false
900 }
901 }
902
903 fn select_prev(
904 &mut self,
905 provider: Option<&dyn CompletionProvider>,
906 cx: &mut ViewContext<Editor>,
907 ) -> bool {
908 if self.visible() {
909 match self {
910 ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
911 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
912 }
913 true
914 } else {
915 false
916 }
917 }
918
919 fn select_next(
920 &mut self,
921 provider: Option<&dyn CompletionProvider>,
922 cx: &mut ViewContext<Editor>,
923 ) -> bool {
924 if self.visible() {
925 match self {
926 ContextMenu::Completions(menu) => menu.select_next(provider, cx),
927 ContextMenu::CodeActions(menu) => menu.select_next(cx),
928 }
929 true
930 } else {
931 false
932 }
933 }
934
935 fn select_last(
936 &mut self,
937 provider: Option<&dyn CompletionProvider>,
938 cx: &mut ViewContext<Editor>,
939 ) -> bool {
940 if self.visible() {
941 match self {
942 ContextMenu::Completions(menu) => menu.select_last(provider, cx),
943 ContextMenu::CodeActions(menu) => menu.select_last(cx),
944 }
945 true
946 } else {
947 false
948 }
949 }
950
951 fn visible(&self) -> bool {
952 match self {
953 ContextMenu::Completions(menu) => menu.visible(),
954 ContextMenu::CodeActions(menu) => menu.visible(),
955 }
956 }
957
958 fn render(
959 &self,
960 cursor_position: DisplayPoint,
961 style: &EditorStyle,
962 max_height: Pixels,
963 workspace: Option<WeakView<Workspace>>,
964 cx: &mut ViewContext<Editor>,
965 ) -> (ContextMenuOrigin, AnyElement) {
966 match self {
967 ContextMenu::Completions(menu) => (
968 ContextMenuOrigin::EditorPoint(cursor_position),
969 menu.render(style, max_height, workspace, cx),
970 ),
971 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
972 }
973 }
974}
975
976enum ContextMenuOrigin {
977 EditorPoint(DisplayPoint),
978 GutterIndicator(DisplayRow),
979}
980
981#[derive(Clone)]
982struct CompletionsMenu {
983 id: CompletionId,
984 sort_completions: bool,
985 initial_position: Anchor,
986 buffer: Model<Buffer>,
987 completions: Arc<RwLock<Box<[Completion]>>>,
988 match_candidates: Arc<[StringMatchCandidate]>,
989 matches: Arc<[StringMatch]>,
990 selected_item: usize,
991 scroll_handle: UniformListScrollHandle,
992 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
993}
994
995impl CompletionsMenu {
996 fn select_first(
997 &mut self,
998 provider: Option<&dyn CompletionProvider>,
999 cx: &mut ViewContext<Editor>,
1000 ) {
1001 self.selected_item = 0;
1002 self.scroll_handle.scroll_to_item(self.selected_item);
1003 self.attempt_resolve_selected_completion_documentation(provider, cx);
1004 cx.notify();
1005 }
1006
1007 fn select_prev(
1008 &mut self,
1009 provider: Option<&dyn CompletionProvider>,
1010 cx: &mut ViewContext<Editor>,
1011 ) {
1012 if self.selected_item > 0 {
1013 self.selected_item -= 1;
1014 } else {
1015 self.selected_item = self.matches.len() - 1;
1016 }
1017 self.scroll_handle.scroll_to_item(self.selected_item);
1018 self.attempt_resolve_selected_completion_documentation(provider, cx);
1019 cx.notify();
1020 }
1021
1022 fn select_next(
1023 &mut self,
1024 provider: Option<&dyn CompletionProvider>,
1025 cx: &mut ViewContext<Editor>,
1026 ) {
1027 if self.selected_item + 1 < self.matches.len() {
1028 self.selected_item += 1;
1029 } else {
1030 self.selected_item = 0;
1031 }
1032 self.scroll_handle.scroll_to_item(self.selected_item);
1033 self.attempt_resolve_selected_completion_documentation(provider, cx);
1034 cx.notify();
1035 }
1036
1037 fn select_last(
1038 &mut self,
1039 provider: Option<&dyn CompletionProvider>,
1040 cx: &mut ViewContext<Editor>,
1041 ) {
1042 self.selected_item = self.matches.len() - 1;
1043 self.scroll_handle.scroll_to_item(self.selected_item);
1044 self.attempt_resolve_selected_completion_documentation(provider, cx);
1045 cx.notify();
1046 }
1047
1048 fn pre_resolve_completion_documentation(
1049 buffer: Model<Buffer>,
1050 completions: Arc<RwLock<Box<[Completion]>>>,
1051 matches: Arc<[StringMatch]>,
1052 editor: &Editor,
1053 cx: &mut ViewContext<Editor>,
1054 ) -> Task<()> {
1055 let settings = EditorSettings::get_global(cx);
1056 if !settings.show_completion_documentation {
1057 return Task::ready(());
1058 }
1059
1060 let Some(provider) = editor.completion_provider.as_ref() else {
1061 return Task::ready(());
1062 };
1063
1064 let resolve_task = provider.resolve_completions(
1065 buffer,
1066 matches.iter().map(|m| m.candidate_id).collect(),
1067 completions.clone(),
1068 cx,
1069 );
1070
1071 cx.spawn(move |this, mut cx| async move {
1072 if let Some(true) = resolve_task.await.log_err() {
1073 this.update(&mut cx, |_, cx| cx.notify()).ok();
1074 }
1075 })
1076 }
1077
1078 fn attempt_resolve_selected_completion_documentation(
1079 &mut self,
1080 provider: Option<&dyn CompletionProvider>,
1081 cx: &mut ViewContext<Editor>,
1082 ) {
1083 let settings = EditorSettings::get_global(cx);
1084 if !settings.show_completion_documentation {
1085 return;
1086 }
1087
1088 let completion_index = self.matches[self.selected_item].candidate_id;
1089 let Some(provider) = provider else {
1090 return;
1091 };
1092
1093 let resolve_task = provider.resolve_completions(
1094 self.buffer.clone(),
1095 vec![completion_index],
1096 self.completions.clone(),
1097 cx,
1098 );
1099
1100 let delay_ms =
1101 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1102 let delay = Duration::from_millis(delay_ms);
1103
1104 self.selected_completion_documentation_resolve_debounce
1105 .lock()
1106 .fire_new(delay, cx, |_, cx| {
1107 cx.spawn(move |this, mut cx| async move {
1108 if let Some(true) = resolve_task.await.log_err() {
1109 this.update(&mut cx, |_, cx| cx.notify()).ok();
1110 }
1111 })
1112 });
1113 }
1114
1115 fn visible(&self) -> bool {
1116 !self.matches.is_empty()
1117 }
1118
1119 fn render(
1120 &self,
1121 style: &EditorStyle,
1122 max_height: Pixels,
1123 workspace: Option<WeakView<Workspace>>,
1124 cx: &mut ViewContext<Editor>,
1125 ) -> AnyElement {
1126 let settings = EditorSettings::get_global(cx);
1127 let show_completion_documentation = settings.show_completion_documentation;
1128
1129 let widest_completion_ix = self
1130 .matches
1131 .iter()
1132 .enumerate()
1133 .max_by_key(|(_, mat)| {
1134 let completions = self.completions.read();
1135 let completion = &completions[mat.candidate_id];
1136 let documentation = &completion.documentation;
1137
1138 let mut len = completion.label.text.chars().count();
1139 if let Some(Documentation::SingleLine(text)) = documentation {
1140 if show_completion_documentation {
1141 len += text.chars().count();
1142 }
1143 }
1144
1145 len
1146 })
1147 .map(|(ix, _)| ix);
1148
1149 let completions = self.completions.clone();
1150 let matches = self.matches.clone();
1151 let selected_item = self.selected_item;
1152 let style = style.clone();
1153
1154 let multiline_docs = if show_completion_documentation {
1155 let mat = &self.matches[selected_item];
1156 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1157 Some(Documentation::MultiLinePlainText(text)) => {
1158 Some(div().child(SharedString::from(text.clone())))
1159 }
1160 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1161 Some(div().child(render_parsed_markdown(
1162 "completions_markdown",
1163 parsed,
1164 &style,
1165 workspace,
1166 cx,
1167 )))
1168 }
1169 _ => None,
1170 };
1171 multiline_docs.map(|div| {
1172 div.id("multiline_docs")
1173 .max_h(max_height)
1174 .flex_1()
1175 .px_1p5()
1176 .py_1()
1177 .min_w(px(260.))
1178 .max_w(px(640.))
1179 .w(px(500.))
1180 .overflow_y_scroll()
1181 .occlude()
1182 })
1183 } else {
1184 None
1185 };
1186
1187 let list = uniform_list(
1188 cx.view().clone(),
1189 "completions",
1190 matches.len(),
1191 move |_editor, range, cx| {
1192 let start_ix = range.start;
1193 let completions_guard = completions.read();
1194
1195 matches[range]
1196 .iter()
1197 .enumerate()
1198 .map(|(ix, mat)| {
1199 let item_ix = start_ix + ix;
1200 let candidate_id = mat.candidate_id;
1201 let completion = &completions_guard[candidate_id];
1202
1203 let documentation = if show_completion_documentation {
1204 &completion.documentation
1205 } else {
1206 &None
1207 };
1208
1209 let highlights = gpui::combine_highlights(
1210 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1211 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1212 |(range, mut highlight)| {
1213 // Ignore font weight for syntax highlighting, as we'll use it
1214 // for fuzzy matches.
1215 highlight.font_weight = None;
1216
1217 if completion.lsp_completion.deprecated.unwrap_or(false) {
1218 highlight.strikethrough = Some(StrikethroughStyle {
1219 thickness: 1.0.into(),
1220 ..Default::default()
1221 });
1222 highlight.color = Some(cx.theme().colors().text_muted);
1223 }
1224
1225 (range, highlight)
1226 },
1227 ),
1228 );
1229 let completion_label = StyledText::new(completion.label.text.clone())
1230 .with_highlights(&style.text, highlights);
1231 let documentation_label =
1232 if let Some(Documentation::SingleLine(text)) = documentation {
1233 if text.trim().is_empty() {
1234 None
1235 } else {
1236 Some(
1237 Label::new(text.clone())
1238 .ml_4()
1239 .size(LabelSize::Small)
1240 .color(Color::Muted),
1241 )
1242 }
1243 } else {
1244 None
1245 };
1246
1247 let color_swatch = completion
1248 .color()
1249 .map(|color| div().size_4().bg(color).rounded_sm());
1250
1251 div().min_w(px(220.)).max_w(px(540.)).child(
1252 ListItem::new(mat.candidate_id)
1253 .inset(true)
1254 .selected(item_ix == selected_item)
1255 .on_click(cx.listener(move |editor, _event, cx| {
1256 cx.stop_propagation();
1257 if let Some(task) = editor.confirm_completion(
1258 &ConfirmCompletion {
1259 item_ix: Some(item_ix),
1260 },
1261 cx,
1262 ) {
1263 task.detach_and_log_err(cx)
1264 }
1265 }))
1266 .start_slot::<Div>(color_swatch)
1267 .child(h_flex().overflow_hidden().child(completion_label))
1268 .end_slot::<Label>(documentation_label),
1269 )
1270 })
1271 .collect()
1272 },
1273 )
1274 .occlude()
1275 .max_h(max_height)
1276 .track_scroll(self.scroll_handle.clone())
1277 .with_width_from_item(widest_completion_ix)
1278 .with_sizing_behavior(ListSizingBehavior::Infer);
1279
1280 Popover::new()
1281 .child(list)
1282 .when_some(multiline_docs, |popover, multiline_docs| {
1283 popover.aside(multiline_docs)
1284 })
1285 .into_any_element()
1286 }
1287
1288 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1289 let mut matches = if let Some(query) = query {
1290 fuzzy::match_strings(
1291 &self.match_candidates,
1292 query,
1293 query.chars().any(|c| c.is_uppercase()),
1294 100,
1295 &Default::default(),
1296 executor,
1297 )
1298 .await
1299 } else {
1300 self.match_candidates
1301 .iter()
1302 .enumerate()
1303 .map(|(candidate_id, candidate)| StringMatch {
1304 candidate_id,
1305 score: Default::default(),
1306 positions: Default::default(),
1307 string: candidate.string.clone(),
1308 })
1309 .collect()
1310 };
1311
1312 // Remove all candidates where the query's start does not match the start of any word in the candidate
1313 if let Some(query) = query {
1314 if let Some(query_start) = query.chars().next() {
1315 matches.retain(|string_match| {
1316 split_words(&string_match.string).any(|word| {
1317 // Check that the first codepoint of the word as lowercase matches the first
1318 // codepoint of the query as lowercase
1319 word.chars()
1320 .flat_map(|codepoint| codepoint.to_lowercase())
1321 .zip(query_start.to_lowercase())
1322 .all(|(word_cp, query_cp)| word_cp == query_cp)
1323 })
1324 });
1325 }
1326 }
1327
1328 let completions = self.completions.read();
1329 if self.sort_completions {
1330 matches.sort_unstable_by_key(|mat| {
1331 // We do want to strike a balance here between what the language server tells us
1332 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1333 // `Creat` and there is a local variable called `CreateComponent`).
1334 // So what we do is: we bucket all matches into two buckets
1335 // - Strong matches
1336 // - Weak matches
1337 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1338 // and the Weak matches are the rest.
1339 //
1340 // For the strong matches, we sort by the language-servers score first and for the weak
1341 // matches, we prefer our fuzzy finder first.
1342 //
1343 // The thinking behind that: it's useless to take the sort_text the language-server gives
1344 // us into account when it's obviously a bad match.
1345
1346 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1347 enum MatchScore<'a> {
1348 Strong {
1349 sort_text: Option<&'a str>,
1350 score: Reverse<OrderedFloat<f64>>,
1351 sort_key: (usize, &'a str),
1352 },
1353 Weak {
1354 score: Reverse<OrderedFloat<f64>>,
1355 sort_text: Option<&'a str>,
1356 sort_key: (usize, &'a str),
1357 },
1358 }
1359
1360 let completion = &completions[mat.candidate_id];
1361 let sort_key = completion.sort_key();
1362 let sort_text = completion.lsp_completion.sort_text.as_deref();
1363 let score = Reverse(OrderedFloat(mat.score));
1364
1365 if mat.score >= 0.2 {
1366 MatchScore::Strong {
1367 sort_text,
1368 score,
1369 sort_key,
1370 }
1371 } else {
1372 MatchScore::Weak {
1373 score,
1374 sort_text,
1375 sort_key,
1376 }
1377 }
1378 });
1379 }
1380
1381 for mat in &mut matches {
1382 let completion = &completions[mat.candidate_id];
1383 mat.string.clone_from(&completion.label.text);
1384 for position in &mut mat.positions {
1385 *position += completion.label.filter_range.start;
1386 }
1387 }
1388 drop(completions);
1389
1390 self.matches = matches.into();
1391 self.selected_item = 0;
1392 }
1393}
1394
1395struct AvailableCodeAction {
1396 excerpt_id: ExcerptId,
1397 action: CodeAction,
1398 provider: Arc<dyn CodeActionProvider>,
1399}
1400
1401#[derive(Clone)]
1402struct CodeActionContents {
1403 tasks: Option<Arc<ResolvedTasks>>,
1404 actions: Option<Arc<[AvailableCodeAction]>>,
1405}
1406
1407impl CodeActionContents {
1408 fn len(&self) -> usize {
1409 match (&self.tasks, &self.actions) {
1410 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1411 (Some(tasks), None) => tasks.templates.len(),
1412 (None, Some(actions)) => actions.len(),
1413 (None, None) => 0,
1414 }
1415 }
1416
1417 fn is_empty(&self) -> bool {
1418 match (&self.tasks, &self.actions) {
1419 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1420 (Some(tasks), None) => tasks.templates.is_empty(),
1421 (None, Some(actions)) => actions.is_empty(),
1422 (None, None) => true,
1423 }
1424 }
1425
1426 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1427 self.tasks
1428 .iter()
1429 .flat_map(|tasks| {
1430 tasks
1431 .templates
1432 .iter()
1433 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1434 })
1435 .chain(self.actions.iter().flat_map(|actions| {
1436 actions.iter().map(|available| CodeActionsItem::CodeAction {
1437 excerpt_id: available.excerpt_id,
1438 action: available.action.clone(),
1439 provider: available.provider.clone(),
1440 })
1441 }))
1442 }
1443 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1444 match (&self.tasks, &self.actions) {
1445 (Some(tasks), Some(actions)) => {
1446 if index < tasks.templates.len() {
1447 tasks
1448 .templates
1449 .get(index)
1450 .cloned()
1451 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1452 } else {
1453 actions.get(index - tasks.templates.len()).map(|available| {
1454 CodeActionsItem::CodeAction {
1455 excerpt_id: available.excerpt_id,
1456 action: available.action.clone(),
1457 provider: available.provider.clone(),
1458 }
1459 })
1460 }
1461 }
1462 (Some(tasks), None) => tasks
1463 .templates
1464 .get(index)
1465 .cloned()
1466 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1467 (None, Some(actions)) => {
1468 actions
1469 .get(index)
1470 .map(|available| CodeActionsItem::CodeAction {
1471 excerpt_id: available.excerpt_id,
1472 action: available.action.clone(),
1473 provider: available.provider.clone(),
1474 })
1475 }
1476 (None, None) => None,
1477 }
1478 }
1479}
1480
1481#[allow(clippy::large_enum_variant)]
1482#[derive(Clone)]
1483enum CodeActionsItem {
1484 Task(TaskSourceKind, ResolvedTask),
1485 CodeAction {
1486 excerpt_id: ExcerptId,
1487 action: CodeAction,
1488 provider: Arc<dyn CodeActionProvider>,
1489 },
1490}
1491
1492impl CodeActionsItem {
1493 fn as_task(&self) -> Option<&ResolvedTask> {
1494 let Self::Task(_, task) = self else {
1495 return None;
1496 };
1497 Some(task)
1498 }
1499 fn as_code_action(&self) -> Option<&CodeAction> {
1500 let Self::CodeAction { action, .. } = self else {
1501 return None;
1502 };
1503 Some(action)
1504 }
1505 fn label(&self) -> String {
1506 match self {
1507 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1508 Self::Task(_, task) => task.resolved_label.clone(),
1509 }
1510 }
1511}
1512
1513struct CodeActionsMenu {
1514 actions: CodeActionContents,
1515 buffer: Model<Buffer>,
1516 selected_item: usize,
1517 scroll_handle: UniformListScrollHandle,
1518 deployed_from_indicator: Option<DisplayRow>,
1519}
1520
1521impl CodeActionsMenu {
1522 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1523 self.selected_item = 0;
1524 self.scroll_handle.scroll_to_item(self.selected_item);
1525 cx.notify()
1526 }
1527
1528 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1529 if self.selected_item > 0 {
1530 self.selected_item -= 1;
1531 } else {
1532 self.selected_item = self.actions.len() - 1;
1533 }
1534 self.scroll_handle.scroll_to_item(self.selected_item);
1535 cx.notify();
1536 }
1537
1538 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1539 if self.selected_item + 1 < self.actions.len() {
1540 self.selected_item += 1;
1541 } else {
1542 self.selected_item = 0;
1543 }
1544 self.scroll_handle.scroll_to_item(self.selected_item);
1545 cx.notify();
1546 }
1547
1548 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1549 self.selected_item = self.actions.len() - 1;
1550 self.scroll_handle.scroll_to_item(self.selected_item);
1551 cx.notify()
1552 }
1553
1554 fn visible(&self) -> bool {
1555 !self.actions.is_empty()
1556 }
1557
1558 fn render(
1559 &self,
1560 cursor_position: DisplayPoint,
1561 _style: &EditorStyle,
1562 max_height: Pixels,
1563 cx: &mut ViewContext<Editor>,
1564 ) -> (ContextMenuOrigin, AnyElement) {
1565 let actions = self.actions.clone();
1566 let selected_item = self.selected_item;
1567 let element = uniform_list(
1568 cx.view().clone(),
1569 "code_actions_menu",
1570 self.actions.len(),
1571 move |_this, range, cx| {
1572 actions
1573 .iter()
1574 .skip(range.start)
1575 .take(range.end - range.start)
1576 .enumerate()
1577 .map(|(ix, action)| {
1578 let item_ix = range.start + ix;
1579 let selected = selected_item == item_ix;
1580 let colors = cx.theme().colors();
1581 div()
1582 .px_1()
1583 .rounded_md()
1584 .text_color(colors.text)
1585 .when(selected, |style| {
1586 style
1587 .bg(colors.element_active)
1588 .text_color(colors.text_accent)
1589 })
1590 .hover(|style| {
1591 style
1592 .bg(colors.element_hover)
1593 .text_color(colors.text_accent)
1594 })
1595 .whitespace_nowrap()
1596 .when_some(action.as_code_action(), |this, action| {
1597 this.on_mouse_down(
1598 MouseButton::Left,
1599 cx.listener(move |editor, _, cx| {
1600 cx.stop_propagation();
1601 if let Some(task) = editor.confirm_code_action(
1602 &ConfirmCodeAction {
1603 item_ix: Some(item_ix),
1604 },
1605 cx,
1606 ) {
1607 task.detach_and_log_err(cx)
1608 }
1609 }),
1610 )
1611 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1612 .child(SharedString::from(action.lsp_action.title.clone()))
1613 })
1614 .when_some(action.as_task(), |this, task| {
1615 this.on_mouse_down(
1616 MouseButton::Left,
1617 cx.listener(move |editor, _, cx| {
1618 cx.stop_propagation();
1619 if let Some(task) = editor.confirm_code_action(
1620 &ConfirmCodeAction {
1621 item_ix: Some(item_ix),
1622 },
1623 cx,
1624 ) {
1625 task.detach_and_log_err(cx)
1626 }
1627 }),
1628 )
1629 .child(SharedString::from(task.resolved_label.clone()))
1630 })
1631 })
1632 .collect()
1633 },
1634 )
1635 .elevation_1(cx)
1636 .p_1()
1637 .max_h(max_height)
1638 .occlude()
1639 .track_scroll(self.scroll_handle.clone())
1640 .with_width_from_item(
1641 self.actions
1642 .iter()
1643 .enumerate()
1644 .max_by_key(|(_, action)| match action {
1645 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1646 CodeActionsItem::CodeAction { action, .. } => {
1647 action.lsp_action.title.chars().count()
1648 }
1649 })
1650 .map(|(ix, _)| ix),
1651 )
1652 .with_sizing_behavior(ListSizingBehavior::Infer)
1653 .into_any_element();
1654
1655 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1656 ContextMenuOrigin::GutterIndicator(row)
1657 } else {
1658 ContextMenuOrigin::EditorPoint(cursor_position)
1659 };
1660
1661 (cursor_position, element)
1662 }
1663}
1664
1665#[derive(Debug)]
1666struct ActiveDiagnosticGroup {
1667 primary_range: Range<Anchor>,
1668 primary_message: String,
1669 group_id: usize,
1670 blocks: HashMap<CustomBlockId, Diagnostic>,
1671 is_valid: bool,
1672}
1673
1674#[derive(Serialize, Deserialize, Clone, Debug)]
1675pub struct ClipboardSelection {
1676 pub len: usize,
1677 pub is_entire_line: bool,
1678 pub first_line_indent: u32,
1679}
1680
1681#[derive(Debug)]
1682pub(crate) struct NavigationData {
1683 cursor_anchor: Anchor,
1684 cursor_position: Point,
1685 scroll_anchor: ScrollAnchor,
1686 scroll_top_row: u32,
1687}
1688
1689#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1690pub enum GotoDefinitionKind {
1691 Symbol,
1692 Declaration,
1693 Type,
1694 Implementation,
1695}
1696
1697#[derive(Debug, Clone)]
1698enum InlayHintRefreshReason {
1699 Toggle(bool),
1700 SettingsChange(InlayHintSettings),
1701 NewLinesShown,
1702 BufferEdited(HashSet<Arc<Language>>),
1703 RefreshRequested,
1704 ExcerptsRemoved(Vec<ExcerptId>),
1705}
1706
1707impl InlayHintRefreshReason {
1708 fn description(&self) -> &'static str {
1709 match self {
1710 Self::Toggle(_) => "toggle",
1711 Self::SettingsChange(_) => "settings change",
1712 Self::NewLinesShown => "new lines shown",
1713 Self::BufferEdited(_) => "buffer edited",
1714 Self::RefreshRequested => "refresh requested",
1715 Self::ExcerptsRemoved(_) => "excerpts removed",
1716 }
1717 }
1718}
1719
1720pub(crate) struct FocusedBlock {
1721 id: BlockId,
1722 focus_handle: WeakFocusHandle,
1723}
1724
1725impl Editor {
1726 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1727 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1728 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1729 Self::new(
1730 EditorMode::SingleLine { auto_width: false },
1731 buffer,
1732 None,
1733 false,
1734 cx,
1735 )
1736 }
1737
1738 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1739 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1740 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1741 Self::new(EditorMode::Full, buffer, None, false, cx)
1742 }
1743
1744 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1745 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1746 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1747 Self::new(
1748 EditorMode::SingleLine { auto_width: true },
1749 buffer,
1750 None,
1751 false,
1752 cx,
1753 )
1754 }
1755
1756 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1757 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1758 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1759 Self::new(
1760 EditorMode::AutoHeight { max_lines },
1761 buffer,
1762 None,
1763 false,
1764 cx,
1765 )
1766 }
1767
1768 pub fn for_buffer(
1769 buffer: Model<Buffer>,
1770 project: Option<Model<Project>>,
1771 cx: &mut ViewContext<Self>,
1772 ) -> Self {
1773 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1774 Self::new(EditorMode::Full, buffer, project, false, cx)
1775 }
1776
1777 pub fn for_multibuffer(
1778 buffer: Model<MultiBuffer>,
1779 project: Option<Model<Project>>,
1780 show_excerpt_controls: bool,
1781 cx: &mut ViewContext<Self>,
1782 ) -> Self {
1783 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1784 }
1785
1786 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1787 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1788 let mut clone = Self::new(
1789 self.mode,
1790 self.buffer.clone(),
1791 self.project.clone(),
1792 show_excerpt_controls,
1793 cx,
1794 );
1795 self.display_map.update(cx, |display_map, cx| {
1796 let snapshot = display_map.snapshot(cx);
1797 clone.display_map.update(cx, |display_map, cx| {
1798 display_map.set_state(&snapshot, cx);
1799 });
1800 });
1801 clone.selections.clone_state(&self.selections);
1802 clone.scroll_manager.clone_state(&self.scroll_manager);
1803 clone.searchable = self.searchable;
1804 clone
1805 }
1806
1807 pub fn new(
1808 mode: EditorMode,
1809 buffer: Model<MultiBuffer>,
1810 project: Option<Model<Project>>,
1811 show_excerpt_controls: bool,
1812 cx: &mut ViewContext<Self>,
1813 ) -> Self {
1814 let style = cx.text_style();
1815 let font_size = style.font_size.to_pixels(cx.rem_size());
1816 let editor = cx.view().downgrade();
1817 let fold_placeholder = FoldPlaceholder {
1818 constrain_width: true,
1819 render: Arc::new(move |fold_id, fold_range, cx| {
1820 let editor = editor.clone();
1821 div()
1822 .id(fold_id)
1823 .bg(cx.theme().colors().ghost_element_background)
1824 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1825 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1826 .rounded_sm()
1827 .size_full()
1828 .cursor_pointer()
1829 .child("⋯")
1830 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1831 .on_click(move |_, cx| {
1832 editor
1833 .update(cx, |editor, cx| {
1834 editor.unfold_ranges(
1835 [fold_range.start..fold_range.end],
1836 true,
1837 false,
1838 cx,
1839 );
1840 cx.stop_propagation();
1841 })
1842 .ok();
1843 })
1844 .into_any()
1845 }),
1846 merge_adjacent: true,
1847 };
1848 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
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_size,
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 file_header_size,
2041 tasks: Default::default(),
2042 _subscriptions: vec![
2043 cx.observe(&buffer, Self::on_buffer_changed),
2044 cx.subscribe(&buffer, Self::on_buffer_event),
2045 cx.observe(&display_map, Self::on_display_map_changed),
2046 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2047 cx.observe_global::<SettingsStore>(Self::settings_changed),
2048 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2049 cx.observe_window_activation(|editor, cx| {
2050 let active = cx.is_window_active();
2051 editor.blink_manager.update(cx, |blink_manager, cx| {
2052 if active {
2053 blink_manager.enable(cx);
2054 } else {
2055 blink_manager.disable(cx);
2056 }
2057 });
2058 }),
2059 ],
2060 tasks_update_task: None,
2061 linked_edit_ranges: Default::default(),
2062 previous_search_ranges: None,
2063 breadcrumb_header: None,
2064 focused_block: None,
2065 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2066 addons: HashMap::default(),
2067 _scroll_cursor_center_top_bottom_task: Task::ready(()),
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.read(cx).language_at(buffer_position).as_ref(),
4254 buffer.read(cx).file(),
4255 cx,
4256 );
4257 if !settings.use_on_type_format {
4258 return None;
4259 }
4260
4261 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4262 // hence we do LSP request & edit on host side only — add formats to host's history.
4263 let push_to_lsp_host_history = true;
4264 // If this is not the host, append its history with new edits.
4265 let push_to_client_history = project.read(cx).is_via_collab();
4266
4267 let on_type_formatting = project.update(cx, |project, cx| {
4268 project.on_type_format(
4269 buffer.clone(),
4270 buffer_position,
4271 input,
4272 push_to_lsp_host_history,
4273 cx,
4274 )
4275 });
4276 Some(cx.spawn(|editor, mut cx| async move {
4277 if let Some(transaction) = on_type_formatting.await? {
4278 if push_to_client_history {
4279 buffer
4280 .update(&mut cx, |buffer, _| {
4281 buffer.push_transaction(transaction, Instant::now());
4282 })
4283 .ok();
4284 }
4285 editor.update(&mut cx, |editor, cx| {
4286 editor.refresh_document_highlights(cx);
4287 })?;
4288 }
4289 Ok(())
4290 }))
4291 }
4292
4293 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4294 if self.pending_rename.is_some() {
4295 return;
4296 }
4297
4298 let Some(provider) = self.completion_provider.as_ref() else {
4299 return;
4300 };
4301
4302 let position = self.selections.newest_anchor().head();
4303 let (buffer, buffer_position) =
4304 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4305 output
4306 } else {
4307 return;
4308 };
4309
4310 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4311 let is_followup_invoke = {
4312 let context_menu_state = self.context_menu.read();
4313 matches!(
4314 context_menu_state.deref(),
4315 Some(ContextMenu::Completions(_))
4316 )
4317 };
4318 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4319 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4320 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4321 CompletionTriggerKind::TRIGGER_CHARACTER
4322 }
4323
4324 _ => CompletionTriggerKind::INVOKED,
4325 };
4326 let completion_context = CompletionContext {
4327 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4328 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4329 Some(String::from(trigger))
4330 } else {
4331 None
4332 }
4333 }),
4334 trigger_kind,
4335 };
4336 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4337 let sort_completions = provider.sort_completions();
4338
4339 let id = post_inc(&mut self.next_completion_id);
4340 let task = cx.spawn(|this, mut cx| {
4341 async move {
4342 this.update(&mut cx, |this, _| {
4343 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4344 })?;
4345 let completions = completions.await.log_err();
4346 let menu = if let Some(completions) = completions {
4347 let mut menu = CompletionsMenu {
4348 id,
4349 sort_completions,
4350 initial_position: position,
4351 match_candidates: completions
4352 .iter()
4353 .enumerate()
4354 .map(|(id, completion)| {
4355 StringMatchCandidate::new(
4356 id,
4357 completion.label.text[completion.label.filter_range.clone()]
4358 .into(),
4359 )
4360 })
4361 .collect(),
4362 buffer: buffer.clone(),
4363 completions: Arc::new(RwLock::new(completions.into())),
4364 matches: Vec::new().into(),
4365 selected_item: 0,
4366 scroll_handle: UniformListScrollHandle::new(),
4367 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4368 DebouncedDelay::new(),
4369 )),
4370 };
4371 menu.filter(query.as_deref(), cx.background_executor().clone())
4372 .await;
4373
4374 if menu.matches.is_empty() {
4375 None
4376 } else {
4377 this.update(&mut cx, |editor, cx| {
4378 let completions = menu.completions.clone();
4379 let matches = menu.matches.clone();
4380
4381 let delay_ms = EditorSettings::get_global(cx)
4382 .completion_documentation_secondary_query_debounce;
4383 let delay = Duration::from_millis(delay_ms);
4384 editor
4385 .completion_documentation_pre_resolve_debounce
4386 .fire_new(delay, cx, |editor, cx| {
4387 CompletionsMenu::pre_resolve_completion_documentation(
4388 buffer,
4389 completions,
4390 matches,
4391 editor,
4392 cx,
4393 )
4394 });
4395 })
4396 .ok();
4397 Some(menu)
4398 }
4399 } else {
4400 None
4401 };
4402
4403 this.update(&mut cx, |this, cx| {
4404 let mut context_menu = this.context_menu.write();
4405 match context_menu.as_ref() {
4406 None => {}
4407
4408 Some(ContextMenu::Completions(prev_menu)) => {
4409 if prev_menu.id > id {
4410 return;
4411 }
4412 }
4413
4414 _ => return,
4415 }
4416
4417 if this.focus_handle.is_focused(cx) && menu.is_some() {
4418 let menu = menu.unwrap();
4419 *context_menu = Some(ContextMenu::Completions(menu));
4420 drop(context_menu);
4421 this.discard_inline_completion(false, cx);
4422 cx.notify();
4423 } else if this.completion_tasks.len() <= 1 {
4424 // If there are no more completion tasks and the last menu was
4425 // empty, we should hide it. If it was already hidden, we should
4426 // also show the copilot completion when available.
4427 drop(context_menu);
4428 if this.hide_context_menu(cx).is_none() {
4429 this.update_visible_inline_completion(cx);
4430 }
4431 }
4432 })?;
4433
4434 Ok::<_, anyhow::Error>(())
4435 }
4436 .log_err()
4437 });
4438
4439 self.completion_tasks.push((id, task));
4440 }
4441
4442 pub fn confirm_completion(
4443 &mut self,
4444 action: &ConfirmCompletion,
4445 cx: &mut ViewContext<Self>,
4446 ) -> Option<Task<Result<()>>> {
4447 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4448 }
4449
4450 pub fn compose_completion(
4451 &mut self,
4452 action: &ComposeCompletion,
4453 cx: &mut ViewContext<Self>,
4454 ) -> Option<Task<Result<()>>> {
4455 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4456 }
4457
4458 fn do_completion(
4459 &mut self,
4460 item_ix: Option<usize>,
4461 intent: CompletionIntent,
4462 cx: &mut ViewContext<Editor>,
4463 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4464 use language::ToOffset as _;
4465
4466 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4467 menu
4468 } else {
4469 return None;
4470 };
4471
4472 let mat = completions_menu
4473 .matches
4474 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4475 let buffer_handle = completions_menu.buffer;
4476 let completions = completions_menu.completions.read();
4477 let completion = completions.get(mat.candidate_id)?;
4478 cx.stop_propagation();
4479
4480 let snippet;
4481 let text;
4482
4483 if completion.is_snippet() {
4484 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4485 text = snippet.as_ref().unwrap().text.clone();
4486 } else {
4487 snippet = None;
4488 text = completion.new_text.clone();
4489 };
4490 let selections = self.selections.all::<usize>(cx);
4491 let buffer = buffer_handle.read(cx);
4492 let old_range = completion.old_range.to_offset(buffer);
4493 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4494
4495 let newest_selection = self.selections.newest_anchor();
4496 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4497 return None;
4498 }
4499
4500 let lookbehind = newest_selection
4501 .start
4502 .text_anchor
4503 .to_offset(buffer)
4504 .saturating_sub(old_range.start);
4505 let lookahead = old_range
4506 .end
4507 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4508 let mut common_prefix_len = old_text
4509 .bytes()
4510 .zip(text.bytes())
4511 .take_while(|(a, b)| a == b)
4512 .count();
4513
4514 let snapshot = self.buffer.read(cx).snapshot(cx);
4515 let mut range_to_replace: Option<Range<isize>> = None;
4516 let mut ranges = Vec::new();
4517 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4518 for selection in &selections {
4519 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4520 let start = selection.start.saturating_sub(lookbehind);
4521 let end = selection.end + lookahead;
4522 if selection.id == newest_selection.id {
4523 range_to_replace = Some(
4524 ((start + common_prefix_len) as isize - selection.start as isize)
4525 ..(end as isize - selection.start as isize),
4526 );
4527 }
4528 ranges.push(start + common_prefix_len..end);
4529 } else {
4530 common_prefix_len = 0;
4531 ranges.clear();
4532 ranges.extend(selections.iter().map(|s| {
4533 if s.id == newest_selection.id {
4534 range_to_replace = Some(
4535 old_range.start.to_offset_utf16(&snapshot).0 as isize
4536 - selection.start as isize
4537 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4538 - selection.start as isize,
4539 );
4540 old_range.clone()
4541 } else {
4542 s.start..s.end
4543 }
4544 }));
4545 break;
4546 }
4547 if !self.linked_edit_ranges.is_empty() {
4548 let start_anchor = snapshot.anchor_before(selection.head());
4549 let end_anchor = snapshot.anchor_after(selection.tail());
4550 if let Some(ranges) = self
4551 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4552 {
4553 for (buffer, edits) in ranges {
4554 linked_edits.entry(buffer.clone()).or_default().extend(
4555 edits
4556 .into_iter()
4557 .map(|range| (range, text[common_prefix_len..].to_owned())),
4558 );
4559 }
4560 }
4561 }
4562 }
4563 let text = &text[common_prefix_len..];
4564
4565 cx.emit(EditorEvent::InputHandled {
4566 utf16_range_to_replace: range_to_replace,
4567 text: text.into(),
4568 });
4569
4570 self.transact(cx, |this, cx| {
4571 if let Some(mut snippet) = snippet {
4572 snippet.text = text.to_string();
4573 for tabstop in snippet.tabstops.iter_mut().flatten() {
4574 tabstop.start -= common_prefix_len as isize;
4575 tabstop.end -= common_prefix_len as isize;
4576 }
4577
4578 this.insert_snippet(&ranges, snippet, cx).log_err();
4579 } else {
4580 this.buffer.update(cx, |buffer, cx| {
4581 buffer.edit(
4582 ranges.iter().map(|range| (range.clone(), text)),
4583 this.autoindent_mode.clone(),
4584 cx,
4585 );
4586 });
4587 }
4588 for (buffer, edits) in linked_edits {
4589 buffer.update(cx, |buffer, cx| {
4590 let snapshot = buffer.snapshot();
4591 let edits = edits
4592 .into_iter()
4593 .map(|(range, text)| {
4594 use text::ToPoint as TP;
4595 let end_point = TP::to_point(&range.end, &snapshot);
4596 let start_point = TP::to_point(&range.start, &snapshot);
4597 (start_point..end_point, text)
4598 })
4599 .sorted_by_key(|(range, _)| range.start)
4600 .collect::<Vec<_>>();
4601 buffer.edit(edits, None, cx);
4602 })
4603 }
4604
4605 this.refresh_inline_completion(true, false, cx);
4606 });
4607
4608 let show_new_completions_on_confirm = completion
4609 .confirm
4610 .as_ref()
4611 .map_or(false, |confirm| confirm(intent, cx));
4612 if show_new_completions_on_confirm {
4613 self.show_completions(&ShowCompletions { trigger: None }, cx);
4614 }
4615
4616 let provider = self.completion_provider.as_ref()?;
4617 let apply_edits = provider.apply_additional_edits_for_completion(
4618 buffer_handle,
4619 completion.clone(),
4620 true,
4621 cx,
4622 );
4623
4624 let editor_settings = EditorSettings::get_global(cx);
4625 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4626 // After the code completion is finished, users often want to know what signatures are needed.
4627 // so we should automatically call signature_help
4628 self.show_signature_help(&ShowSignatureHelp, cx);
4629 }
4630
4631 Some(cx.foreground_executor().spawn(async move {
4632 apply_edits.await?;
4633 Ok(())
4634 }))
4635 }
4636
4637 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4638 let mut context_menu = self.context_menu.write();
4639 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4640 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4641 // Toggle if we're selecting the same one
4642 *context_menu = None;
4643 cx.notify();
4644 return;
4645 } else {
4646 // Otherwise, clear it and start a new one
4647 *context_menu = None;
4648 cx.notify();
4649 }
4650 }
4651 drop(context_menu);
4652 let snapshot = self.snapshot(cx);
4653 let deployed_from_indicator = action.deployed_from_indicator;
4654 let mut task = self.code_actions_task.take();
4655 let action = action.clone();
4656 cx.spawn(|editor, mut cx| async move {
4657 while let Some(prev_task) = task {
4658 prev_task.await.log_err();
4659 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4660 }
4661
4662 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4663 if editor.focus_handle.is_focused(cx) {
4664 let multibuffer_point = action
4665 .deployed_from_indicator
4666 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4667 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4668 let (buffer, buffer_row) = snapshot
4669 .buffer_snapshot
4670 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4671 .and_then(|(buffer_snapshot, range)| {
4672 editor
4673 .buffer
4674 .read(cx)
4675 .buffer(buffer_snapshot.remote_id())
4676 .map(|buffer| (buffer, range.start.row))
4677 })?;
4678 let (_, code_actions) = editor
4679 .available_code_actions
4680 .clone()
4681 .and_then(|(location, code_actions)| {
4682 let snapshot = location.buffer.read(cx).snapshot();
4683 let point_range = location.range.to_point(&snapshot);
4684 let point_range = point_range.start.row..=point_range.end.row;
4685 if point_range.contains(&buffer_row) {
4686 Some((location, code_actions))
4687 } else {
4688 None
4689 }
4690 })
4691 .unzip();
4692 let buffer_id = buffer.read(cx).remote_id();
4693 let tasks = editor
4694 .tasks
4695 .get(&(buffer_id, buffer_row))
4696 .map(|t| Arc::new(t.to_owned()));
4697 if tasks.is_none() && code_actions.is_none() {
4698 return None;
4699 }
4700
4701 editor.completion_tasks.clear();
4702 editor.discard_inline_completion(false, cx);
4703 let task_context =
4704 tasks
4705 .as_ref()
4706 .zip(editor.project.clone())
4707 .map(|(tasks, project)| {
4708 let position = Point::new(buffer_row, tasks.column);
4709 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4710 let location = Location {
4711 buffer: buffer.clone(),
4712 range: range_start..range_start,
4713 };
4714 // Fill in the environmental variables from the tree-sitter captures
4715 let mut captured_task_variables = TaskVariables::default();
4716 for (capture_name, value) in tasks.extra_variables.clone() {
4717 captured_task_variables.insert(
4718 task::VariableName::Custom(capture_name.into()),
4719 value.clone(),
4720 );
4721 }
4722 project.update(cx, |project, cx| {
4723 project.task_store().update(cx, |task_store, cx| {
4724 task_store.task_context_for_location(
4725 captured_task_variables,
4726 location,
4727 cx,
4728 )
4729 })
4730 })
4731 });
4732
4733 Some(cx.spawn(|editor, mut cx| async move {
4734 let task_context = match task_context {
4735 Some(task_context) => task_context.await,
4736 None => None,
4737 };
4738 let resolved_tasks =
4739 tasks.zip(task_context).map(|(tasks, task_context)| {
4740 Arc::new(ResolvedTasks {
4741 templates: tasks
4742 .templates
4743 .iter()
4744 .filter_map(|(kind, template)| {
4745 template
4746 .resolve_task(&kind.to_id_base(), &task_context)
4747 .map(|task| (kind.clone(), task))
4748 })
4749 .collect(),
4750 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4751 multibuffer_point.row,
4752 tasks.column,
4753 )),
4754 })
4755 });
4756 let spawn_straight_away = resolved_tasks
4757 .as_ref()
4758 .map_or(false, |tasks| tasks.templates.len() == 1)
4759 && code_actions
4760 .as_ref()
4761 .map_or(true, |actions| actions.is_empty());
4762 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4763 *editor.context_menu.write() =
4764 Some(ContextMenu::CodeActions(CodeActionsMenu {
4765 buffer,
4766 actions: CodeActionContents {
4767 tasks: resolved_tasks,
4768 actions: code_actions,
4769 },
4770 selected_item: Default::default(),
4771 scroll_handle: UniformListScrollHandle::default(),
4772 deployed_from_indicator,
4773 }));
4774 if spawn_straight_away {
4775 if let Some(task) = editor.confirm_code_action(
4776 &ConfirmCodeAction { item_ix: Some(0) },
4777 cx,
4778 ) {
4779 cx.notify();
4780 return task;
4781 }
4782 }
4783 cx.notify();
4784 Task::ready(Ok(()))
4785 }) {
4786 task.await
4787 } else {
4788 Ok(())
4789 }
4790 }))
4791 } else {
4792 Some(Task::ready(Ok(())))
4793 }
4794 })?;
4795 if let Some(task) = spawned_test_task {
4796 task.await?;
4797 }
4798
4799 Ok::<_, anyhow::Error>(())
4800 })
4801 .detach_and_log_err(cx);
4802 }
4803
4804 pub fn confirm_code_action(
4805 &mut self,
4806 action: &ConfirmCodeAction,
4807 cx: &mut ViewContext<Self>,
4808 ) -> Option<Task<Result<()>>> {
4809 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4810 menu
4811 } else {
4812 return None;
4813 };
4814 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4815 let action = actions_menu.actions.get(action_ix)?;
4816 let title = action.label();
4817 let buffer = actions_menu.buffer;
4818 let workspace = self.workspace()?;
4819
4820 match action {
4821 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4822 workspace.update(cx, |workspace, cx| {
4823 workspace::tasks::schedule_resolved_task(
4824 workspace,
4825 task_source_kind,
4826 resolved_task,
4827 false,
4828 cx,
4829 );
4830
4831 Some(Task::ready(Ok(())))
4832 })
4833 }
4834 CodeActionsItem::CodeAction {
4835 excerpt_id,
4836 action,
4837 provider,
4838 } => {
4839 let apply_code_action =
4840 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4841 let workspace = workspace.downgrade();
4842 Some(cx.spawn(|editor, cx| async move {
4843 let project_transaction = apply_code_action.await?;
4844 Self::open_project_transaction(
4845 &editor,
4846 workspace,
4847 project_transaction,
4848 title,
4849 cx,
4850 )
4851 .await
4852 }))
4853 }
4854 }
4855 }
4856
4857 pub async fn open_project_transaction(
4858 this: &WeakView<Editor>,
4859 workspace: WeakView<Workspace>,
4860 transaction: ProjectTransaction,
4861 title: String,
4862 mut cx: AsyncWindowContext,
4863 ) -> Result<()> {
4864 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4865 cx.update(|cx| {
4866 entries.sort_unstable_by_key(|(buffer, _)| {
4867 buffer.read(cx).file().map(|f| f.path().clone())
4868 });
4869 })?;
4870
4871 // If the project transaction's edits are all contained within this editor, then
4872 // avoid opening a new editor to display them.
4873
4874 if let Some((buffer, transaction)) = entries.first() {
4875 if entries.len() == 1 {
4876 let excerpt = this.update(&mut cx, |editor, cx| {
4877 editor
4878 .buffer()
4879 .read(cx)
4880 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4881 })?;
4882 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4883 if excerpted_buffer == *buffer {
4884 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4885 let excerpt_range = excerpt_range.to_offset(buffer);
4886 buffer
4887 .edited_ranges_for_transaction::<usize>(transaction)
4888 .all(|range| {
4889 excerpt_range.start <= range.start
4890 && excerpt_range.end >= range.end
4891 })
4892 })?;
4893
4894 if all_edits_within_excerpt {
4895 return Ok(());
4896 }
4897 }
4898 }
4899 }
4900 } else {
4901 return Ok(());
4902 }
4903
4904 let mut ranges_to_highlight = Vec::new();
4905 let excerpt_buffer = cx.new_model(|cx| {
4906 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4907 for (buffer_handle, transaction) in &entries {
4908 let buffer = buffer_handle.read(cx);
4909 ranges_to_highlight.extend(
4910 multibuffer.push_excerpts_with_context_lines(
4911 buffer_handle.clone(),
4912 buffer
4913 .edited_ranges_for_transaction::<usize>(transaction)
4914 .collect(),
4915 DEFAULT_MULTIBUFFER_CONTEXT,
4916 cx,
4917 ),
4918 );
4919 }
4920 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4921 multibuffer
4922 })?;
4923
4924 workspace.update(&mut cx, |workspace, cx| {
4925 let project = workspace.project().clone();
4926 let editor =
4927 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4928 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4929 editor.update(cx, |editor, cx| {
4930 editor.highlight_background::<Self>(
4931 &ranges_to_highlight,
4932 |theme| theme.editor_highlighted_line_background,
4933 cx,
4934 );
4935 });
4936 })?;
4937
4938 Ok(())
4939 }
4940
4941 pub fn clear_code_action_providers(&mut self) {
4942 self.code_action_providers.clear();
4943 self.available_code_actions.take();
4944 }
4945
4946 pub fn push_code_action_provider(
4947 &mut self,
4948 provider: Arc<dyn CodeActionProvider>,
4949 cx: &mut ViewContext<Self>,
4950 ) {
4951 self.code_action_providers.push(provider);
4952 self.refresh_code_actions(cx);
4953 }
4954
4955 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4956 let buffer = self.buffer.read(cx);
4957 let newest_selection = self.selections.newest_anchor().clone();
4958 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4959 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4960 if start_buffer != end_buffer {
4961 return None;
4962 }
4963
4964 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4965 cx.background_executor()
4966 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4967 .await;
4968
4969 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4970 let providers = this.code_action_providers.clone();
4971 let tasks = this
4972 .code_action_providers
4973 .iter()
4974 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4975 .collect::<Vec<_>>();
4976 (providers, tasks)
4977 })?;
4978
4979 let mut actions = Vec::new();
4980 for (provider, provider_actions) in
4981 providers.into_iter().zip(future::join_all(tasks).await)
4982 {
4983 if let Some(provider_actions) = provider_actions.log_err() {
4984 actions.extend(provider_actions.into_iter().map(|action| {
4985 AvailableCodeAction {
4986 excerpt_id: newest_selection.start.excerpt_id,
4987 action,
4988 provider: provider.clone(),
4989 }
4990 }));
4991 }
4992 }
4993
4994 this.update(&mut cx, |this, cx| {
4995 this.available_code_actions = if actions.is_empty() {
4996 None
4997 } else {
4998 Some((
4999 Location {
5000 buffer: start_buffer,
5001 range: start..end,
5002 },
5003 actions.into(),
5004 ))
5005 };
5006 cx.notify();
5007 })
5008 }));
5009 None
5010 }
5011
5012 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5013 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5014 self.show_git_blame_inline = false;
5015
5016 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5017 cx.background_executor().timer(delay).await;
5018
5019 this.update(&mut cx, |this, cx| {
5020 this.show_git_blame_inline = true;
5021 cx.notify();
5022 })
5023 .log_err();
5024 }));
5025 }
5026 }
5027
5028 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5029 if self.pending_rename.is_some() {
5030 return None;
5031 }
5032
5033 let provider = self.semantics_provider.clone()?;
5034 let buffer = self.buffer.read(cx);
5035 let newest_selection = self.selections.newest_anchor().clone();
5036 let cursor_position = newest_selection.head();
5037 let (cursor_buffer, cursor_buffer_position) =
5038 buffer.text_anchor_for_position(cursor_position, cx)?;
5039 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5040 if cursor_buffer != tail_buffer {
5041 return None;
5042 }
5043
5044 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5045 cx.background_executor()
5046 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5047 .await;
5048
5049 let highlights = if let Some(highlights) = cx
5050 .update(|cx| {
5051 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5052 })
5053 .ok()
5054 .flatten()
5055 {
5056 highlights.await.log_err()
5057 } else {
5058 None
5059 };
5060
5061 if let Some(highlights) = highlights {
5062 this.update(&mut cx, |this, cx| {
5063 if this.pending_rename.is_some() {
5064 return;
5065 }
5066
5067 let buffer_id = cursor_position.buffer_id;
5068 let buffer = this.buffer.read(cx);
5069 if !buffer
5070 .text_anchor_for_position(cursor_position, cx)
5071 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5072 {
5073 return;
5074 }
5075
5076 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5077 let mut write_ranges = Vec::new();
5078 let mut read_ranges = Vec::new();
5079 for highlight in highlights {
5080 for (excerpt_id, excerpt_range) in
5081 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5082 {
5083 let start = highlight
5084 .range
5085 .start
5086 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5087 let end = highlight
5088 .range
5089 .end
5090 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5091 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5092 continue;
5093 }
5094
5095 let range = Anchor {
5096 buffer_id,
5097 excerpt_id,
5098 text_anchor: start,
5099 }..Anchor {
5100 buffer_id,
5101 excerpt_id,
5102 text_anchor: end,
5103 };
5104 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5105 write_ranges.push(range);
5106 } else {
5107 read_ranges.push(range);
5108 }
5109 }
5110 }
5111
5112 this.highlight_background::<DocumentHighlightRead>(
5113 &read_ranges,
5114 |theme| theme.editor_document_highlight_read_background,
5115 cx,
5116 );
5117 this.highlight_background::<DocumentHighlightWrite>(
5118 &write_ranges,
5119 |theme| theme.editor_document_highlight_write_background,
5120 cx,
5121 );
5122 cx.notify();
5123 })
5124 .log_err();
5125 }
5126 }));
5127 None
5128 }
5129
5130 pub fn refresh_inline_completion(
5131 &mut self,
5132 debounce: bool,
5133 user_requested: bool,
5134 cx: &mut ViewContext<Self>,
5135 ) -> Option<()> {
5136 let provider = self.inline_completion_provider()?;
5137 let cursor = self.selections.newest_anchor().head();
5138 let (buffer, cursor_buffer_position) =
5139 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5140
5141 if !user_requested
5142 && (!self.enable_inline_completions
5143 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5144 {
5145 self.discard_inline_completion(false, cx);
5146 return None;
5147 }
5148
5149 self.update_visible_inline_completion(cx);
5150 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5151 Some(())
5152 }
5153
5154 fn cycle_inline_completion(
5155 &mut self,
5156 direction: Direction,
5157 cx: &mut ViewContext<Self>,
5158 ) -> Option<()> {
5159 let provider = self.inline_completion_provider()?;
5160 let cursor = self.selections.newest_anchor().head();
5161 let (buffer, cursor_buffer_position) =
5162 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5163 if !self.enable_inline_completions
5164 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5165 {
5166 return None;
5167 }
5168
5169 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5170 self.update_visible_inline_completion(cx);
5171
5172 Some(())
5173 }
5174
5175 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5176 if !self.has_active_inline_completion(cx) {
5177 self.refresh_inline_completion(false, true, cx);
5178 return;
5179 }
5180
5181 self.update_visible_inline_completion(cx);
5182 }
5183
5184 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5185 self.show_cursor_names(cx);
5186 }
5187
5188 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5189 self.show_cursor_names = true;
5190 cx.notify();
5191 cx.spawn(|this, mut cx| async move {
5192 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5193 this.update(&mut cx, |this, cx| {
5194 this.show_cursor_names = false;
5195 cx.notify()
5196 })
5197 .ok()
5198 })
5199 .detach();
5200 }
5201
5202 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5203 if self.has_active_inline_completion(cx) {
5204 self.cycle_inline_completion(Direction::Next, cx);
5205 } else {
5206 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5207 if is_copilot_disabled {
5208 cx.propagate();
5209 }
5210 }
5211 }
5212
5213 pub fn previous_inline_completion(
5214 &mut self,
5215 _: &PreviousInlineCompletion,
5216 cx: &mut ViewContext<Self>,
5217 ) {
5218 if self.has_active_inline_completion(cx) {
5219 self.cycle_inline_completion(Direction::Prev, cx);
5220 } else {
5221 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5222 if is_copilot_disabled {
5223 cx.propagate();
5224 }
5225 }
5226 }
5227
5228 pub fn accept_inline_completion(
5229 &mut self,
5230 _: &AcceptInlineCompletion,
5231 cx: &mut ViewContext<Self>,
5232 ) {
5233 let Some(completion) = self.take_active_inline_completion(cx) else {
5234 return;
5235 };
5236 if let Some(provider) = self.inline_completion_provider() {
5237 provider.accept(cx);
5238 }
5239
5240 cx.emit(EditorEvent::InputHandled {
5241 utf16_range_to_replace: None,
5242 text: completion.text.to_string().into(),
5243 });
5244
5245 if let Some(range) = completion.delete_range {
5246 self.change_selections(None, cx, |s| s.select_ranges([range]))
5247 }
5248 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5249 self.refresh_inline_completion(true, true, cx);
5250 cx.notify();
5251 }
5252
5253 pub fn accept_partial_inline_completion(
5254 &mut self,
5255 _: &AcceptPartialInlineCompletion,
5256 cx: &mut ViewContext<Self>,
5257 ) {
5258 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5259 if let Some(completion) = self.take_active_inline_completion(cx) {
5260 let mut partial_completion = completion
5261 .text
5262 .chars()
5263 .by_ref()
5264 .take_while(|c| c.is_alphabetic())
5265 .collect::<String>();
5266 if partial_completion.is_empty() {
5267 partial_completion = completion
5268 .text
5269 .chars()
5270 .by_ref()
5271 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5272 .collect::<String>();
5273 }
5274
5275 cx.emit(EditorEvent::InputHandled {
5276 utf16_range_to_replace: None,
5277 text: partial_completion.clone().into(),
5278 });
5279
5280 if let Some(range) = completion.delete_range {
5281 self.change_selections(None, cx, |s| s.select_ranges([range]))
5282 }
5283 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5284
5285 self.refresh_inline_completion(true, true, cx);
5286 cx.notify();
5287 }
5288 }
5289 }
5290
5291 fn discard_inline_completion(
5292 &mut self,
5293 should_report_inline_completion_event: bool,
5294 cx: &mut ViewContext<Self>,
5295 ) -> bool {
5296 if let Some(provider) = self.inline_completion_provider() {
5297 provider.discard(should_report_inline_completion_event, cx);
5298 }
5299
5300 self.take_active_inline_completion(cx).is_some()
5301 }
5302
5303 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5304 if let Some(completion) = self.active_inline_completion.as_ref() {
5305 let buffer = self.buffer.read(cx).read(cx);
5306 completion.position.is_valid(&buffer)
5307 } else {
5308 false
5309 }
5310 }
5311
5312 fn take_active_inline_completion(
5313 &mut self,
5314 cx: &mut ViewContext<Self>,
5315 ) -> Option<CompletionState> {
5316 let completion = self.active_inline_completion.take()?;
5317 let render_inlay_ids = completion.render_inlay_ids.clone();
5318 self.display_map.update(cx, |map, cx| {
5319 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5320 });
5321 let buffer = self.buffer.read(cx).read(cx);
5322
5323 if completion.position.is_valid(&buffer) {
5324 Some(completion)
5325 } else {
5326 None
5327 }
5328 }
5329
5330 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5331 let selection = self.selections.newest_anchor();
5332 let cursor = selection.head();
5333
5334 let excerpt_id = cursor.excerpt_id;
5335
5336 if self.context_menu.read().is_none()
5337 && self.completion_tasks.is_empty()
5338 && selection.start == selection.end
5339 {
5340 if let Some(provider) = self.inline_completion_provider() {
5341 if let Some((buffer, cursor_buffer_position)) =
5342 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5343 {
5344 if let Some(proposal) =
5345 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5346 {
5347 let mut to_remove = Vec::new();
5348 if let Some(completion) = self.active_inline_completion.take() {
5349 to_remove.extend(completion.render_inlay_ids.iter());
5350 }
5351
5352 let to_add = proposal
5353 .inlays
5354 .iter()
5355 .filter_map(|inlay| {
5356 let snapshot = self.buffer.read(cx).snapshot(cx);
5357 let id = post_inc(&mut self.next_inlay_id);
5358 match inlay {
5359 InlayProposal::Hint(position, hint) => {
5360 let position =
5361 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5362 Some(Inlay::hint(id, position, hint))
5363 }
5364 InlayProposal::Suggestion(position, text) => {
5365 let position =
5366 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5367 Some(Inlay::suggestion(id, position, text.clone()))
5368 }
5369 }
5370 })
5371 .collect_vec();
5372
5373 self.active_inline_completion = Some(CompletionState {
5374 position: cursor,
5375 text: proposal.text,
5376 delete_range: proposal.delete_range.and_then(|range| {
5377 let snapshot = self.buffer.read(cx).snapshot(cx);
5378 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5379 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5380 Some(start?..end?)
5381 }),
5382 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5383 });
5384
5385 self.display_map
5386 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5387
5388 cx.notify();
5389 return;
5390 }
5391 }
5392 }
5393 }
5394
5395 self.discard_inline_completion(false, cx);
5396 }
5397
5398 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5399 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5400 }
5401
5402 fn render_code_actions_indicator(
5403 &self,
5404 _style: &EditorStyle,
5405 row: DisplayRow,
5406 is_active: bool,
5407 cx: &mut ViewContext<Self>,
5408 ) -> Option<IconButton> {
5409 if self.available_code_actions.is_some() {
5410 Some(
5411 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5412 .shape(ui::IconButtonShape::Square)
5413 .icon_size(IconSize::XSmall)
5414 .icon_color(Color::Muted)
5415 .selected(is_active)
5416 .tooltip({
5417 let focus_handle = self.focus_handle.clone();
5418 move |cx| {
5419 Tooltip::for_action_in(
5420 "Toggle Code Actions",
5421 &ToggleCodeActions {
5422 deployed_from_indicator: None,
5423 },
5424 &focus_handle,
5425 cx,
5426 )
5427 }
5428 })
5429 .on_click(cx.listener(move |editor, _e, cx| {
5430 editor.focus(cx);
5431 editor.toggle_code_actions(
5432 &ToggleCodeActions {
5433 deployed_from_indicator: Some(row),
5434 },
5435 cx,
5436 );
5437 })),
5438 )
5439 } else {
5440 None
5441 }
5442 }
5443
5444 fn clear_tasks(&mut self) {
5445 self.tasks.clear()
5446 }
5447
5448 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5449 if self.tasks.insert(key, value).is_some() {
5450 // This case should hopefully be rare, but just in case...
5451 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5452 }
5453 }
5454
5455 fn render_run_indicator(
5456 &self,
5457 _style: &EditorStyle,
5458 is_active: bool,
5459 row: DisplayRow,
5460 cx: &mut ViewContext<Self>,
5461 ) -> IconButton {
5462 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5463 .shape(ui::IconButtonShape::Square)
5464 .icon_size(IconSize::XSmall)
5465 .icon_color(Color::Muted)
5466 .selected(is_active)
5467 .on_click(cx.listener(move |editor, _e, cx| {
5468 editor.focus(cx);
5469 editor.toggle_code_actions(
5470 &ToggleCodeActions {
5471 deployed_from_indicator: Some(row),
5472 },
5473 cx,
5474 );
5475 }))
5476 }
5477
5478 pub fn context_menu_visible(&self) -> bool {
5479 self.context_menu
5480 .read()
5481 .as_ref()
5482 .map_or(false, |menu| menu.visible())
5483 }
5484
5485 fn render_context_menu(
5486 &self,
5487 cursor_position: DisplayPoint,
5488 style: &EditorStyle,
5489 max_height: Pixels,
5490 cx: &mut ViewContext<Editor>,
5491 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5492 self.context_menu.read().as_ref().map(|menu| {
5493 menu.render(
5494 cursor_position,
5495 style,
5496 max_height,
5497 self.workspace.as_ref().map(|(w, _)| w.clone()),
5498 cx,
5499 )
5500 })
5501 }
5502
5503 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5504 cx.notify();
5505 self.completion_tasks.clear();
5506 let context_menu = self.context_menu.write().take();
5507 if context_menu.is_some() {
5508 self.update_visible_inline_completion(cx);
5509 }
5510 context_menu
5511 }
5512
5513 pub fn insert_snippet(
5514 &mut self,
5515 insertion_ranges: &[Range<usize>],
5516 snippet: Snippet,
5517 cx: &mut ViewContext<Self>,
5518 ) -> Result<()> {
5519 struct Tabstop<T> {
5520 is_end_tabstop: bool,
5521 ranges: Vec<Range<T>>,
5522 }
5523
5524 let tabstops = self.buffer.update(cx, |buffer, cx| {
5525 let snippet_text: Arc<str> = snippet.text.clone().into();
5526 buffer.edit(
5527 insertion_ranges
5528 .iter()
5529 .cloned()
5530 .map(|range| (range, snippet_text.clone())),
5531 Some(AutoindentMode::EachLine),
5532 cx,
5533 );
5534
5535 let snapshot = &*buffer.read(cx);
5536 let snippet = &snippet;
5537 snippet
5538 .tabstops
5539 .iter()
5540 .map(|tabstop| {
5541 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5542 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5543 });
5544 let mut tabstop_ranges = tabstop
5545 .iter()
5546 .flat_map(|tabstop_range| {
5547 let mut delta = 0_isize;
5548 insertion_ranges.iter().map(move |insertion_range| {
5549 let insertion_start = insertion_range.start as isize + delta;
5550 delta +=
5551 snippet.text.len() as isize - insertion_range.len() as isize;
5552
5553 let start = ((insertion_start + tabstop_range.start) as usize)
5554 .min(snapshot.len());
5555 let end = ((insertion_start + tabstop_range.end) as usize)
5556 .min(snapshot.len());
5557 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5558 })
5559 })
5560 .collect::<Vec<_>>();
5561 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5562
5563 Tabstop {
5564 is_end_tabstop,
5565 ranges: tabstop_ranges,
5566 }
5567 })
5568 .collect::<Vec<_>>()
5569 });
5570 if let Some(tabstop) = tabstops.first() {
5571 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5572 s.select_ranges(tabstop.ranges.iter().cloned());
5573 });
5574
5575 // If we're already at the last tabstop and it's at the end of the snippet,
5576 // we're done, we don't need to keep the state around.
5577 if !tabstop.is_end_tabstop {
5578 let ranges = tabstops
5579 .into_iter()
5580 .map(|tabstop| tabstop.ranges)
5581 .collect::<Vec<_>>();
5582 self.snippet_stack.push(SnippetState {
5583 active_index: 0,
5584 ranges,
5585 });
5586 }
5587
5588 // Check whether the just-entered snippet ends with an auto-closable bracket.
5589 if self.autoclose_regions.is_empty() {
5590 let snapshot = self.buffer.read(cx).snapshot(cx);
5591 for selection in &mut self.selections.all::<Point>(cx) {
5592 let selection_head = selection.head();
5593 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5594 continue;
5595 };
5596
5597 let mut bracket_pair = None;
5598 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5599 let prev_chars = snapshot
5600 .reversed_chars_at(selection_head)
5601 .collect::<String>();
5602 for (pair, enabled) in scope.brackets() {
5603 if enabled
5604 && pair.close
5605 && prev_chars.starts_with(pair.start.as_str())
5606 && next_chars.starts_with(pair.end.as_str())
5607 {
5608 bracket_pair = Some(pair.clone());
5609 break;
5610 }
5611 }
5612 if let Some(pair) = bracket_pair {
5613 let start = snapshot.anchor_after(selection_head);
5614 let end = snapshot.anchor_after(selection_head);
5615 self.autoclose_regions.push(AutocloseRegion {
5616 selection_id: selection.id,
5617 range: start..end,
5618 pair,
5619 });
5620 }
5621 }
5622 }
5623 }
5624 Ok(())
5625 }
5626
5627 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5628 self.move_to_snippet_tabstop(Bias::Right, cx)
5629 }
5630
5631 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5632 self.move_to_snippet_tabstop(Bias::Left, cx)
5633 }
5634
5635 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5636 if let Some(mut snippet) = self.snippet_stack.pop() {
5637 match bias {
5638 Bias::Left => {
5639 if snippet.active_index > 0 {
5640 snippet.active_index -= 1;
5641 } else {
5642 self.snippet_stack.push(snippet);
5643 return false;
5644 }
5645 }
5646 Bias::Right => {
5647 if snippet.active_index + 1 < snippet.ranges.len() {
5648 snippet.active_index += 1;
5649 } else {
5650 self.snippet_stack.push(snippet);
5651 return false;
5652 }
5653 }
5654 }
5655 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5656 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5657 s.select_anchor_ranges(current_ranges.iter().cloned())
5658 });
5659 // If snippet state is not at the last tabstop, push it back on the stack
5660 if snippet.active_index + 1 < snippet.ranges.len() {
5661 self.snippet_stack.push(snippet);
5662 }
5663 return true;
5664 }
5665 }
5666
5667 false
5668 }
5669
5670 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5671 self.transact(cx, |this, cx| {
5672 this.select_all(&SelectAll, cx);
5673 this.insert("", cx);
5674 });
5675 }
5676
5677 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5678 self.transact(cx, |this, cx| {
5679 this.select_autoclose_pair(cx);
5680 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5681 if !this.linked_edit_ranges.is_empty() {
5682 let selections = this.selections.all::<MultiBufferPoint>(cx);
5683 let snapshot = this.buffer.read(cx).snapshot(cx);
5684
5685 for selection in selections.iter() {
5686 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5687 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5688 if selection_start.buffer_id != selection_end.buffer_id {
5689 continue;
5690 }
5691 if let Some(ranges) =
5692 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5693 {
5694 for (buffer, entries) in ranges {
5695 linked_ranges.entry(buffer).or_default().extend(entries);
5696 }
5697 }
5698 }
5699 }
5700
5701 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5702 if !this.selections.line_mode {
5703 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5704 for selection in &mut selections {
5705 if selection.is_empty() {
5706 let old_head = selection.head();
5707 let mut new_head =
5708 movement::left(&display_map, old_head.to_display_point(&display_map))
5709 .to_point(&display_map);
5710 if let Some((buffer, line_buffer_range)) = display_map
5711 .buffer_snapshot
5712 .buffer_line_for_row(MultiBufferRow(old_head.row))
5713 {
5714 let indent_size =
5715 buffer.indent_size_for_line(line_buffer_range.start.row);
5716 let indent_len = match indent_size.kind {
5717 IndentKind::Space => {
5718 buffer.settings_at(line_buffer_range.start, cx).tab_size
5719 }
5720 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5721 };
5722 if old_head.column <= indent_size.len && old_head.column > 0 {
5723 let indent_len = indent_len.get();
5724 new_head = cmp::min(
5725 new_head,
5726 MultiBufferPoint::new(
5727 old_head.row,
5728 ((old_head.column - 1) / indent_len) * indent_len,
5729 ),
5730 );
5731 }
5732 }
5733
5734 selection.set_head(new_head, SelectionGoal::None);
5735 }
5736 }
5737 }
5738
5739 this.signature_help_state.set_backspace_pressed(true);
5740 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5741 this.insert("", cx);
5742 let empty_str: Arc<str> = Arc::from("");
5743 for (buffer, edits) in linked_ranges {
5744 let snapshot = buffer.read(cx).snapshot();
5745 use text::ToPoint as TP;
5746
5747 let edits = edits
5748 .into_iter()
5749 .map(|range| {
5750 let end_point = TP::to_point(&range.end, &snapshot);
5751 let mut start_point = TP::to_point(&range.start, &snapshot);
5752
5753 if end_point == start_point {
5754 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5755 .saturating_sub(1);
5756 start_point = TP::to_point(&offset, &snapshot);
5757 };
5758
5759 (start_point..end_point, empty_str.clone())
5760 })
5761 .sorted_by_key(|(range, _)| range.start)
5762 .collect::<Vec<_>>();
5763 buffer.update(cx, |this, cx| {
5764 this.edit(edits, None, cx);
5765 })
5766 }
5767 this.refresh_inline_completion(true, false, cx);
5768 linked_editing_ranges::refresh_linked_ranges(this, cx);
5769 });
5770 }
5771
5772 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5773 self.transact(cx, |this, cx| {
5774 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5775 let line_mode = s.line_mode;
5776 s.move_with(|map, selection| {
5777 if selection.is_empty() && !line_mode {
5778 let cursor = movement::right(map, selection.head());
5779 selection.end = cursor;
5780 selection.reversed = true;
5781 selection.goal = SelectionGoal::None;
5782 }
5783 })
5784 });
5785 this.insert("", cx);
5786 this.refresh_inline_completion(true, false, cx);
5787 });
5788 }
5789
5790 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5791 if self.move_to_prev_snippet_tabstop(cx) {
5792 return;
5793 }
5794
5795 self.outdent(&Outdent, cx);
5796 }
5797
5798 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5799 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5800 return;
5801 }
5802
5803 let mut selections = self.selections.all_adjusted(cx);
5804 let buffer = self.buffer.read(cx);
5805 let snapshot = buffer.snapshot(cx);
5806 let rows_iter = selections.iter().map(|s| s.head().row);
5807 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5808
5809 let mut edits = Vec::new();
5810 let mut prev_edited_row = 0;
5811 let mut row_delta = 0;
5812 for selection in &mut selections {
5813 if selection.start.row != prev_edited_row {
5814 row_delta = 0;
5815 }
5816 prev_edited_row = selection.end.row;
5817
5818 // If the selection is non-empty, then increase the indentation of the selected lines.
5819 if !selection.is_empty() {
5820 row_delta =
5821 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5822 continue;
5823 }
5824
5825 // If the selection is empty and the cursor is in the leading whitespace before the
5826 // suggested indentation, then auto-indent the line.
5827 let cursor = selection.head();
5828 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5829 if let Some(suggested_indent) =
5830 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5831 {
5832 if cursor.column < suggested_indent.len
5833 && cursor.column <= current_indent.len
5834 && current_indent.len <= suggested_indent.len
5835 {
5836 selection.start = Point::new(cursor.row, suggested_indent.len);
5837 selection.end = selection.start;
5838 if row_delta == 0 {
5839 edits.extend(Buffer::edit_for_indent_size_adjustment(
5840 cursor.row,
5841 current_indent,
5842 suggested_indent,
5843 ));
5844 row_delta = suggested_indent.len - current_indent.len;
5845 }
5846 continue;
5847 }
5848 }
5849
5850 // Otherwise, insert a hard or soft tab.
5851 let settings = buffer.settings_at(cursor, cx);
5852 let tab_size = if settings.hard_tabs {
5853 IndentSize::tab()
5854 } else {
5855 let tab_size = settings.tab_size.get();
5856 let char_column = snapshot
5857 .text_for_range(Point::new(cursor.row, 0)..cursor)
5858 .flat_map(str::chars)
5859 .count()
5860 + row_delta as usize;
5861 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5862 IndentSize::spaces(chars_to_next_tab_stop)
5863 };
5864 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5865 selection.end = selection.start;
5866 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5867 row_delta += tab_size.len;
5868 }
5869
5870 self.transact(cx, |this, cx| {
5871 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5872 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5873 this.refresh_inline_completion(true, false, cx);
5874 });
5875 }
5876
5877 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5878 if self.read_only(cx) {
5879 return;
5880 }
5881 let mut selections = self.selections.all::<Point>(cx);
5882 let mut prev_edited_row = 0;
5883 let mut row_delta = 0;
5884 let mut edits = Vec::new();
5885 let buffer = self.buffer.read(cx);
5886 let snapshot = buffer.snapshot(cx);
5887 for selection in &mut selections {
5888 if selection.start.row != prev_edited_row {
5889 row_delta = 0;
5890 }
5891 prev_edited_row = selection.end.row;
5892
5893 row_delta =
5894 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5895 }
5896
5897 self.transact(cx, |this, cx| {
5898 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5899 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5900 });
5901 }
5902
5903 fn indent_selection(
5904 buffer: &MultiBuffer,
5905 snapshot: &MultiBufferSnapshot,
5906 selection: &mut Selection<Point>,
5907 edits: &mut Vec<(Range<Point>, String)>,
5908 delta_for_start_row: u32,
5909 cx: &AppContext,
5910 ) -> u32 {
5911 let settings = buffer.settings_at(selection.start, cx);
5912 let tab_size = settings.tab_size.get();
5913 let indent_kind = if settings.hard_tabs {
5914 IndentKind::Tab
5915 } else {
5916 IndentKind::Space
5917 };
5918 let mut start_row = selection.start.row;
5919 let mut end_row = selection.end.row + 1;
5920
5921 // If a selection ends at the beginning of a line, don't indent
5922 // that last line.
5923 if selection.end.column == 0 && selection.end.row > selection.start.row {
5924 end_row -= 1;
5925 }
5926
5927 // Avoid re-indenting a row that has already been indented by a
5928 // previous selection, but still update this selection's column
5929 // to reflect that indentation.
5930 if delta_for_start_row > 0 {
5931 start_row += 1;
5932 selection.start.column += delta_for_start_row;
5933 if selection.end.row == selection.start.row {
5934 selection.end.column += delta_for_start_row;
5935 }
5936 }
5937
5938 let mut delta_for_end_row = 0;
5939 let has_multiple_rows = start_row + 1 != end_row;
5940 for row in start_row..end_row {
5941 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5942 let indent_delta = match (current_indent.kind, indent_kind) {
5943 (IndentKind::Space, IndentKind::Space) => {
5944 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5945 IndentSize::spaces(columns_to_next_tab_stop)
5946 }
5947 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5948 (_, IndentKind::Tab) => IndentSize::tab(),
5949 };
5950
5951 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5952 0
5953 } else {
5954 selection.start.column
5955 };
5956 let row_start = Point::new(row, start);
5957 edits.push((
5958 row_start..row_start,
5959 indent_delta.chars().collect::<String>(),
5960 ));
5961
5962 // Update this selection's endpoints to reflect the indentation.
5963 if row == selection.start.row {
5964 selection.start.column += indent_delta.len;
5965 }
5966 if row == selection.end.row {
5967 selection.end.column += indent_delta.len;
5968 delta_for_end_row = indent_delta.len;
5969 }
5970 }
5971
5972 if selection.start.row == selection.end.row {
5973 delta_for_start_row + delta_for_end_row
5974 } else {
5975 delta_for_end_row
5976 }
5977 }
5978
5979 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5980 if self.read_only(cx) {
5981 return;
5982 }
5983 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5984 let selections = self.selections.all::<Point>(cx);
5985 let mut deletion_ranges = Vec::new();
5986 let mut last_outdent = None;
5987 {
5988 let buffer = self.buffer.read(cx);
5989 let snapshot = buffer.snapshot(cx);
5990 for selection in &selections {
5991 let settings = buffer.settings_at(selection.start, cx);
5992 let tab_size = settings.tab_size.get();
5993 let mut rows = selection.spanned_rows(false, &display_map);
5994
5995 // Avoid re-outdenting a row that has already been outdented by a
5996 // previous selection.
5997 if let Some(last_row) = last_outdent {
5998 if last_row == rows.start {
5999 rows.start = rows.start.next_row();
6000 }
6001 }
6002 let has_multiple_rows = rows.len() > 1;
6003 for row in rows.iter_rows() {
6004 let indent_size = snapshot.indent_size_for_line(row);
6005 if indent_size.len > 0 {
6006 let deletion_len = match indent_size.kind {
6007 IndentKind::Space => {
6008 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6009 if columns_to_prev_tab_stop == 0 {
6010 tab_size
6011 } else {
6012 columns_to_prev_tab_stop
6013 }
6014 }
6015 IndentKind::Tab => 1,
6016 };
6017 let start = if has_multiple_rows
6018 || deletion_len > selection.start.column
6019 || indent_size.len < selection.start.column
6020 {
6021 0
6022 } else {
6023 selection.start.column - deletion_len
6024 };
6025 deletion_ranges.push(
6026 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6027 );
6028 last_outdent = Some(row);
6029 }
6030 }
6031 }
6032 }
6033
6034 self.transact(cx, |this, cx| {
6035 this.buffer.update(cx, |buffer, cx| {
6036 let empty_str: Arc<str> = Arc::default();
6037 buffer.edit(
6038 deletion_ranges
6039 .into_iter()
6040 .map(|range| (range, empty_str.clone())),
6041 None,
6042 cx,
6043 );
6044 });
6045 let selections = this.selections.all::<usize>(cx);
6046 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6047 });
6048 }
6049
6050 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6051 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6052 let selections = self.selections.all::<Point>(cx);
6053
6054 let mut new_cursors = Vec::new();
6055 let mut edit_ranges = Vec::new();
6056 let mut selections = selections.iter().peekable();
6057 while let Some(selection) = selections.next() {
6058 let mut rows = selection.spanned_rows(false, &display_map);
6059 let goal_display_column = selection.head().to_display_point(&display_map).column();
6060
6061 // Accumulate contiguous regions of rows that we want to delete.
6062 while let Some(next_selection) = selections.peek() {
6063 let next_rows = next_selection.spanned_rows(false, &display_map);
6064 if next_rows.start <= rows.end {
6065 rows.end = next_rows.end;
6066 selections.next().unwrap();
6067 } else {
6068 break;
6069 }
6070 }
6071
6072 let buffer = &display_map.buffer_snapshot;
6073 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6074 let edit_end;
6075 let cursor_buffer_row;
6076 if buffer.max_point().row >= rows.end.0 {
6077 // If there's a line after the range, delete the \n from the end of the row range
6078 // and position the cursor on the next line.
6079 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6080 cursor_buffer_row = rows.end;
6081 } else {
6082 // If there isn't a line after the range, delete the \n from the line before the
6083 // start of the row range and position the cursor there.
6084 edit_start = edit_start.saturating_sub(1);
6085 edit_end = buffer.len();
6086 cursor_buffer_row = rows.start.previous_row();
6087 }
6088
6089 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6090 *cursor.column_mut() =
6091 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6092
6093 new_cursors.push((
6094 selection.id,
6095 buffer.anchor_after(cursor.to_point(&display_map)),
6096 ));
6097 edit_ranges.push(edit_start..edit_end);
6098 }
6099
6100 self.transact(cx, |this, cx| {
6101 let buffer = this.buffer.update(cx, |buffer, cx| {
6102 let empty_str: Arc<str> = Arc::default();
6103 buffer.edit(
6104 edit_ranges
6105 .into_iter()
6106 .map(|range| (range, empty_str.clone())),
6107 None,
6108 cx,
6109 );
6110 buffer.snapshot(cx)
6111 });
6112 let new_selections = new_cursors
6113 .into_iter()
6114 .map(|(id, cursor)| {
6115 let cursor = cursor.to_point(&buffer);
6116 Selection {
6117 id,
6118 start: cursor,
6119 end: cursor,
6120 reversed: false,
6121 goal: SelectionGoal::None,
6122 }
6123 })
6124 .collect();
6125
6126 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6127 s.select(new_selections);
6128 });
6129 });
6130 }
6131
6132 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6133 if self.read_only(cx) {
6134 return;
6135 }
6136 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6137 for selection in self.selections.all::<Point>(cx) {
6138 let start = MultiBufferRow(selection.start.row);
6139 let end = if selection.start.row == selection.end.row {
6140 MultiBufferRow(selection.start.row + 1)
6141 } else {
6142 MultiBufferRow(selection.end.row)
6143 };
6144
6145 if let Some(last_row_range) = row_ranges.last_mut() {
6146 if start <= last_row_range.end {
6147 last_row_range.end = end;
6148 continue;
6149 }
6150 }
6151 row_ranges.push(start..end);
6152 }
6153
6154 let snapshot = self.buffer.read(cx).snapshot(cx);
6155 let mut cursor_positions = Vec::new();
6156 for row_range in &row_ranges {
6157 let anchor = snapshot.anchor_before(Point::new(
6158 row_range.end.previous_row().0,
6159 snapshot.line_len(row_range.end.previous_row()),
6160 ));
6161 cursor_positions.push(anchor..anchor);
6162 }
6163
6164 self.transact(cx, |this, cx| {
6165 for row_range in row_ranges.into_iter().rev() {
6166 for row in row_range.iter_rows().rev() {
6167 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6168 let next_line_row = row.next_row();
6169 let indent = snapshot.indent_size_for_line(next_line_row);
6170 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6171
6172 let replace = if snapshot.line_len(next_line_row) > indent.len {
6173 " "
6174 } else {
6175 ""
6176 };
6177
6178 this.buffer.update(cx, |buffer, cx| {
6179 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6180 });
6181 }
6182 }
6183
6184 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6185 s.select_anchor_ranges(cursor_positions)
6186 });
6187 });
6188 }
6189
6190 pub fn sort_lines_case_sensitive(
6191 &mut self,
6192 _: &SortLinesCaseSensitive,
6193 cx: &mut ViewContext<Self>,
6194 ) {
6195 self.manipulate_lines(cx, |lines| lines.sort())
6196 }
6197
6198 pub fn sort_lines_case_insensitive(
6199 &mut self,
6200 _: &SortLinesCaseInsensitive,
6201 cx: &mut ViewContext<Self>,
6202 ) {
6203 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6204 }
6205
6206 pub fn unique_lines_case_insensitive(
6207 &mut self,
6208 _: &UniqueLinesCaseInsensitive,
6209 cx: &mut ViewContext<Self>,
6210 ) {
6211 self.manipulate_lines(cx, |lines| {
6212 let mut seen = HashSet::default();
6213 lines.retain(|line| seen.insert(line.to_lowercase()));
6214 })
6215 }
6216
6217 pub fn unique_lines_case_sensitive(
6218 &mut self,
6219 _: &UniqueLinesCaseSensitive,
6220 cx: &mut ViewContext<Self>,
6221 ) {
6222 self.manipulate_lines(cx, |lines| {
6223 let mut seen = HashSet::default();
6224 lines.retain(|line| seen.insert(*line));
6225 })
6226 }
6227
6228 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6229 let mut revert_changes = HashMap::default();
6230 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6231 for hunk in hunks_for_rows(
6232 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6233 &multi_buffer_snapshot,
6234 ) {
6235 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6236 }
6237 if !revert_changes.is_empty() {
6238 self.transact(cx, |editor, cx| {
6239 editor.revert(revert_changes, cx);
6240 });
6241 }
6242 }
6243
6244 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6245 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6246 if !revert_changes.is_empty() {
6247 self.transact(cx, |editor, cx| {
6248 editor.revert(revert_changes, cx);
6249 });
6250 }
6251 }
6252
6253 fn apply_selected_diff_hunks(&mut self, _: &ApplyDiffHunk, cx: &mut ViewContext<Self>) {
6254 let snapshot = self.buffer.read(cx).snapshot(cx);
6255 let hunks = hunks_for_selections(&snapshot, &self.selections.disjoint_anchors());
6256 let mut ranges_by_buffer = HashMap::default();
6257 self.transact(cx, |editor, cx| {
6258 for hunk in hunks {
6259 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
6260 ranges_by_buffer
6261 .entry(buffer.clone())
6262 .or_insert_with(Vec::new)
6263 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
6264 }
6265 }
6266
6267 for (buffer, ranges) in ranges_by_buffer {
6268 buffer.update(cx, |buffer, cx| {
6269 buffer.merge_into_base(ranges, cx);
6270 });
6271 }
6272 });
6273 }
6274
6275 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6276 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6277 let project_path = buffer.read(cx).project_path(cx)?;
6278 let project = self.project.as_ref()?.read(cx);
6279 let entry = project.entry_for_path(&project_path, cx)?;
6280 let abs_path = project.absolute_path(&project_path, cx)?;
6281 let parent = if entry.is_symlink {
6282 abs_path.canonicalize().ok()?
6283 } else {
6284 abs_path
6285 }
6286 .parent()?
6287 .to_path_buf();
6288 Some(parent)
6289 }) {
6290 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6291 }
6292 }
6293
6294 fn gather_revert_changes(
6295 &mut self,
6296 selections: &[Selection<Anchor>],
6297 cx: &mut ViewContext<'_, Editor>,
6298 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6299 let mut revert_changes = HashMap::default();
6300 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6301 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6302 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6303 }
6304 revert_changes
6305 }
6306
6307 pub fn prepare_revert_change(
6308 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6309 multi_buffer: &Model<MultiBuffer>,
6310 hunk: &MultiBufferDiffHunk,
6311 cx: &AppContext,
6312 ) -> Option<()> {
6313 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6314 let buffer = buffer.read(cx);
6315 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6316 let buffer_snapshot = buffer.snapshot();
6317 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6318 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6319 probe
6320 .0
6321 .start
6322 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6323 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6324 }) {
6325 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6326 Some(())
6327 } else {
6328 None
6329 }
6330 }
6331
6332 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6333 self.manipulate_lines(cx, |lines| lines.reverse())
6334 }
6335
6336 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6337 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6338 }
6339
6340 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6341 where
6342 Fn: FnMut(&mut Vec<&str>),
6343 {
6344 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6345 let buffer = self.buffer.read(cx).snapshot(cx);
6346
6347 let mut edits = Vec::new();
6348
6349 let selections = self.selections.all::<Point>(cx);
6350 let mut selections = selections.iter().peekable();
6351 let mut contiguous_row_selections = Vec::new();
6352 let mut new_selections = Vec::new();
6353 let mut added_lines = 0;
6354 let mut removed_lines = 0;
6355
6356 while let Some(selection) = selections.next() {
6357 let (start_row, end_row) = consume_contiguous_rows(
6358 &mut contiguous_row_selections,
6359 selection,
6360 &display_map,
6361 &mut selections,
6362 );
6363
6364 let start_point = Point::new(start_row.0, 0);
6365 let end_point = Point::new(
6366 end_row.previous_row().0,
6367 buffer.line_len(end_row.previous_row()),
6368 );
6369 let text = buffer
6370 .text_for_range(start_point..end_point)
6371 .collect::<String>();
6372
6373 let mut lines = text.split('\n').collect_vec();
6374
6375 let lines_before = lines.len();
6376 callback(&mut lines);
6377 let lines_after = lines.len();
6378
6379 edits.push((start_point..end_point, lines.join("\n")));
6380
6381 // Selections must change based on added and removed line count
6382 let start_row =
6383 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6384 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6385 new_selections.push(Selection {
6386 id: selection.id,
6387 start: start_row,
6388 end: end_row,
6389 goal: SelectionGoal::None,
6390 reversed: selection.reversed,
6391 });
6392
6393 if lines_after > lines_before {
6394 added_lines += lines_after - lines_before;
6395 } else if lines_before > lines_after {
6396 removed_lines += lines_before - lines_after;
6397 }
6398 }
6399
6400 self.transact(cx, |this, cx| {
6401 let buffer = this.buffer.update(cx, |buffer, cx| {
6402 buffer.edit(edits, None, cx);
6403 buffer.snapshot(cx)
6404 });
6405
6406 // Recalculate offsets on newly edited buffer
6407 let new_selections = new_selections
6408 .iter()
6409 .map(|s| {
6410 let start_point = Point::new(s.start.0, 0);
6411 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6412 Selection {
6413 id: s.id,
6414 start: buffer.point_to_offset(start_point),
6415 end: buffer.point_to_offset(end_point),
6416 goal: s.goal,
6417 reversed: s.reversed,
6418 }
6419 })
6420 .collect();
6421
6422 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6423 s.select(new_selections);
6424 });
6425
6426 this.request_autoscroll(Autoscroll::fit(), cx);
6427 });
6428 }
6429
6430 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6431 self.manipulate_text(cx, |text| text.to_uppercase())
6432 }
6433
6434 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6435 self.manipulate_text(cx, |text| text.to_lowercase())
6436 }
6437
6438 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6439 self.manipulate_text(cx, |text| {
6440 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6441 // https://github.com/rutrum/convert-case/issues/16
6442 text.split('\n')
6443 .map(|line| line.to_case(Case::Title))
6444 .join("\n")
6445 })
6446 }
6447
6448 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6449 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6450 }
6451
6452 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6453 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6454 }
6455
6456 pub fn convert_to_upper_camel_case(
6457 &mut self,
6458 _: &ConvertToUpperCamelCase,
6459 cx: &mut ViewContext<Self>,
6460 ) {
6461 self.manipulate_text(cx, |text| {
6462 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6463 // https://github.com/rutrum/convert-case/issues/16
6464 text.split('\n')
6465 .map(|line| line.to_case(Case::UpperCamel))
6466 .join("\n")
6467 })
6468 }
6469
6470 pub fn convert_to_lower_camel_case(
6471 &mut self,
6472 _: &ConvertToLowerCamelCase,
6473 cx: &mut ViewContext<Self>,
6474 ) {
6475 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6476 }
6477
6478 pub fn convert_to_opposite_case(
6479 &mut self,
6480 _: &ConvertToOppositeCase,
6481 cx: &mut ViewContext<Self>,
6482 ) {
6483 self.manipulate_text(cx, |text| {
6484 text.chars()
6485 .fold(String::with_capacity(text.len()), |mut t, c| {
6486 if c.is_uppercase() {
6487 t.extend(c.to_lowercase());
6488 } else {
6489 t.extend(c.to_uppercase());
6490 }
6491 t
6492 })
6493 })
6494 }
6495
6496 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6497 where
6498 Fn: FnMut(&str) -> String,
6499 {
6500 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6501 let buffer = self.buffer.read(cx).snapshot(cx);
6502
6503 let mut new_selections = Vec::new();
6504 let mut edits = Vec::new();
6505 let mut selection_adjustment = 0i32;
6506
6507 for selection in self.selections.all::<usize>(cx) {
6508 let selection_is_empty = selection.is_empty();
6509
6510 let (start, end) = if selection_is_empty {
6511 let word_range = movement::surrounding_word(
6512 &display_map,
6513 selection.start.to_display_point(&display_map),
6514 );
6515 let start = word_range.start.to_offset(&display_map, Bias::Left);
6516 let end = word_range.end.to_offset(&display_map, Bias::Left);
6517 (start, end)
6518 } else {
6519 (selection.start, selection.end)
6520 };
6521
6522 let text = buffer.text_for_range(start..end).collect::<String>();
6523 let old_length = text.len() as i32;
6524 let text = callback(&text);
6525
6526 new_selections.push(Selection {
6527 start: (start as i32 - selection_adjustment) as usize,
6528 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6529 goal: SelectionGoal::None,
6530 ..selection
6531 });
6532
6533 selection_adjustment += old_length - text.len() as i32;
6534
6535 edits.push((start..end, text));
6536 }
6537
6538 self.transact(cx, |this, cx| {
6539 this.buffer.update(cx, |buffer, cx| {
6540 buffer.edit(edits, None, cx);
6541 });
6542
6543 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6544 s.select(new_selections);
6545 });
6546
6547 this.request_autoscroll(Autoscroll::fit(), cx);
6548 });
6549 }
6550
6551 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6552 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6553 let buffer = &display_map.buffer_snapshot;
6554 let selections = self.selections.all::<Point>(cx);
6555
6556 let mut edits = Vec::new();
6557 let mut selections_iter = selections.iter().peekable();
6558 while let Some(selection) = selections_iter.next() {
6559 // Avoid duplicating the same lines twice.
6560 let mut rows = selection.spanned_rows(false, &display_map);
6561
6562 while let Some(next_selection) = selections_iter.peek() {
6563 let next_rows = next_selection.spanned_rows(false, &display_map);
6564 if next_rows.start < rows.end {
6565 rows.end = next_rows.end;
6566 selections_iter.next().unwrap();
6567 } else {
6568 break;
6569 }
6570 }
6571
6572 // Copy the text from the selected row region and splice it either at the start
6573 // or end of the region.
6574 let start = Point::new(rows.start.0, 0);
6575 let end = Point::new(
6576 rows.end.previous_row().0,
6577 buffer.line_len(rows.end.previous_row()),
6578 );
6579 let text = buffer
6580 .text_for_range(start..end)
6581 .chain(Some("\n"))
6582 .collect::<String>();
6583 let insert_location = if upwards {
6584 Point::new(rows.end.0, 0)
6585 } else {
6586 start
6587 };
6588 edits.push((insert_location..insert_location, text));
6589 }
6590
6591 self.transact(cx, |this, cx| {
6592 this.buffer.update(cx, |buffer, cx| {
6593 buffer.edit(edits, None, cx);
6594 });
6595
6596 this.request_autoscroll(Autoscroll::fit(), cx);
6597 });
6598 }
6599
6600 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6601 self.duplicate_line(true, cx);
6602 }
6603
6604 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6605 self.duplicate_line(false, cx);
6606 }
6607
6608 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6609 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6610 let buffer = self.buffer.read(cx).snapshot(cx);
6611
6612 let mut edits = Vec::new();
6613 let mut unfold_ranges = Vec::new();
6614 let mut refold_ranges = Vec::new();
6615
6616 let selections = self.selections.all::<Point>(cx);
6617 let mut selections = selections.iter().peekable();
6618 let mut contiguous_row_selections = Vec::new();
6619 let mut new_selections = Vec::new();
6620
6621 while let Some(selection) = selections.next() {
6622 // Find all the selections that span a contiguous row range
6623 let (start_row, end_row) = consume_contiguous_rows(
6624 &mut contiguous_row_selections,
6625 selection,
6626 &display_map,
6627 &mut selections,
6628 );
6629
6630 // Move the text spanned by the row range to be before the line preceding the row range
6631 if start_row.0 > 0 {
6632 let range_to_move = Point::new(
6633 start_row.previous_row().0,
6634 buffer.line_len(start_row.previous_row()),
6635 )
6636 ..Point::new(
6637 end_row.previous_row().0,
6638 buffer.line_len(end_row.previous_row()),
6639 );
6640 let insertion_point = display_map
6641 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6642 .0;
6643
6644 // Don't move lines across excerpts
6645 if buffer
6646 .excerpt_boundaries_in_range((
6647 Bound::Excluded(insertion_point),
6648 Bound::Included(range_to_move.end),
6649 ))
6650 .next()
6651 .is_none()
6652 {
6653 let text = buffer
6654 .text_for_range(range_to_move.clone())
6655 .flat_map(|s| s.chars())
6656 .skip(1)
6657 .chain(['\n'])
6658 .collect::<String>();
6659
6660 edits.push((
6661 buffer.anchor_after(range_to_move.start)
6662 ..buffer.anchor_before(range_to_move.end),
6663 String::new(),
6664 ));
6665 let insertion_anchor = buffer.anchor_after(insertion_point);
6666 edits.push((insertion_anchor..insertion_anchor, text));
6667
6668 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6669
6670 // Move selections up
6671 new_selections.extend(contiguous_row_selections.drain(..).map(
6672 |mut selection| {
6673 selection.start.row -= row_delta;
6674 selection.end.row -= row_delta;
6675 selection
6676 },
6677 ));
6678
6679 // Move folds up
6680 unfold_ranges.push(range_to_move.clone());
6681 for fold in display_map.folds_in_range(
6682 buffer.anchor_before(range_to_move.start)
6683 ..buffer.anchor_after(range_to_move.end),
6684 ) {
6685 let mut start = fold.range.start.to_point(&buffer);
6686 let mut end = fold.range.end.to_point(&buffer);
6687 start.row -= row_delta;
6688 end.row -= row_delta;
6689 refold_ranges.push((start..end, fold.placeholder.clone()));
6690 }
6691 }
6692 }
6693
6694 // If we didn't move line(s), preserve the existing selections
6695 new_selections.append(&mut contiguous_row_selections);
6696 }
6697
6698 self.transact(cx, |this, cx| {
6699 this.unfold_ranges(unfold_ranges, true, true, cx);
6700 this.buffer.update(cx, |buffer, cx| {
6701 for (range, text) in edits {
6702 buffer.edit([(range, text)], None, cx);
6703 }
6704 });
6705 this.fold_ranges(refold_ranges, true, cx);
6706 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6707 s.select(new_selections);
6708 })
6709 });
6710 }
6711
6712 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6713 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6714 let buffer = self.buffer.read(cx).snapshot(cx);
6715
6716 let mut edits = Vec::new();
6717 let mut unfold_ranges = Vec::new();
6718 let mut refold_ranges = Vec::new();
6719
6720 let selections = self.selections.all::<Point>(cx);
6721 let mut selections = selections.iter().peekable();
6722 let mut contiguous_row_selections = Vec::new();
6723 let mut new_selections = Vec::new();
6724
6725 while let Some(selection) = selections.next() {
6726 // Find all the selections that span a contiguous row range
6727 let (start_row, end_row) = consume_contiguous_rows(
6728 &mut contiguous_row_selections,
6729 selection,
6730 &display_map,
6731 &mut selections,
6732 );
6733
6734 // Move the text spanned by the row range to be after the last line of the row range
6735 if end_row.0 <= buffer.max_point().row {
6736 let range_to_move =
6737 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6738 let insertion_point = display_map
6739 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6740 .0;
6741
6742 // Don't move lines across excerpt boundaries
6743 if buffer
6744 .excerpt_boundaries_in_range((
6745 Bound::Excluded(range_to_move.start),
6746 Bound::Included(insertion_point),
6747 ))
6748 .next()
6749 .is_none()
6750 {
6751 let mut text = String::from("\n");
6752 text.extend(buffer.text_for_range(range_to_move.clone()));
6753 text.pop(); // Drop trailing newline
6754 edits.push((
6755 buffer.anchor_after(range_to_move.start)
6756 ..buffer.anchor_before(range_to_move.end),
6757 String::new(),
6758 ));
6759 let insertion_anchor = buffer.anchor_after(insertion_point);
6760 edits.push((insertion_anchor..insertion_anchor, text));
6761
6762 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6763
6764 // Move selections down
6765 new_selections.extend(contiguous_row_selections.drain(..).map(
6766 |mut selection| {
6767 selection.start.row += row_delta;
6768 selection.end.row += row_delta;
6769 selection
6770 },
6771 ));
6772
6773 // Move folds down
6774 unfold_ranges.push(range_to_move.clone());
6775 for fold in display_map.folds_in_range(
6776 buffer.anchor_before(range_to_move.start)
6777 ..buffer.anchor_after(range_to_move.end),
6778 ) {
6779 let mut start = fold.range.start.to_point(&buffer);
6780 let mut end = fold.range.end.to_point(&buffer);
6781 start.row += row_delta;
6782 end.row += row_delta;
6783 refold_ranges.push((start..end, fold.placeholder.clone()));
6784 }
6785 }
6786 }
6787
6788 // If we didn't move line(s), preserve the existing selections
6789 new_selections.append(&mut contiguous_row_selections);
6790 }
6791
6792 self.transact(cx, |this, cx| {
6793 this.unfold_ranges(unfold_ranges, true, true, cx);
6794 this.buffer.update(cx, |buffer, cx| {
6795 for (range, text) in edits {
6796 buffer.edit([(range, text)], None, cx);
6797 }
6798 });
6799 this.fold_ranges(refold_ranges, true, cx);
6800 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6801 });
6802 }
6803
6804 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6805 let text_layout_details = &self.text_layout_details(cx);
6806 self.transact(cx, |this, cx| {
6807 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6808 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6809 let line_mode = s.line_mode;
6810 s.move_with(|display_map, selection| {
6811 if !selection.is_empty() || line_mode {
6812 return;
6813 }
6814
6815 let mut head = selection.head();
6816 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6817 if head.column() == display_map.line_len(head.row()) {
6818 transpose_offset = display_map
6819 .buffer_snapshot
6820 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6821 }
6822
6823 if transpose_offset == 0 {
6824 return;
6825 }
6826
6827 *head.column_mut() += 1;
6828 head = display_map.clip_point(head, Bias::Right);
6829 let goal = SelectionGoal::HorizontalPosition(
6830 display_map
6831 .x_for_display_point(head, text_layout_details)
6832 .into(),
6833 );
6834 selection.collapse_to(head, goal);
6835
6836 let transpose_start = display_map
6837 .buffer_snapshot
6838 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6839 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6840 let transpose_end = display_map
6841 .buffer_snapshot
6842 .clip_offset(transpose_offset + 1, Bias::Right);
6843 if let Some(ch) =
6844 display_map.buffer_snapshot.chars_at(transpose_start).next()
6845 {
6846 edits.push((transpose_start..transpose_offset, String::new()));
6847 edits.push((transpose_end..transpose_end, ch.to_string()));
6848 }
6849 }
6850 });
6851 edits
6852 });
6853 this.buffer
6854 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6855 let selections = this.selections.all::<usize>(cx);
6856 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6857 s.select(selections);
6858 });
6859 });
6860 }
6861
6862 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6863 self.rewrap_impl(true, cx)
6864 }
6865
6866 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6867 let buffer = self.buffer.read(cx).snapshot(cx);
6868 let selections = self.selections.all::<Point>(cx);
6869 let mut selections = selections.iter().peekable();
6870
6871 let mut edits = Vec::new();
6872 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6873
6874 while let Some(selection) = selections.next() {
6875 let mut start_row = selection.start.row;
6876 let mut end_row = selection.end.row;
6877
6878 // Skip selections that overlap with a range that has already been rewrapped.
6879 let selection_range = start_row..end_row;
6880 if rewrapped_row_ranges
6881 .iter()
6882 .any(|range| range.overlaps(&selection_range))
6883 {
6884 continue;
6885 }
6886
6887 let mut should_rewrap = !only_text;
6888
6889 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6890 match language_scope.language_name().0.as_ref() {
6891 "Markdown" | "Plain Text" => {
6892 should_rewrap = true;
6893 }
6894 _ => {}
6895 }
6896 }
6897
6898 // Since not all lines in the selection may be at the same indent
6899 // level, choose the indent size that is the most common between all
6900 // of the lines.
6901 //
6902 // If there is a tie, we use the deepest indent.
6903 let (indent_size, indent_end) = {
6904 let mut indent_size_occurrences = HashMap::default();
6905 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6906
6907 for row in start_row..=end_row {
6908 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6909 rows_by_indent_size.entry(indent).or_default().push(row);
6910 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6911 }
6912
6913 let indent_size = indent_size_occurrences
6914 .into_iter()
6915 .max_by_key(|(indent, count)| (*count, indent.len))
6916 .map(|(indent, _)| indent)
6917 .unwrap_or_default();
6918 let row = rows_by_indent_size[&indent_size][0];
6919 let indent_end = Point::new(row, indent_size.len);
6920
6921 (indent_size, indent_end)
6922 };
6923
6924 let mut line_prefix = indent_size.chars().collect::<String>();
6925
6926 if let Some(comment_prefix) =
6927 buffer
6928 .language_scope_at(selection.head())
6929 .and_then(|language| {
6930 language
6931 .line_comment_prefixes()
6932 .iter()
6933 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6934 .cloned()
6935 })
6936 {
6937 line_prefix.push_str(&comment_prefix);
6938 should_rewrap = true;
6939 }
6940
6941 if selection.is_empty() {
6942 'expand_upwards: while start_row > 0 {
6943 let prev_row = start_row - 1;
6944 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6945 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6946 {
6947 start_row = prev_row;
6948 } else {
6949 break 'expand_upwards;
6950 }
6951 }
6952
6953 'expand_downwards: while end_row < buffer.max_point().row {
6954 let next_row = end_row + 1;
6955 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6956 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6957 {
6958 end_row = next_row;
6959 } else {
6960 break 'expand_downwards;
6961 }
6962 }
6963 }
6964
6965 if !should_rewrap {
6966 continue;
6967 }
6968
6969 let start = Point::new(start_row, 0);
6970 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6971 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6972 let Some(lines_without_prefixes) = selection_text
6973 .lines()
6974 .map(|line| {
6975 line.strip_prefix(&line_prefix)
6976 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6977 .ok_or_else(|| {
6978 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6979 })
6980 })
6981 .collect::<Result<Vec<_>, _>>()
6982 .log_err()
6983 else {
6984 continue;
6985 };
6986
6987 let unwrapped_text = lines_without_prefixes.join(" ");
6988 let wrap_column = buffer
6989 .settings_at(Point::new(start_row, 0), cx)
6990 .preferred_line_length as usize;
6991 let mut wrapped_text = String::new();
6992 let mut current_line = line_prefix.clone();
6993 for word in unwrapped_text.split_whitespace() {
6994 if current_line.len() + word.len() >= wrap_column {
6995 wrapped_text.push_str(¤t_line);
6996 wrapped_text.push('\n');
6997 current_line.truncate(line_prefix.len());
6998 }
6999
7000 if current_line.len() > line_prefix.len() {
7001 current_line.push(' ');
7002 }
7003
7004 current_line.push_str(word);
7005 }
7006
7007 if !current_line.is_empty() {
7008 wrapped_text.push_str(¤t_line);
7009 }
7010
7011 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
7012 let mut offset = start.to_offset(&buffer);
7013 let mut moved_since_edit = true;
7014
7015 for change in diff.iter_all_changes() {
7016 let value = change.value();
7017 match change.tag() {
7018 ChangeTag::Equal => {
7019 offset += value.len();
7020 moved_since_edit = true;
7021 }
7022 ChangeTag::Delete => {
7023 let start = buffer.anchor_after(offset);
7024 let end = buffer.anchor_before(offset + value.len());
7025
7026 if moved_since_edit {
7027 edits.push((start..end, String::new()));
7028 } else {
7029 edits.last_mut().unwrap().0.end = end;
7030 }
7031
7032 offset += value.len();
7033 moved_since_edit = false;
7034 }
7035 ChangeTag::Insert => {
7036 if moved_since_edit {
7037 let anchor = buffer.anchor_after(offset);
7038 edits.push((anchor..anchor, value.to_string()));
7039 } else {
7040 edits.last_mut().unwrap().1.push_str(value);
7041 }
7042
7043 moved_since_edit = false;
7044 }
7045 }
7046 }
7047
7048 rewrapped_row_ranges.push(start_row..=end_row);
7049 }
7050
7051 self.buffer
7052 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7053 }
7054
7055 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7056 let mut text = String::new();
7057 let buffer = self.buffer.read(cx).snapshot(cx);
7058 let mut selections = self.selections.all::<Point>(cx);
7059 let mut clipboard_selections = Vec::with_capacity(selections.len());
7060 {
7061 let max_point = buffer.max_point();
7062 let mut is_first = true;
7063 for selection in &mut selections {
7064 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7065 if is_entire_line {
7066 selection.start = Point::new(selection.start.row, 0);
7067 if !selection.is_empty() && selection.end.column == 0 {
7068 selection.end = cmp::min(max_point, selection.end);
7069 } else {
7070 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7071 }
7072 selection.goal = SelectionGoal::None;
7073 }
7074 if is_first {
7075 is_first = false;
7076 } else {
7077 text += "\n";
7078 }
7079 let mut len = 0;
7080 for chunk in buffer.text_for_range(selection.start..selection.end) {
7081 text.push_str(chunk);
7082 len += chunk.len();
7083 }
7084 clipboard_selections.push(ClipboardSelection {
7085 len,
7086 is_entire_line,
7087 first_line_indent: buffer
7088 .indent_size_for_line(MultiBufferRow(selection.start.row))
7089 .len,
7090 });
7091 }
7092 }
7093
7094 self.transact(cx, |this, cx| {
7095 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7096 s.select(selections);
7097 });
7098 this.insert("", cx);
7099 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7100 text,
7101 clipboard_selections,
7102 ));
7103 });
7104 }
7105
7106 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7107 let selections = self.selections.all::<Point>(cx);
7108 let buffer = self.buffer.read(cx).read(cx);
7109 let mut text = String::new();
7110
7111 let mut clipboard_selections = Vec::with_capacity(selections.len());
7112 {
7113 let max_point = buffer.max_point();
7114 let mut is_first = true;
7115 for selection in selections.iter() {
7116 let mut start = selection.start;
7117 let mut end = selection.end;
7118 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7119 if is_entire_line {
7120 start = Point::new(start.row, 0);
7121 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7122 }
7123 if is_first {
7124 is_first = false;
7125 } else {
7126 text += "\n";
7127 }
7128 let mut len = 0;
7129 for chunk in buffer.text_for_range(start..end) {
7130 text.push_str(chunk);
7131 len += chunk.len();
7132 }
7133 clipboard_selections.push(ClipboardSelection {
7134 len,
7135 is_entire_line,
7136 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7137 });
7138 }
7139 }
7140
7141 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7142 text,
7143 clipboard_selections,
7144 ));
7145 }
7146
7147 pub fn do_paste(
7148 &mut self,
7149 text: &String,
7150 clipboard_selections: Option<Vec<ClipboardSelection>>,
7151 handle_entire_lines: bool,
7152 cx: &mut ViewContext<Self>,
7153 ) {
7154 if self.read_only(cx) {
7155 return;
7156 }
7157
7158 let clipboard_text = Cow::Borrowed(text);
7159
7160 self.transact(cx, |this, cx| {
7161 if let Some(mut clipboard_selections) = clipboard_selections {
7162 let old_selections = this.selections.all::<usize>(cx);
7163 let all_selections_were_entire_line =
7164 clipboard_selections.iter().all(|s| s.is_entire_line);
7165 let first_selection_indent_column =
7166 clipboard_selections.first().map(|s| s.first_line_indent);
7167 if clipboard_selections.len() != old_selections.len() {
7168 clipboard_selections.drain(..);
7169 }
7170
7171 this.buffer.update(cx, |buffer, cx| {
7172 let snapshot = buffer.read(cx);
7173 let mut start_offset = 0;
7174 let mut edits = Vec::new();
7175 let mut original_indent_columns = Vec::new();
7176 for (ix, selection) in old_selections.iter().enumerate() {
7177 let to_insert;
7178 let entire_line;
7179 let original_indent_column;
7180 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7181 let end_offset = start_offset + clipboard_selection.len;
7182 to_insert = &clipboard_text[start_offset..end_offset];
7183 entire_line = clipboard_selection.is_entire_line;
7184 start_offset = end_offset + 1;
7185 original_indent_column = Some(clipboard_selection.first_line_indent);
7186 } else {
7187 to_insert = clipboard_text.as_str();
7188 entire_line = all_selections_were_entire_line;
7189 original_indent_column = first_selection_indent_column
7190 }
7191
7192 // If the corresponding selection was empty when this slice of the
7193 // clipboard text was written, then the entire line containing the
7194 // selection was copied. If this selection is also currently empty,
7195 // then paste the line before the current line of the buffer.
7196 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7197 let column = selection.start.to_point(&snapshot).column as usize;
7198 let line_start = selection.start - column;
7199 line_start..line_start
7200 } else {
7201 selection.range()
7202 };
7203
7204 edits.push((range, to_insert));
7205 original_indent_columns.extend(original_indent_column);
7206 }
7207 drop(snapshot);
7208
7209 buffer.edit(
7210 edits,
7211 Some(AutoindentMode::Block {
7212 original_indent_columns,
7213 }),
7214 cx,
7215 );
7216 });
7217
7218 let selections = this.selections.all::<usize>(cx);
7219 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7220 } else {
7221 this.insert(&clipboard_text, cx);
7222 }
7223 });
7224 }
7225
7226 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7227 if let Some(item) = cx.read_from_clipboard() {
7228 let entries = item.entries();
7229
7230 match entries.first() {
7231 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7232 // of all the pasted entries.
7233 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7234 .do_paste(
7235 clipboard_string.text(),
7236 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7237 true,
7238 cx,
7239 ),
7240 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7241 }
7242 }
7243 }
7244
7245 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7246 if self.read_only(cx) {
7247 return;
7248 }
7249
7250 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7251 if let Some((selections, _)) =
7252 self.selection_history.transaction(transaction_id).cloned()
7253 {
7254 self.change_selections(None, cx, |s| {
7255 s.select_anchors(selections.to_vec());
7256 });
7257 }
7258 self.request_autoscroll(Autoscroll::fit(), cx);
7259 self.unmark_text(cx);
7260 self.refresh_inline_completion(true, false, cx);
7261 cx.emit(EditorEvent::Edited { transaction_id });
7262 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7263 }
7264 }
7265
7266 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7267 if self.read_only(cx) {
7268 return;
7269 }
7270
7271 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7272 if let Some((_, Some(selections))) =
7273 self.selection_history.transaction(transaction_id).cloned()
7274 {
7275 self.change_selections(None, cx, |s| {
7276 s.select_anchors(selections.to_vec());
7277 });
7278 }
7279 self.request_autoscroll(Autoscroll::fit(), cx);
7280 self.unmark_text(cx);
7281 self.refresh_inline_completion(true, false, cx);
7282 cx.emit(EditorEvent::Edited { transaction_id });
7283 }
7284 }
7285
7286 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7287 self.buffer
7288 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7289 }
7290
7291 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7292 self.buffer
7293 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7294 }
7295
7296 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7297 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7298 let line_mode = s.line_mode;
7299 s.move_with(|map, selection| {
7300 let cursor = if selection.is_empty() && !line_mode {
7301 movement::left(map, selection.start)
7302 } else {
7303 selection.start
7304 };
7305 selection.collapse_to(cursor, SelectionGoal::None);
7306 });
7307 })
7308 }
7309
7310 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7311 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7312 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7313 })
7314 }
7315
7316 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7317 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7318 let line_mode = s.line_mode;
7319 s.move_with(|map, selection| {
7320 let cursor = if selection.is_empty() && !line_mode {
7321 movement::right(map, selection.end)
7322 } else {
7323 selection.end
7324 };
7325 selection.collapse_to(cursor, SelectionGoal::None)
7326 });
7327 })
7328 }
7329
7330 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7331 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7332 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7333 })
7334 }
7335
7336 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7337 if self.take_rename(true, cx).is_some() {
7338 return;
7339 }
7340
7341 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7342 cx.propagate();
7343 return;
7344 }
7345
7346 let text_layout_details = &self.text_layout_details(cx);
7347 let selection_count = self.selections.count();
7348 let first_selection = self.selections.first_anchor();
7349
7350 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7351 let line_mode = s.line_mode;
7352 s.move_with(|map, selection| {
7353 if !selection.is_empty() && !line_mode {
7354 selection.goal = SelectionGoal::None;
7355 }
7356 let (cursor, goal) = movement::up(
7357 map,
7358 selection.start,
7359 selection.goal,
7360 false,
7361 text_layout_details,
7362 );
7363 selection.collapse_to(cursor, goal);
7364 });
7365 });
7366
7367 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7368 {
7369 cx.propagate();
7370 }
7371 }
7372
7373 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7374 if self.take_rename(true, cx).is_some() {
7375 return;
7376 }
7377
7378 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7379 cx.propagate();
7380 return;
7381 }
7382
7383 let text_layout_details = &self.text_layout_details(cx);
7384
7385 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7386 let line_mode = s.line_mode;
7387 s.move_with(|map, selection| {
7388 if !selection.is_empty() && !line_mode {
7389 selection.goal = SelectionGoal::None;
7390 }
7391 let (cursor, goal) = movement::up_by_rows(
7392 map,
7393 selection.start,
7394 action.lines,
7395 selection.goal,
7396 false,
7397 text_layout_details,
7398 );
7399 selection.collapse_to(cursor, goal);
7400 });
7401 })
7402 }
7403
7404 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7405 if self.take_rename(true, cx).is_some() {
7406 return;
7407 }
7408
7409 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7410 cx.propagate();
7411 return;
7412 }
7413
7414 let text_layout_details = &self.text_layout_details(cx);
7415
7416 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7417 let line_mode = s.line_mode;
7418 s.move_with(|map, selection| {
7419 if !selection.is_empty() && !line_mode {
7420 selection.goal = SelectionGoal::None;
7421 }
7422 let (cursor, goal) = movement::down_by_rows(
7423 map,
7424 selection.start,
7425 action.lines,
7426 selection.goal,
7427 false,
7428 text_layout_details,
7429 );
7430 selection.collapse_to(cursor, goal);
7431 });
7432 })
7433 }
7434
7435 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7436 let text_layout_details = &self.text_layout_details(cx);
7437 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7438 s.move_heads_with(|map, head, goal| {
7439 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7440 })
7441 })
7442 }
7443
7444 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7445 let text_layout_details = &self.text_layout_details(cx);
7446 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7447 s.move_heads_with(|map, head, goal| {
7448 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7449 })
7450 })
7451 }
7452
7453 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7454 let Some(row_count) = self.visible_row_count() else {
7455 return;
7456 };
7457
7458 let text_layout_details = &self.text_layout_details(cx);
7459
7460 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7461 s.move_heads_with(|map, head, goal| {
7462 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7463 })
7464 })
7465 }
7466
7467 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7468 if self.take_rename(true, cx).is_some() {
7469 return;
7470 }
7471
7472 if self
7473 .context_menu
7474 .write()
7475 .as_mut()
7476 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7477 .unwrap_or(false)
7478 {
7479 return;
7480 }
7481
7482 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7483 cx.propagate();
7484 return;
7485 }
7486
7487 let Some(row_count) = self.visible_row_count() else {
7488 return;
7489 };
7490
7491 let autoscroll = if action.center_cursor {
7492 Autoscroll::center()
7493 } else {
7494 Autoscroll::fit()
7495 };
7496
7497 let text_layout_details = &self.text_layout_details(cx);
7498
7499 self.change_selections(Some(autoscroll), cx, |s| {
7500 let line_mode = s.line_mode;
7501 s.move_with(|map, selection| {
7502 if !selection.is_empty() && !line_mode {
7503 selection.goal = SelectionGoal::None;
7504 }
7505 let (cursor, goal) = movement::up_by_rows(
7506 map,
7507 selection.end,
7508 row_count,
7509 selection.goal,
7510 false,
7511 text_layout_details,
7512 );
7513 selection.collapse_to(cursor, goal);
7514 });
7515 });
7516 }
7517
7518 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7519 let text_layout_details = &self.text_layout_details(cx);
7520 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7521 s.move_heads_with(|map, head, goal| {
7522 movement::up(map, head, goal, false, text_layout_details)
7523 })
7524 })
7525 }
7526
7527 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7528 self.take_rename(true, cx);
7529
7530 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7531 cx.propagate();
7532 return;
7533 }
7534
7535 let text_layout_details = &self.text_layout_details(cx);
7536 let selection_count = self.selections.count();
7537 let first_selection = self.selections.first_anchor();
7538
7539 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7540 let line_mode = s.line_mode;
7541 s.move_with(|map, selection| {
7542 if !selection.is_empty() && !line_mode {
7543 selection.goal = SelectionGoal::None;
7544 }
7545 let (cursor, goal) = movement::down(
7546 map,
7547 selection.end,
7548 selection.goal,
7549 false,
7550 text_layout_details,
7551 );
7552 selection.collapse_to(cursor, goal);
7553 });
7554 });
7555
7556 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7557 {
7558 cx.propagate();
7559 }
7560 }
7561
7562 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7563 let Some(row_count) = self.visible_row_count() else {
7564 return;
7565 };
7566
7567 let text_layout_details = &self.text_layout_details(cx);
7568
7569 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7570 s.move_heads_with(|map, head, goal| {
7571 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7572 })
7573 })
7574 }
7575
7576 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7577 if self.take_rename(true, cx).is_some() {
7578 return;
7579 }
7580
7581 if self
7582 .context_menu
7583 .write()
7584 .as_mut()
7585 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7586 .unwrap_or(false)
7587 {
7588 return;
7589 }
7590
7591 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7592 cx.propagate();
7593 return;
7594 }
7595
7596 let Some(row_count) = self.visible_row_count() else {
7597 return;
7598 };
7599
7600 let autoscroll = if action.center_cursor {
7601 Autoscroll::center()
7602 } else {
7603 Autoscroll::fit()
7604 };
7605
7606 let text_layout_details = &self.text_layout_details(cx);
7607 self.change_selections(Some(autoscroll), cx, |s| {
7608 let line_mode = s.line_mode;
7609 s.move_with(|map, selection| {
7610 if !selection.is_empty() && !line_mode {
7611 selection.goal = SelectionGoal::None;
7612 }
7613 let (cursor, goal) = movement::down_by_rows(
7614 map,
7615 selection.end,
7616 row_count,
7617 selection.goal,
7618 false,
7619 text_layout_details,
7620 );
7621 selection.collapse_to(cursor, goal);
7622 });
7623 });
7624 }
7625
7626 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7627 let text_layout_details = &self.text_layout_details(cx);
7628 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7629 s.move_heads_with(|map, head, goal| {
7630 movement::down(map, head, goal, false, text_layout_details)
7631 })
7632 });
7633 }
7634
7635 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7636 if let Some(context_menu) = self.context_menu.write().as_mut() {
7637 context_menu.select_first(self.completion_provider.as_deref(), cx);
7638 }
7639 }
7640
7641 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7642 if let Some(context_menu) = self.context_menu.write().as_mut() {
7643 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7644 }
7645 }
7646
7647 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7648 if let Some(context_menu) = self.context_menu.write().as_mut() {
7649 context_menu.select_next(self.completion_provider.as_deref(), cx);
7650 }
7651 }
7652
7653 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7654 if let Some(context_menu) = self.context_menu.write().as_mut() {
7655 context_menu.select_last(self.completion_provider.as_deref(), cx);
7656 }
7657 }
7658
7659 pub fn move_to_previous_word_start(
7660 &mut self,
7661 _: &MoveToPreviousWordStart,
7662 cx: &mut ViewContext<Self>,
7663 ) {
7664 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7665 s.move_cursors_with(|map, head, _| {
7666 (
7667 movement::previous_word_start(map, head),
7668 SelectionGoal::None,
7669 )
7670 });
7671 })
7672 }
7673
7674 pub fn move_to_previous_subword_start(
7675 &mut self,
7676 _: &MoveToPreviousSubwordStart,
7677 cx: &mut ViewContext<Self>,
7678 ) {
7679 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7680 s.move_cursors_with(|map, head, _| {
7681 (
7682 movement::previous_subword_start(map, head),
7683 SelectionGoal::None,
7684 )
7685 });
7686 })
7687 }
7688
7689 pub fn select_to_previous_word_start(
7690 &mut self,
7691 _: &SelectToPreviousWordStart,
7692 cx: &mut ViewContext<Self>,
7693 ) {
7694 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7695 s.move_heads_with(|map, head, _| {
7696 (
7697 movement::previous_word_start(map, head),
7698 SelectionGoal::None,
7699 )
7700 });
7701 })
7702 }
7703
7704 pub fn select_to_previous_subword_start(
7705 &mut self,
7706 _: &SelectToPreviousSubwordStart,
7707 cx: &mut ViewContext<Self>,
7708 ) {
7709 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7710 s.move_heads_with(|map, head, _| {
7711 (
7712 movement::previous_subword_start(map, head),
7713 SelectionGoal::None,
7714 )
7715 });
7716 })
7717 }
7718
7719 pub fn delete_to_previous_word_start(
7720 &mut self,
7721 action: &DeleteToPreviousWordStart,
7722 cx: &mut ViewContext<Self>,
7723 ) {
7724 self.transact(cx, |this, cx| {
7725 this.select_autoclose_pair(cx);
7726 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7727 let line_mode = s.line_mode;
7728 s.move_with(|map, selection| {
7729 if selection.is_empty() && !line_mode {
7730 let cursor = if action.ignore_newlines {
7731 movement::previous_word_start(map, selection.head())
7732 } else {
7733 movement::previous_word_start_or_newline(map, selection.head())
7734 };
7735 selection.set_head(cursor, SelectionGoal::None);
7736 }
7737 });
7738 });
7739 this.insert("", cx);
7740 });
7741 }
7742
7743 pub fn delete_to_previous_subword_start(
7744 &mut self,
7745 _: &DeleteToPreviousSubwordStart,
7746 cx: &mut ViewContext<Self>,
7747 ) {
7748 self.transact(cx, |this, cx| {
7749 this.select_autoclose_pair(cx);
7750 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7751 let line_mode = s.line_mode;
7752 s.move_with(|map, selection| {
7753 if selection.is_empty() && !line_mode {
7754 let cursor = movement::previous_subword_start(map, selection.head());
7755 selection.set_head(cursor, SelectionGoal::None);
7756 }
7757 });
7758 });
7759 this.insert("", cx);
7760 });
7761 }
7762
7763 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7764 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7765 s.move_cursors_with(|map, head, _| {
7766 (movement::next_word_end(map, head), SelectionGoal::None)
7767 });
7768 })
7769 }
7770
7771 pub fn move_to_next_subword_end(
7772 &mut self,
7773 _: &MoveToNextSubwordEnd,
7774 cx: &mut ViewContext<Self>,
7775 ) {
7776 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7777 s.move_cursors_with(|map, head, _| {
7778 (movement::next_subword_end(map, head), SelectionGoal::None)
7779 });
7780 })
7781 }
7782
7783 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7784 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7785 s.move_heads_with(|map, head, _| {
7786 (movement::next_word_end(map, head), SelectionGoal::None)
7787 });
7788 })
7789 }
7790
7791 pub fn select_to_next_subword_end(
7792 &mut self,
7793 _: &SelectToNextSubwordEnd,
7794 cx: &mut ViewContext<Self>,
7795 ) {
7796 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7797 s.move_heads_with(|map, head, _| {
7798 (movement::next_subword_end(map, head), SelectionGoal::None)
7799 });
7800 })
7801 }
7802
7803 pub fn delete_to_next_word_end(
7804 &mut self,
7805 action: &DeleteToNextWordEnd,
7806 cx: &mut ViewContext<Self>,
7807 ) {
7808 self.transact(cx, |this, cx| {
7809 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7810 let line_mode = s.line_mode;
7811 s.move_with(|map, selection| {
7812 if selection.is_empty() && !line_mode {
7813 let cursor = if action.ignore_newlines {
7814 movement::next_word_end(map, selection.head())
7815 } else {
7816 movement::next_word_end_or_newline(map, selection.head())
7817 };
7818 selection.set_head(cursor, SelectionGoal::None);
7819 }
7820 });
7821 });
7822 this.insert("", cx);
7823 });
7824 }
7825
7826 pub fn delete_to_next_subword_end(
7827 &mut self,
7828 _: &DeleteToNextSubwordEnd,
7829 cx: &mut ViewContext<Self>,
7830 ) {
7831 self.transact(cx, |this, cx| {
7832 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7833 s.move_with(|map, selection| {
7834 if selection.is_empty() {
7835 let cursor = movement::next_subword_end(map, selection.head());
7836 selection.set_head(cursor, SelectionGoal::None);
7837 }
7838 });
7839 });
7840 this.insert("", cx);
7841 });
7842 }
7843
7844 pub fn move_to_beginning_of_line(
7845 &mut self,
7846 action: &MoveToBeginningOfLine,
7847 cx: &mut ViewContext<Self>,
7848 ) {
7849 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7850 s.move_cursors_with(|map, head, _| {
7851 (
7852 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7853 SelectionGoal::None,
7854 )
7855 });
7856 })
7857 }
7858
7859 pub fn select_to_beginning_of_line(
7860 &mut self,
7861 action: &SelectToBeginningOfLine,
7862 cx: &mut ViewContext<Self>,
7863 ) {
7864 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7865 s.move_heads_with(|map, head, _| {
7866 (
7867 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7868 SelectionGoal::None,
7869 )
7870 });
7871 });
7872 }
7873
7874 pub fn delete_to_beginning_of_line(
7875 &mut self,
7876 _: &DeleteToBeginningOfLine,
7877 cx: &mut ViewContext<Self>,
7878 ) {
7879 self.transact(cx, |this, cx| {
7880 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7881 s.move_with(|_, selection| {
7882 selection.reversed = true;
7883 });
7884 });
7885
7886 this.select_to_beginning_of_line(
7887 &SelectToBeginningOfLine {
7888 stop_at_soft_wraps: false,
7889 },
7890 cx,
7891 );
7892 this.backspace(&Backspace, cx);
7893 });
7894 }
7895
7896 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7897 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7898 s.move_cursors_with(|map, head, _| {
7899 (
7900 movement::line_end(map, head, action.stop_at_soft_wraps),
7901 SelectionGoal::None,
7902 )
7903 });
7904 })
7905 }
7906
7907 pub fn select_to_end_of_line(
7908 &mut self,
7909 action: &SelectToEndOfLine,
7910 cx: &mut ViewContext<Self>,
7911 ) {
7912 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7913 s.move_heads_with(|map, head, _| {
7914 (
7915 movement::line_end(map, head, action.stop_at_soft_wraps),
7916 SelectionGoal::None,
7917 )
7918 });
7919 })
7920 }
7921
7922 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7923 self.transact(cx, |this, cx| {
7924 this.select_to_end_of_line(
7925 &SelectToEndOfLine {
7926 stop_at_soft_wraps: false,
7927 },
7928 cx,
7929 );
7930 this.delete(&Delete, cx);
7931 });
7932 }
7933
7934 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7935 self.transact(cx, |this, cx| {
7936 this.select_to_end_of_line(
7937 &SelectToEndOfLine {
7938 stop_at_soft_wraps: false,
7939 },
7940 cx,
7941 );
7942 this.cut(&Cut, cx);
7943 });
7944 }
7945
7946 pub fn move_to_start_of_paragraph(
7947 &mut self,
7948 _: &MoveToStartOfParagraph,
7949 cx: &mut ViewContext<Self>,
7950 ) {
7951 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7952 cx.propagate();
7953 return;
7954 }
7955
7956 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7957 s.move_with(|map, selection| {
7958 selection.collapse_to(
7959 movement::start_of_paragraph(map, selection.head(), 1),
7960 SelectionGoal::None,
7961 )
7962 });
7963 })
7964 }
7965
7966 pub fn move_to_end_of_paragraph(
7967 &mut self,
7968 _: &MoveToEndOfParagraph,
7969 cx: &mut ViewContext<Self>,
7970 ) {
7971 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7972 cx.propagate();
7973 return;
7974 }
7975
7976 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7977 s.move_with(|map, selection| {
7978 selection.collapse_to(
7979 movement::end_of_paragraph(map, selection.head(), 1),
7980 SelectionGoal::None,
7981 )
7982 });
7983 })
7984 }
7985
7986 pub fn select_to_start_of_paragraph(
7987 &mut self,
7988 _: &SelectToStartOfParagraph,
7989 cx: &mut ViewContext<Self>,
7990 ) {
7991 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7992 cx.propagate();
7993 return;
7994 }
7995
7996 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7997 s.move_heads_with(|map, head, _| {
7998 (
7999 movement::start_of_paragraph(map, head, 1),
8000 SelectionGoal::None,
8001 )
8002 });
8003 })
8004 }
8005
8006 pub fn select_to_end_of_paragraph(
8007 &mut self,
8008 _: &SelectToEndOfParagraph,
8009 cx: &mut ViewContext<Self>,
8010 ) {
8011 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8012 cx.propagate();
8013 return;
8014 }
8015
8016 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8017 s.move_heads_with(|map, head, _| {
8018 (
8019 movement::end_of_paragraph(map, head, 1),
8020 SelectionGoal::None,
8021 )
8022 });
8023 })
8024 }
8025
8026 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8027 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8028 cx.propagate();
8029 return;
8030 }
8031
8032 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8033 s.select_ranges(vec![0..0]);
8034 });
8035 }
8036
8037 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8038 let mut selection = self.selections.last::<Point>(cx);
8039 selection.set_head(Point::zero(), SelectionGoal::None);
8040
8041 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8042 s.select(vec![selection]);
8043 });
8044 }
8045
8046 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8047 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8048 cx.propagate();
8049 return;
8050 }
8051
8052 let cursor = self.buffer.read(cx).read(cx).len();
8053 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8054 s.select_ranges(vec![cursor..cursor])
8055 });
8056 }
8057
8058 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8059 self.nav_history = nav_history;
8060 }
8061
8062 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8063 self.nav_history.as_ref()
8064 }
8065
8066 fn push_to_nav_history(
8067 &mut self,
8068 cursor_anchor: Anchor,
8069 new_position: Option<Point>,
8070 cx: &mut ViewContext<Self>,
8071 ) {
8072 if let Some(nav_history) = self.nav_history.as_mut() {
8073 let buffer = self.buffer.read(cx).read(cx);
8074 let cursor_position = cursor_anchor.to_point(&buffer);
8075 let scroll_state = self.scroll_manager.anchor();
8076 let scroll_top_row = scroll_state.top_row(&buffer);
8077 drop(buffer);
8078
8079 if let Some(new_position) = new_position {
8080 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8081 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8082 return;
8083 }
8084 }
8085
8086 nav_history.push(
8087 Some(NavigationData {
8088 cursor_anchor,
8089 cursor_position,
8090 scroll_anchor: scroll_state,
8091 scroll_top_row,
8092 }),
8093 cx,
8094 );
8095 }
8096 }
8097
8098 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8099 let buffer = self.buffer.read(cx).snapshot(cx);
8100 let mut selection = self.selections.first::<usize>(cx);
8101 selection.set_head(buffer.len(), SelectionGoal::None);
8102 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8103 s.select(vec![selection]);
8104 });
8105 }
8106
8107 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8108 let end = self.buffer.read(cx).read(cx).len();
8109 self.change_selections(None, cx, |s| {
8110 s.select_ranges(vec![0..end]);
8111 });
8112 }
8113
8114 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8115 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8116 let mut selections = self.selections.all::<Point>(cx);
8117 let max_point = display_map.buffer_snapshot.max_point();
8118 for selection in &mut selections {
8119 let rows = selection.spanned_rows(true, &display_map);
8120 selection.start = Point::new(rows.start.0, 0);
8121 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8122 selection.reversed = false;
8123 }
8124 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8125 s.select(selections);
8126 });
8127 }
8128
8129 pub fn split_selection_into_lines(
8130 &mut self,
8131 _: &SplitSelectionIntoLines,
8132 cx: &mut ViewContext<Self>,
8133 ) {
8134 let mut to_unfold = Vec::new();
8135 let mut new_selection_ranges = Vec::new();
8136 {
8137 let selections = self.selections.all::<Point>(cx);
8138 let buffer = self.buffer.read(cx).read(cx);
8139 for selection in selections {
8140 for row in selection.start.row..selection.end.row {
8141 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8142 new_selection_ranges.push(cursor..cursor);
8143 }
8144 new_selection_ranges.push(selection.end..selection.end);
8145 to_unfold.push(selection.start..selection.end);
8146 }
8147 }
8148 self.unfold_ranges(to_unfold, true, true, cx);
8149 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8150 s.select_ranges(new_selection_ranges);
8151 });
8152 }
8153
8154 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8155 self.add_selection(true, cx);
8156 }
8157
8158 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8159 self.add_selection(false, cx);
8160 }
8161
8162 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8163 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8164 let mut selections = self.selections.all::<Point>(cx);
8165 let text_layout_details = self.text_layout_details(cx);
8166 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8167 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8168 let range = oldest_selection.display_range(&display_map).sorted();
8169
8170 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8171 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8172 let positions = start_x.min(end_x)..start_x.max(end_x);
8173
8174 selections.clear();
8175 let mut stack = Vec::new();
8176 for row in range.start.row().0..=range.end.row().0 {
8177 if let Some(selection) = self.selections.build_columnar_selection(
8178 &display_map,
8179 DisplayRow(row),
8180 &positions,
8181 oldest_selection.reversed,
8182 &text_layout_details,
8183 ) {
8184 stack.push(selection.id);
8185 selections.push(selection);
8186 }
8187 }
8188
8189 if above {
8190 stack.reverse();
8191 }
8192
8193 AddSelectionsState { above, stack }
8194 });
8195
8196 let last_added_selection = *state.stack.last().unwrap();
8197 let mut new_selections = Vec::new();
8198 if above == state.above {
8199 let end_row = if above {
8200 DisplayRow(0)
8201 } else {
8202 display_map.max_point().row()
8203 };
8204
8205 'outer: for selection in selections {
8206 if selection.id == last_added_selection {
8207 let range = selection.display_range(&display_map).sorted();
8208 debug_assert_eq!(range.start.row(), range.end.row());
8209 let mut row = range.start.row();
8210 let positions =
8211 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8212 px(start)..px(end)
8213 } else {
8214 let start_x =
8215 display_map.x_for_display_point(range.start, &text_layout_details);
8216 let end_x =
8217 display_map.x_for_display_point(range.end, &text_layout_details);
8218 start_x.min(end_x)..start_x.max(end_x)
8219 };
8220
8221 while row != end_row {
8222 if above {
8223 row.0 -= 1;
8224 } else {
8225 row.0 += 1;
8226 }
8227
8228 if let Some(new_selection) = self.selections.build_columnar_selection(
8229 &display_map,
8230 row,
8231 &positions,
8232 selection.reversed,
8233 &text_layout_details,
8234 ) {
8235 state.stack.push(new_selection.id);
8236 if above {
8237 new_selections.push(new_selection);
8238 new_selections.push(selection);
8239 } else {
8240 new_selections.push(selection);
8241 new_selections.push(new_selection);
8242 }
8243
8244 continue 'outer;
8245 }
8246 }
8247 }
8248
8249 new_selections.push(selection);
8250 }
8251 } else {
8252 new_selections = selections;
8253 new_selections.retain(|s| s.id != last_added_selection);
8254 state.stack.pop();
8255 }
8256
8257 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8258 s.select(new_selections);
8259 });
8260 if state.stack.len() > 1 {
8261 self.add_selections_state = Some(state);
8262 }
8263 }
8264
8265 pub fn select_next_match_internal(
8266 &mut self,
8267 display_map: &DisplaySnapshot,
8268 replace_newest: bool,
8269 autoscroll: Option<Autoscroll>,
8270 cx: &mut ViewContext<Self>,
8271 ) -> Result<()> {
8272 fn select_next_match_ranges(
8273 this: &mut Editor,
8274 range: Range<usize>,
8275 replace_newest: bool,
8276 auto_scroll: Option<Autoscroll>,
8277 cx: &mut ViewContext<Editor>,
8278 ) {
8279 this.unfold_ranges([range.clone()], false, true, cx);
8280 this.change_selections(auto_scroll, cx, |s| {
8281 if replace_newest {
8282 s.delete(s.newest_anchor().id);
8283 }
8284 s.insert_range(range.clone());
8285 });
8286 }
8287
8288 let buffer = &display_map.buffer_snapshot;
8289 let mut selections = self.selections.all::<usize>(cx);
8290 if let Some(mut select_next_state) = self.select_next_state.take() {
8291 let query = &select_next_state.query;
8292 if !select_next_state.done {
8293 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8294 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8295 let mut next_selected_range = None;
8296
8297 let bytes_after_last_selection =
8298 buffer.bytes_in_range(last_selection.end..buffer.len());
8299 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8300 let query_matches = query
8301 .stream_find_iter(bytes_after_last_selection)
8302 .map(|result| (last_selection.end, result))
8303 .chain(
8304 query
8305 .stream_find_iter(bytes_before_first_selection)
8306 .map(|result| (0, result)),
8307 );
8308
8309 for (start_offset, query_match) in query_matches {
8310 let query_match = query_match.unwrap(); // can only fail due to I/O
8311 let offset_range =
8312 start_offset + query_match.start()..start_offset + query_match.end();
8313 let display_range = offset_range.start.to_display_point(display_map)
8314 ..offset_range.end.to_display_point(display_map);
8315
8316 if !select_next_state.wordwise
8317 || (!movement::is_inside_word(display_map, display_range.start)
8318 && !movement::is_inside_word(display_map, display_range.end))
8319 {
8320 // TODO: This is n^2, because we might check all the selections
8321 if !selections
8322 .iter()
8323 .any(|selection| selection.range().overlaps(&offset_range))
8324 {
8325 next_selected_range = Some(offset_range);
8326 break;
8327 }
8328 }
8329 }
8330
8331 if let Some(next_selected_range) = next_selected_range {
8332 select_next_match_ranges(
8333 self,
8334 next_selected_range,
8335 replace_newest,
8336 autoscroll,
8337 cx,
8338 );
8339 } else {
8340 select_next_state.done = true;
8341 }
8342 }
8343
8344 self.select_next_state = Some(select_next_state);
8345 } else {
8346 let mut only_carets = true;
8347 let mut same_text_selected = true;
8348 let mut selected_text = None;
8349
8350 let mut selections_iter = selections.iter().peekable();
8351 while let Some(selection) = selections_iter.next() {
8352 if selection.start != selection.end {
8353 only_carets = false;
8354 }
8355
8356 if same_text_selected {
8357 if selected_text.is_none() {
8358 selected_text =
8359 Some(buffer.text_for_range(selection.range()).collect::<String>());
8360 }
8361
8362 if let Some(next_selection) = selections_iter.peek() {
8363 if next_selection.range().len() == selection.range().len() {
8364 let next_selected_text = buffer
8365 .text_for_range(next_selection.range())
8366 .collect::<String>();
8367 if Some(next_selected_text) != selected_text {
8368 same_text_selected = false;
8369 selected_text = None;
8370 }
8371 } else {
8372 same_text_selected = false;
8373 selected_text = None;
8374 }
8375 }
8376 }
8377 }
8378
8379 if only_carets {
8380 for selection in &mut selections {
8381 let word_range = movement::surrounding_word(
8382 display_map,
8383 selection.start.to_display_point(display_map),
8384 );
8385 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8386 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8387 selection.goal = SelectionGoal::None;
8388 selection.reversed = false;
8389 select_next_match_ranges(
8390 self,
8391 selection.start..selection.end,
8392 replace_newest,
8393 autoscroll,
8394 cx,
8395 );
8396 }
8397
8398 if selections.len() == 1 {
8399 let selection = selections
8400 .last()
8401 .expect("ensured that there's only one selection");
8402 let query = buffer
8403 .text_for_range(selection.start..selection.end)
8404 .collect::<String>();
8405 let is_empty = query.is_empty();
8406 let select_state = SelectNextState {
8407 query: AhoCorasick::new(&[query])?,
8408 wordwise: true,
8409 done: is_empty,
8410 };
8411 self.select_next_state = Some(select_state);
8412 } else {
8413 self.select_next_state = None;
8414 }
8415 } else if let Some(selected_text) = selected_text {
8416 self.select_next_state = Some(SelectNextState {
8417 query: AhoCorasick::new(&[selected_text])?,
8418 wordwise: false,
8419 done: false,
8420 });
8421 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8422 }
8423 }
8424 Ok(())
8425 }
8426
8427 pub fn select_all_matches(
8428 &mut self,
8429 _action: &SelectAllMatches,
8430 cx: &mut ViewContext<Self>,
8431 ) -> Result<()> {
8432 self.push_to_selection_history();
8433 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8434
8435 self.select_next_match_internal(&display_map, false, None, cx)?;
8436 let Some(select_next_state) = self.select_next_state.as_mut() else {
8437 return Ok(());
8438 };
8439 if select_next_state.done {
8440 return Ok(());
8441 }
8442
8443 let mut new_selections = self.selections.all::<usize>(cx);
8444
8445 let buffer = &display_map.buffer_snapshot;
8446 let query_matches = select_next_state
8447 .query
8448 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8449
8450 for query_match in query_matches {
8451 let query_match = query_match.unwrap(); // can only fail due to I/O
8452 let offset_range = query_match.start()..query_match.end();
8453 let display_range = offset_range.start.to_display_point(&display_map)
8454 ..offset_range.end.to_display_point(&display_map);
8455
8456 if !select_next_state.wordwise
8457 || (!movement::is_inside_word(&display_map, display_range.start)
8458 && !movement::is_inside_word(&display_map, display_range.end))
8459 {
8460 self.selections.change_with(cx, |selections| {
8461 new_selections.push(Selection {
8462 id: selections.new_selection_id(),
8463 start: offset_range.start,
8464 end: offset_range.end,
8465 reversed: false,
8466 goal: SelectionGoal::None,
8467 });
8468 });
8469 }
8470 }
8471
8472 new_selections.sort_by_key(|selection| selection.start);
8473 let mut ix = 0;
8474 while ix + 1 < new_selections.len() {
8475 let current_selection = &new_selections[ix];
8476 let next_selection = &new_selections[ix + 1];
8477 if current_selection.range().overlaps(&next_selection.range()) {
8478 if current_selection.id < next_selection.id {
8479 new_selections.remove(ix + 1);
8480 } else {
8481 new_selections.remove(ix);
8482 }
8483 } else {
8484 ix += 1;
8485 }
8486 }
8487
8488 select_next_state.done = true;
8489 self.unfold_ranges(
8490 new_selections.iter().map(|selection| selection.range()),
8491 false,
8492 false,
8493 cx,
8494 );
8495 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8496 selections.select(new_selections)
8497 });
8498
8499 Ok(())
8500 }
8501
8502 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8503 self.push_to_selection_history();
8504 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8505 self.select_next_match_internal(
8506 &display_map,
8507 action.replace_newest,
8508 Some(Autoscroll::newest()),
8509 cx,
8510 )?;
8511 Ok(())
8512 }
8513
8514 pub fn select_previous(
8515 &mut self,
8516 action: &SelectPrevious,
8517 cx: &mut ViewContext<Self>,
8518 ) -> Result<()> {
8519 self.push_to_selection_history();
8520 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8521 let buffer = &display_map.buffer_snapshot;
8522 let mut selections = self.selections.all::<usize>(cx);
8523 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8524 let query = &select_prev_state.query;
8525 if !select_prev_state.done {
8526 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8527 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8528 let mut next_selected_range = None;
8529 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8530 let bytes_before_last_selection =
8531 buffer.reversed_bytes_in_range(0..last_selection.start);
8532 let bytes_after_first_selection =
8533 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8534 let query_matches = query
8535 .stream_find_iter(bytes_before_last_selection)
8536 .map(|result| (last_selection.start, result))
8537 .chain(
8538 query
8539 .stream_find_iter(bytes_after_first_selection)
8540 .map(|result| (buffer.len(), result)),
8541 );
8542 for (end_offset, query_match) in query_matches {
8543 let query_match = query_match.unwrap(); // can only fail due to I/O
8544 let offset_range =
8545 end_offset - query_match.end()..end_offset - query_match.start();
8546 let display_range = offset_range.start.to_display_point(&display_map)
8547 ..offset_range.end.to_display_point(&display_map);
8548
8549 if !select_prev_state.wordwise
8550 || (!movement::is_inside_word(&display_map, display_range.start)
8551 && !movement::is_inside_word(&display_map, display_range.end))
8552 {
8553 next_selected_range = Some(offset_range);
8554 break;
8555 }
8556 }
8557
8558 if let Some(next_selected_range) = next_selected_range {
8559 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8560 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8561 if action.replace_newest {
8562 s.delete(s.newest_anchor().id);
8563 }
8564 s.insert_range(next_selected_range);
8565 });
8566 } else {
8567 select_prev_state.done = true;
8568 }
8569 }
8570
8571 self.select_prev_state = Some(select_prev_state);
8572 } else {
8573 let mut only_carets = true;
8574 let mut same_text_selected = true;
8575 let mut selected_text = None;
8576
8577 let mut selections_iter = selections.iter().peekable();
8578 while let Some(selection) = selections_iter.next() {
8579 if selection.start != selection.end {
8580 only_carets = false;
8581 }
8582
8583 if same_text_selected {
8584 if selected_text.is_none() {
8585 selected_text =
8586 Some(buffer.text_for_range(selection.range()).collect::<String>());
8587 }
8588
8589 if let Some(next_selection) = selections_iter.peek() {
8590 if next_selection.range().len() == selection.range().len() {
8591 let next_selected_text = buffer
8592 .text_for_range(next_selection.range())
8593 .collect::<String>();
8594 if Some(next_selected_text) != selected_text {
8595 same_text_selected = false;
8596 selected_text = None;
8597 }
8598 } else {
8599 same_text_selected = false;
8600 selected_text = None;
8601 }
8602 }
8603 }
8604 }
8605
8606 if only_carets {
8607 for selection in &mut selections {
8608 let word_range = movement::surrounding_word(
8609 &display_map,
8610 selection.start.to_display_point(&display_map),
8611 );
8612 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8613 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8614 selection.goal = SelectionGoal::None;
8615 selection.reversed = false;
8616 }
8617 if selections.len() == 1 {
8618 let selection = selections
8619 .last()
8620 .expect("ensured that there's only one selection");
8621 let query = buffer
8622 .text_for_range(selection.start..selection.end)
8623 .collect::<String>();
8624 let is_empty = query.is_empty();
8625 let select_state = SelectNextState {
8626 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8627 wordwise: true,
8628 done: is_empty,
8629 };
8630 self.select_prev_state = Some(select_state);
8631 } else {
8632 self.select_prev_state = None;
8633 }
8634
8635 self.unfold_ranges(
8636 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8637 false,
8638 true,
8639 cx,
8640 );
8641 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8642 s.select(selections);
8643 });
8644 } else if let Some(selected_text) = selected_text {
8645 self.select_prev_state = Some(SelectNextState {
8646 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8647 wordwise: false,
8648 done: false,
8649 });
8650 self.select_previous(action, cx)?;
8651 }
8652 }
8653 Ok(())
8654 }
8655
8656 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8657 let text_layout_details = &self.text_layout_details(cx);
8658 self.transact(cx, |this, cx| {
8659 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8660 let mut edits = Vec::new();
8661 let mut selection_edit_ranges = Vec::new();
8662 let mut last_toggled_row = None;
8663 let snapshot = this.buffer.read(cx).read(cx);
8664 let empty_str: Arc<str> = Arc::default();
8665 let mut suffixes_inserted = Vec::new();
8666
8667 fn comment_prefix_range(
8668 snapshot: &MultiBufferSnapshot,
8669 row: MultiBufferRow,
8670 comment_prefix: &str,
8671 comment_prefix_whitespace: &str,
8672 ) -> Range<Point> {
8673 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8674
8675 let mut line_bytes = snapshot
8676 .bytes_in_range(start..snapshot.max_point())
8677 .flatten()
8678 .copied();
8679
8680 // If this line currently begins with the line comment prefix, then record
8681 // the range containing the prefix.
8682 if line_bytes
8683 .by_ref()
8684 .take(comment_prefix.len())
8685 .eq(comment_prefix.bytes())
8686 {
8687 // Include any whitespace that matches the comment prefix.
8688 let matching_whitespace_len = line_bytes
8689 .zip(comment_prefix_whitespace.bytes())
8690 .take_while(|(a, b)| a == b)
8691 .count() as u32;
8692 let end = Point::new(
8693 start.row,
8694 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8695 );
8696 start..end
8697 } else {
8698 start..start
8699 }
8700 }
8701
8702 fn comment_suffix_range(
8703 snapshot: &MultiBufferSnapshot,
8704 row: MultiBufferRow,
8705 comment_suffix: &str,
8706 comment_suffix_has_leading_space: bool,
8707 ) -> Range<Point> {
8708 let end = Point::new(row.0, snapshot.line_len(row));
8709 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8710
8711 let mut line_end_bytes = snapshot
8712 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8713 .flatten()
8714 .copied();
8715
8716 let leading_space_len = if suffix_start_column > 0
8717 && line_end_bytes.next() == Some(b' ')
8718 && comment_suffix_has_leading_space
8719 {
8720 1
8721 } else {
8722 0
8723 };
8724
8725 // If this line currently begins with the line comment prefix, then record
8726 // the range containing the prefix.
8727 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8728 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8729 start..end
8730 } else {
8731 end..end
8732 }
8733 }
8734
8735 // TODO: Handle selections that cross excerpts
8736 for selection in &mut selections {
8737 let start_column = snapshot
8738 .indent_size_for_line(MultiBufferRow(selection.start.row))
8739 .len;
8740 let language = if let Some(language) =
8741 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8742 {
8743 language
8744 } else {
8745 continue;
8746 };
8747
8748 selection_edit_ranges.clear();
8749
8750 // If multiple selections contain a given row, avoid processing that
8751 // row more than once.
8752 let mut start_row = MultiBufferRow(selection.start.row);
8753 if last_toggled_row == Some(start_row) {
8754 start_row = start_row.next_row();
8755 }
8756 let end_row =
8757 if selection.end.row > selection.start.row && selection.end.column == 0 {
8758 MultiBufferRow(selection.end.row - 1)
8759 } else {
8760 MultiBufferRow(selection.end.row)
8761 };
8762 last_toggled_row = Some(end_row);
8763
8764 if start_row > end_row {
8765 continue;
8766 }
8767
8768 // If the language has line comments, toggle those.
8769 let full_comment_prefixes = language.line_comment_prefixes();
8770 if !full_comment_prefixes.is_empty() {
8771 let first_prefix = full_comment_prefixes
8772 .first()
8773 .expect("prefixes is non-empty");
8774 let prefix_trimmed_lengths = full_comment_prefixes
8775 .iter()
8776 .map(|p| p.trim_end_matches(' ').len())
8777 .collect::<SmallVec<[usize; 4]>>();
8778
8779 let mut all_selection_lines_are_comments = true;
8780
8781 for row in start_row.0..=end_row.0 {
8782 let row = MultiBufferRow(row);
8783 if start_row < end_row && snapshot.is_line_blank(row) {
8784 continue;
8785 }
8786
8787 let prefix_range = full_comment_prefixes
8788 .iter()
8789 .zip(prefix_trimmed_lengths.iter().copied())
8790 .map(|(prefix, trimmed_prefix_len)| {
8791 comment_prefix_range(
8792 snapshot.deref(),
8793 row,
8794 &prefix[..trimmed_prefix_len],
8795 &prefix[trimmed_prefix_len..],
8796 )
8797 })
8798 .max_by_key(|range| range.end.column - range.start.column)
8799 .expect("prefixes is non-empty");
8800
8801 if prefix_range.is_empty() {
8802 all_selection_lines_are_comments = false;
8803 }
8804
8805 selection_edit_ranges.push(prefix_range);
8806 }
8807
8808 if all_selection_lines_are_comments {
8809 edits.extend(
8810 selection_edit_ranges
8811 .iter()
8812 .cloned()
8813 .map(|range| (range, empty_str.clone())),
8814 );
8815 } else {
8816 let min_column = selection_edit_ranges
8817 .iter()
8818 .map(|range| range.start.column)
8819 .min()
8820 .unwrap_or(0);
8821 edits.extend(selection_edit_ranges.iter().map(|range| {
8822 let position = Point::new(range.start.row, min_column);
8823 (position..position, first_prefix.clone())
8824 }));
8825 }
8826 } else if let Some((full_comment_prefix, comment_suffix)) =
8827 language.block_comment_delimiters()
8828 {
8829 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8830 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8831 let prefix_range = comment_prefix_range(
8832 snapshot.deref(),
8833 start_row,
8834 comment_prefix,
8835 comment_prefix_whitespace,
8836 );
8837 let suffix_range = comment_suffix_range(
8838 snapshot.deref(),
8839 end_row,
8840 comment_suffix.trim_start_matches(' '),
8841 comment_suffix.starts_with(' '),
8842 );
8843
8844 if prefix_range.is_empty() || suffix_range.is_empty() {
8845 edits.push((
8846 prefix_range.start..prefix_range.start,
8847 full_comment_prefix.clone(),
8848 ));
8849 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8850 suffixes_inserted.push((end_row, comment_suffix.len()));
8851 } else {
8852 edits.push((prefix_range, empty_str.clone()));
8853 edits.push((suffix_range, empty_str.clone()));
8854 }
8855 } else {
8856 continue;
8857 }
8858 }
8859
8860 drop(snapshot);
8861 this.buffer.update(cx, |buffer, cx| {
8862 buffer.edit(edits, None, cx);
8863 });
8864
8865 // Adjust selections so that they end before any comment suffixes that
8866 // were inserted.
8867 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8868 let mut selections = this.selections.all::<Point>(cx);
8869 let snapshot = this.buffer.read(cx).read(cx);
8870 for selection in &mut selections {
8871 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8872 match row.cmp(&MultiBufferRow(selection.end.row)) {
8873 Ordering::Less => {
8874 suffixes_inserted.next();
8875 continue;
8876 }
8877 Ordering::Greater => break,
8878 Ordering::Equal => {
8879 if selection.end.column == snapshot.line_len(row) {
8880 if selection.is_empty() {
8881 selection.start.column -= suffix_len as u32;
8882 }
8883 selection.end.column -= suffix_len as u32;
8884 }
8885 break;
8886 }
8887 }
8888 }
8889 }
8890
8891 drop(snapshot);
8892 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8893
8894 let selections = this.selections.all::<Point>(cx);
8895 let selections_on_single_row = selections.windows(2).all(|selections| {
8896 selections[0].start.row == selections[1].start.row
8897 && selections[0].end.row == selections[1].end.row
8898 && selections[0].start.row == selections[0].end.row
8899 });
8900 let selections_selecting = selections
8901 .iter()
8902 .any(|selection| selection.start != selection.end);
8903 let advance_downwards = action.advance_downwards
8904 && selections_on_single_row
8905 && !selections_selecting
8906 && !matches!(this.mode, EditorMode::SingleLine { .. });
8907
8908 if advance_downwards {
8909 let snapshot = this.buffer.read(cx).snapshot(cx);
8910
8911 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8912 s.move_cursors_with(|display_snapshot, display_point, _| {
8913 let mut point = display_point.to_point(display_snapshot);
8914 point.row += 1;
8915 point = snapshot.clip_point(point, Bias::Left);
8916 let display_point = point.to_display_point(display_snapshot);
8917 let goal = SelectionGoal::HorizontalPosition(
8918 display_snapshot
8919 .x_for_display_point(display_point, text_layout_details)
8920 .into(),
8921 );
8922 (display_point, goal)
8923 })
8924 });
8925 }
8926 });
8927 }
8928
8929 pub fn select_enclosing_symbol(
8930 &mut self,
8931 _: &SelectEnclosingSymbol,
8932 cx: &mut ViewContext<Self>,
8933 ) {
8934 let buffer = self.buffer.read(cx).snapshot(cx);
8935 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8936
8937 fn update_selection(
8938 selection: &Selection<usize>,
8939 buffer_snap: &MultiBufferSnapshot,
8940 ) -> Option<Selection<usize>> {
8941 let cursor = selection.head();
8942 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8943 for symbol in symbols.iter().rev() {
8944 let start = symbol.range.start.to_offset(buffer_snap);
8945 let end = symbol.range.end.to_offset(buffer_snap);
8946 let new_range = start..end;
8947 if start < selection.start || end > selection.end {
8948 return Some(Selection {
8949 id: selection.id,
8950 start: new_range.start,
8951 end: new_range.end,
8952 goal: SelectionGoal::None,
8953 reversed: selection.reversed,
8954 });
8955 }
8956 }
8957 None
8958 }
8959
8960 let mut selected_larger_symbol = false;
8961 let new_selections = old_selections
8962 .iter()
8963 .map(|selection| match update_selection(selection, &buffer) {
8964 Some(new_selection) => {
8965 if new_selection.range() != selection.range() {
8966 selected_larger_symbol = true;
8967 }
8968 new_selection
8969 }
8970 None => selection.clone(),
8971 })
8972 .collect::<Vec<_>>();
8973
8974 if selected_larger_symbol {
8975 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8976 s.select(new_selections);
8977 });
8978 }
8979 }
8980
8981 pub fn select_larger_syntax_node(
8982 &mut self,
8983 _: &SelectLargerSyntaxNode,
8984 cx: &mut ViewContext<Self>,
8985 ) {
8986 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8987 let buffer = self.buffer.read(cx).snapshot(cx);
8988 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8989
8990 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8991 let mut selected_larger_node = false;
8992 let new_selections = old_selections
8993 .iter()
8994 .map(|selection| {
8995 let old_range = selection.start..selection.end;
8996 let mut new_range = old_range.clone();
8997 while let Some(containing_range) =
8998 buffer.range_for_syntax_ancestor(new_range.clone())
8999 {
9000 new_range = containing_range;
9001 if !display_map.intersects_fold(new_range.start)
9002 && !display_map.intersects_fold(new_range.end)
9003 {
9004 break;
9005 }
9006 }
9007
9008 selected_larger_node |= new_range != old_range;
9009 Selection {
9010 id: selection.id,
9011 start: new_range.start,
9012 end: new_range.end,
9013 goal: SelectionGoal::None,
9014 reversed: selection.reversed,
9015 }
9016 })
9017 .collect::<Vec<_>>();
9018
9019 if selected_larger_node {
9020 stack.push(old_selections);
9021 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9022 s.select(new_selections);
9023 });
9024 }
9025 self.select_larger_syntax_node_stack = stack;
9026 }
9027
9028 pub fn select_smaller_syntax_node(
9029 &mut self,
9030 _: &SelectSmallerSyntaxNode,
9031 cx: &mut ViewContext<Self>,
9032 ) {
9033 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9034 if let Some(selections) = stack.pop() {
9035 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9036 s.select(selections.to_vec());
9037 });
9038 }
9039 self.select_larger_syntax_node_stack = stack;
9040 }
9041
9042 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9043 if !EditorSettings::get_global(cx).gutter.runnables {
9044 self.clear_tasks();
9045 return Task::ready(());
9046 }
9047 let project = self.project.clone();
9048 cx.spawn(|this, mut cx| async move {
9049 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9050 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9051 }) else {
9052 return;
9053 };
9054
9055 let Some(project) = project else {
9056 return;
9057 };
9058
9059 let hide_runnables = project
9060 .update(&mut cx, |project, cx| {
9061 // Do not display any test indicators in non-dev server remote projects.
9062 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9063 })
9064 .unwrap_or(true);
9065 if hide_runnables {
9066 return;
9067 }
9068 let new_rows =
9069 cx.background_executor()
9070 .spawn({
9071 let snapshot = display_snapshot.clone();
9072 async move {
9073 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9074 }
9075 })
9076 .await;
9077 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9078
9079 this.update(&mut cx, |this, _| {
9080 this.clear_tasks();
9081 for (key, value) in rows {
9082 this.insert_tasks(key, value);
9083 }
9084 })
9085 .ok();
9086 })
9087 }
9088 fn fetch_runnable_ranges(
9089 snapshot: &DisplaySnapshot,
9090 range: Range<Anchor>,
9091 ) -> Vec<language::RunnableRange> {
9092 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9093 }
9094
9095 fn runnable_rows(
9096 project: Model<Project>,
9097 snapshot: DisplaySnapshot,
9098 runnable_ranges: Vec<RunnableRange>,
9099 mut cx: AsyncWindowContext,
9100 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9101 runnable_ranges
9102 .into_iter()
9103 .filter_map(|mut runnable| {
9104 let tasks = cx
9105 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9106 .ok()?;
9107 if tasks.is_empty() {
9108 return None;
9109 }
9110
9111 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9112
9113 let row = snapshot
9114 .buffer_snapshot
9115 .buffer_line_for_row(MultiBufferRow(point.row))?
9116 .1
9117 .start
9118 .row;
9119
9120 let context_range =
9121 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9122 Some((
9123 (runnable.buffer_id, row),
9124 RunnableTasks {
9125 templates: tasks,
9126 offset: MultiBufferOffset(runnable.run_range.start),
9127 context_range,
9128 column: point.column,
9129 extra_variables: runnable.extra_captures,
9130 },
9131 ))
9132 })
9133 .collect()
9134 }
9135
9136 fn templates_with_tags(
9137 project: &Model<Project>,
9138 runnable: &mut Runnable,
9139 cx: &WindowContext<'_>,
9140 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9141 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9142 let (worktree_id, file) = project
9143 .buffer_for_id(runnable.buffer, cx)
9144 .and_then(|buffer| buffer.read(cx).file())
9145 .map(|file| (file.worktree_id(cx), file.clone()))
9146 .unzip();
9147
9148 (
9149 project.task_store().read(cx).task_inventory().cloned(),
9150 worktree_id,
9151 file,
9152 )
9153 });
9154
9155 let tags = mem::take(&mut runnable.tags);
9156 let mut tags: Vec<_> = tags
9157 .into_iter()
9158 .flat_map(|tag| {
9159 let tag = tag.0.clone();
9160 inventory
9161 .as_ref()
9162 .into_iter()
9163 .flat_map(|inventory| {
9164 inventory.read(cx).list_tasks(
9165 file.clone(),
9166 Some(runnable.language.clone()),
9167 worktree_id,
9168 cx,
9169 )
9170 })
9171 .filter(move |(_, template)| {
9172 template.tags.iter().any(|source_tag| source_tag == &tag)
9173 })
9174 })
9175 .sorted_by_key(|(kind, _)| kind.to_owned())
9176 .collect();
9177 if let Some((leading_tag_source, _)) = tags.first() {
9178 // Strongest source wins; if we have worktree tag binding, prefer that to
9179 // global and language bindings;
9180 // if we have a global binding, prefer that to language binding.
9181 let first_mismatch = tags
9182 .iter()
9183 .position(|(tag_source, _)| tag_source != leading_tag_source);
9184 if let Some(index) = first_mismatch {
9185 tags.truncate(index);
9186 }
9187 }
9188
9189 tags
9190 }
9191
9192 pub fn move_to_enclosing_bracket(
9193 &mut self,
9194 _: &MoveToEnclosingBracket,
9195 cx: &mut ViewContext<Self>,
9196 ) {
9197 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9198 s.move_offsets_with(|snapshot, selection| {
9199 let Some(enclosing_bracket_ranges) =
9200 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9201 else {
9202 return;
9203 };
9204
9205 let mut best_length = usize::MAX;
9206 let mut best_inside = false;
9207 let mut best_in_bracket_range = false;
9208 let mut best_destination = None;
9209 for (open, close) in enclosing_bracket_ranges {
9210 let close = close.to_inclusive();
9211 let length = close.end() - open.start;
9212 let inside = selection.start >= open.end && selection.end <= *close.start();
9213 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9214 || close.contains(&selection.head());
9215
9216 // If best is next to a bracket and current isn't, skip
9217 if !in_bracket_range && best_in_bracket_range {
9218 continue;
9219 }
9220
9221 // Prefer smaller lengths unless best is inside and current isn't
9222 if length > best_length && (best_inside || !inside) {
9223 continue;
9224 }
9225
9226 best_length = length;
9227 best_inside = inside;
9228 best_in_bracket_range = in_bracket_range;
9229 best_destination = Some(
9230 if close.contains(&selection.start) && close.contains(&selection.end) {
9231 if inside {
9232 open.end
9233 } else {
9234 open.start
9235 }
9236 } else if inside {
9237 *close.start()
9238 } else {
9239 *close.end()
9240 },
9241 );
9242 }
9243
9244 if let Some(destination) = best_destination {
9245 selection.collapse_to(destination, SelectionGoal::None);
9246 }
9247 })
9248 });
9249 }
9250
9251 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9252 self.end_selection(cx);
9253 self.selection_history.mode = SelectionHistoryMode::Undoing;
9254 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9255 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9256 self.select_next_state = entry.select_next_state;
9257 self.select_prev_state = entry.select_prev_state;
9258 self.add_selections_state = entry.add_selections_state;
9259 self.request_autoscroll(Autoscroll::newest(), cx);
9260 }
9261 self.selection_history.mode = SelectionHistoryMode::Normal;
9262 }
9263
9264 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9265 self.end_selection(cx);
9266 self.selection_history.mode = SelectionHistoryMode::Redoing;
9267 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9268 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9269 self.select_next_state = entry.select_next_state;
9270 self.select_prev_state = entry.select_prev_state;
9271 self.add_selections_state = entry.add_selections_state;
9272 self.request_autoscroll(Autoscroll::newest(), cx);
9273 }
9274 self.selection_history.mode = SelectionHistoryMode::Normal;
9275 }
9276
9277 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9278 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9279 }
9280
9281 pub fn expand_excerpts_down(
9282 &mut self,
9283 action: &ExpandExcerptsDown,
9284 cx: &mut ViewContext<Self>,
9285 ) {
9286 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9287 }
9288
9289 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9290 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9291 }
9292
9293 pub fn expand_excerpts_for_direction(
9294 &mut self,
9295 lines: u32,
9296 direction: ExpandExcerptDirection,
9297 cx: &mut ViewContext<Self>,
9298 ) {
9299 let selections = self.selections.disjoint_anchors();
9300
9301 let lines = if lines == 0 {
9302 EditorSettings::get_global(cx).expand_excerpt_lines
9303 } else {
9304 lines
9305 };
9306
9307 self.buffer.update(cx, |buffer, cx| {
9308 buffer.expand_excerpts(
9309 selections
9310 .iter()
9311 .map(|selection| selection.head().excerpt_id)
9312 .dedup(),
9313 lines,
9314 direction,
9315 cx,
9316 )
9317 })
9318 }
9319
9320 pub fn expand_excerpt(
9321 &mut self,
9322 excerpt: ExcerptId,
9323 direction: ExpandExcerptDirection,
9324 cx: &mut ViewContext<Self>,
9325 ) {
9326 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9327 self.buffer.update(cx, |buffer, cx| {
9328 buffer.expand_excerpts([excerpt], lines, direction, cx)
9329 })
9330 }
9331
9332 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9333 self.go_to_diagnostic_impl(Direction::Next, cx)
9334 }
9335
9336 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9337 self.go_to_diagnostic_impl(Direction::Prev, cx)
9338 }
9339
9340 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9341 let buffer = self.buffer.read(cx).snapshot(cx);
9342 let selection = self.selections.newest::<usize>(cx);
9343
9344 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9345 if direction == Direction::Next {
9346 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9347 let (group_id, jump_to) = popover.activation_info();
9348 if self.activate_diagnostics(group_id, cx) {
9349 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9350 let mut new_selection = s.newest_anchor().clone();
9351 new_selection.collapse_to(jump_to, SelectionGoal::None);
9352 s.select_anchors(vec![new_selection.clone()]);
9353 });
9354 }
9355 return;
9356 }
9357 }
9358
9359 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9360 active_diagnostics
9361 .primary_range
9362 .to_offset(&buffer)
9363 .to_inclusive()
9364 });
9365 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9366 if active_primary_range.contains(&selection.head()) {
9367 *active_primary_range.start()
9368 } else {
9369 selection.head()
9370 }
9371 } else {
9372 selection.head()
9373 };
9374 let snapshot = self.snapshot(cx);
9375 loop {
9376 let diagnostics = if direction == Direction::Prev {
9377 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9378 } else {
9379 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9380 }
9381 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9382 let group = diagnostics
9383 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9384 // be sorted in a stable way
9385 // skip until we are at current active diagnostic, if it exists
9386 .skip_while(|entry| {
9387 (match direction {
9388 Direction::Prev => entry.range.start >= search_start,
9389 Direction::Next => entry.range.start <= search_start,
9390 }) && self
9391 .active_diagnostics
9392 .as_ref()
9393 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9394 })
9395 .find_map(|entry| {
9396 if entry.diagnostic.is_primary
9397 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9398 && !entry.range.is_empty()
9399 // if we match with the active diagnostic, skip it
9400 && Some(entry.diagnostic.group_id)
9401 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9402 {
9403 Some((entry.range, entry.diagnostic.group_id))
9404 } else {
9405 None
9406 }
9407 });
9408
9409 if let Some((primary_range, group_id)) = group {
9410 if self.activate_diagnostics(group_id, cx) {
9411 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9412 s.select(vec![Selection {
9413 id: selection.id,
9414 start: primary_range.start,
9415 end: primary_range.start,
9416 reversed: false,
9417 goal: SelectionGoal::None,
9418 }]);
9419 });
9420 }
9421 break;
9422 } else {
9423 // Cycle around to the start of the buffer, potentially moving back to the start of
9424 // the currently active diagnostic.
9425 active_primary_range.take();
9426 if direction == Direction::Prev {
9427 if search_start == buffer.len() {
9428 break;
9429 } else {
9430 search_start = buffer.len();
9431 }
9432 } else if search_start == 0 {
9433 break;
9434 } else {
9435 search_start = 0;
9436 }
9437 }
9438 }
9439 }
9440
9441 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9442 let snapshot = self
9443 .display_map
9444 .update(cx, |display_map, cx| display_map.snapshot(cx));
9445 let selection = self.selections.newest::<Point>(cx);
9446 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9447 }
9448
9449 fn go_to_hunk_after_position(
9450 &mut self,
9451 snapshot: &DisplaySnapshot,
9452 position: Point,
9453 cx: &mut ViewContext<'_, Editor>,
9454 ) -> Option<MultiBufferDiffHunk> {
9455 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9456 snapshot,
9457 position,
9458 false,
9459 snapshot
9460 .buffer_snapshot
9461 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9462 cx,
9463 ) {
9464 return Some(hunk);
9465 }
9466
9467 let wrapped_point = Point::zero();
9468 self.go_to_next_hunk_in_direction(
9469 snapshot,
9470 wrapped_point,
9471 true,
9472 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9473 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9474 ),
9475 cx,
9476 )
9477 }
9478
9479 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9480 let snapshot = self
9481 .display_map
9482 .update(cx, |display_map, cx| display_map.snapshot(cx));
9483 let selection = self.selections.newest::<Point>(cx);
9484
9485 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9486 }
9487
9488 fn go_to_hunk_before_position(
9489 &mut self,
9490 snapshot: &DisplaySnapshot,
9491 position: Point,
9492 cx: &mut ViewContext<'_, Editor>,
9493 ) -> Option<MultiBufferDiffHunk> {
9494 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9495 snapshot,
9496 position,
9497 false,
9498 snapshot
9499 .buffer_snapshot
9500 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9501 cx,
9502 ) {
9503 return Some(hunk);
9504 }
9505
9506 let wrapped_point = snapshot.buffer_snapshot.max_point();
9507 self.go_to_next_hunk_in_direction(
9508 snapshot,
9509 wrapped_point,
9510 true,
9511 snapshot
9512 .buffer_snapshot
9513 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9514 cx,
9515 )
9516 }
9517
9518 fn go_to_next_hunk_in_direction(
9519 &mut self,
9520 snapshot: &DisplaySnapshot,
9521 initial_point: Point,
9522 is_wrapped: bool,
9523 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9524 cx: &mut ViewContext<Editor>,
9525 ) -> Option<MultiBufferDiffHunk> {
9526 let display_point = initial_point.to_display_point(snapshot);
9527 let mut hunks = hunks
9528 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9529 .filter(|(display_hunk, _)| {
9530 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9531 })
9532 .dedup();
9533
9534 if let Some((display_hunk, hunk)) = hunks.next() {
9535 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9536 let row = display_hunk.start_display_row();
9537 let point = DisplayPoint::new(row, 0);
9538 s.select_display_ranges([point..point]);
9539 });
9540
9541 Some(hunk)
9542 } else {
9543 None
9544 }
9545 }
9546
9547 pub fn go_to_definition(
9548 &mut self,
9549 _: &GoToDefinition,
9550 cx: &mut ViewContext<Self>,
9551 ) -> Task<Result<Navigated>> {
9552 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9553 cx.spawn(|editor, mut cx| async move {
9554 if definition.await? == Navigated::Yes {
9555 return Ok(Navigated::Yes);
9556 }
9557 match editor.update(&mut cx, |editor, cx| {
9558 editor.find_all_references(&FindAllReferences, cx)
9559 })? {
9560 Some(references) => references.await,
9561 None => Ok(Navigated::No),
9562 }
9563 })
9564 }
9565
9566 pub fn go_to_declaration(
9567 &mut self,
9568 _: &GoToDeclaration,
9569 cx: &mut ViewContext<Self>,
9570 ) -> Task<Result<Navigated>> {
9571 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9572 }
9573
9574 pub fn go_to_declaration_split(
9575 &mut self,
9576 _: &GoToDeclaration,
9577 cx: &mut ViewContext<Self>,
9578 ) -> Task<Result<Navigated>> {
9579 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9580 }
9581
9582 pub fn go_to_implementation(
9583 &mut self,
9584 _: &GoToImplementation,
9585 cx: &mut ViewContext<Self>,
9586 ) -> Task<Result<Navigated>> {
9587 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9588 }
9589
9590 pub fn go_to_implementation_split(
9591 &mut self,
9592 _: &GoToImplementationSplit,
9593 cx: &mut ViewContext<Self>,
9594 ) -> Task<Result<Navigated>> {
9595 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9596 }
9597
9598 pub fn go_to_type_definition(
9599 &mut self,
9600 _: &GoToTypeDefinition,
9601 cx: &mut ViewContext<Self>,
9602 ) -> Task<Result<Navigated>> {
9603 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9604 }
9605
9606 pub fn go_to_definition_split(
9607 &mut self,
9608 _: &GoToDefinitionSplit,
9609 cx: &mut ViewContext<Self>,
9610 ) -> Task<Result<Navigated>> {
9611 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9612 }
9613
9614 pub fn go_to_type_definition_split(
9615 &mut self,
9616 _: &GoToTypeDefinitionSplit,
9617 cx: &mut ViewContext<Self>,
9618 ) -> Task<Result<Navigated>> {
9619 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9620 }
9621
9622 fn go_to_definition_of_kind(
9623 &mut self,
9624 kind: GotoDefinitionKind,
9625 split: bool,
9626 cx: &mut ViewContext<Self>,
9627 ) -> Task<Result<Navigated>> {
9628 let Some(provider) = self.semantics_provider.clone() else {
9629 return Task::ready(Ok(Navigated::No));
9630 };
9631 let buffer = self.buffer.read(cx);
9632 let head = self.selections.newest::<usize>(cx).head();
9633 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9634 text_anchor
9635 } else {
9636 return Task::ready(Ok(Navigated::No));
9637 };
9638
9639 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9640 return Task::ready(Ok(Navigated::No));
9641 };
9642
9643 cx.spawn(|editor, mut cx| async move {
9644 let definitions = definitions.await?;
9645 let navigated = editor
9646 .update(&mut cx, |editor, cx| {
9647 editor.navigate_to_hover_links(
9648 Some(kind),
9649 definitions
9650 .into_iter()
9651 .filter(|location| {
9652 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9653 })
9654 .map(HoverLink::Text)
9655 .collect::<Vec<_>>(),
9656 split,
9657 cx,
9658 )
9659 })?
9660 .await?;
9661 anyhow::Ok(navigated)
9662 })
9663 }
9664
9665 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9666 let position = self.selections.newest_anchor().head();
9667 let Some((buffer, buffer_position)) =
9668 self.buffer.read(cx).text_anchor_for_position(position, cx)
9669 else {
9670 return;
9671 };
9672
9673 cx.spawn(|editor, mut cx| async move {
9674 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9675 editor.update(&mut cx, |_, cx| {
9676 cx.open_url(&url);
9677 })
9678 } else {
9679 Ok(())
9680 }
9681 })
9682 .detach();
9683 }
9684
9685 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9686 let Some(workspace) = self.workspace() else {
9687 return;
9688 };
9689
9690 let position = self.selections.newest_anchor().head();
9691
9692 let Some((buffer, buffer_position)) =
9693 self.buffer.read(cx).text_anchor_for_position(position, cx)
9694 else {
9695 return;
9696 };
9697
9698 let project = self.project.clone();
9699
9700 cx.spawn(|_, mut cx| async move {
9701 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9702
9703 if let Some((_, path)) = result {
9704 workspace
9705 .update(&mut cx, |workspace, cx| {
9706 workspace.open_resolved_path(path, cx)
9707 })?
9708 .await?;
9709 }
9710 anyhow::Ok(())
9711 })
9712 .detach();
9713 }
9714
9715 pub(crate) fn navigate_to_hover_links(
9716 &mut self,
9717 kind: Option<GotoDefinitionKind>,
9718 mut definitions: Vec<HoverLink>,
9719 split: bool,
9720 cx: &mut ViewContext<Editor>,
9721 ) -> Task<Result<Navigated>> {
9722 // If there is one definition, just open it directly
9723 if definitions.len() == 1 {
9724 let definition = definitions.pop().unwrap();
9725
9726 enum TargetTaskResult {
9727 Location(Option<Location>),
9728 AlreadyNavigated,
9729 }
9730
9731 let target_task = match definition {
9732 HoverLink::Text(link) => {
9733 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9734 }
9735 HoverLink::InlayHint(lsp_location, server_id) => {
9736 let computation = self.compute_target_location(lsp_location, server_id, cx);
9737 cx.background_executor().spawn(async move {
9738 let location = computation.await?;
9739 Ok(TargetTaskResult::Location(location))
9740 })
9741 }
9742 HoverLink::Url(url) => {
9743 cx.open_url(&url);
9744 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9745 }
9746 HoverLink::File(path) => {
9747 if let Some(workspace) = self.workspace() {
9748 cx.spawn(|_, mut cx| async move {
9749 workspace
9750 .update(&mut cx, |workspace, cx| {
9751 workspace.open_resolved_path(path, cx)
9752 })?
9753 .await
9754 .map(|_| TargetTaskResult::AlreadyNavigated)
9755 })
9756 } else {
9757 Task::ready(Ok(TargetTaskResult::Location(None)))
9758 }
9759 }
9760 };
9761 cx.spawn(|editor, mut cx| async move {
9762 let target = match target_task.await.context("target resolution task")? {
9763 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9764 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9765 TargetTaskResult::Location(Some(target)) => target,
9766 };
9767
9768 editor.update(&mut cx, |editor, cx| {
9769 let Some(workspace) = editor.workspace() else {
9770 return Navigated::No;
9771 };
9772 let pane = workspace.read(cx).active_pane().clone();
9773
9774 let range = target.range.to_offset(target.buffer.read(cx));
9775 let range = editor.range_for_match(&range);
9776
9777 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9778 let buffer = target.buffer.read(cx);
9779 let range = check_multiline_range(buffer, range);
9780 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9781 s.select_ranges([range]);
9782 });
9783 } else {
9784 cx.window_context().defer(move |cx| {
9785 let target_editor: View<Self> =
9786 workspace.update(cx, |workspace, cx| {
9787 let pane = if split {
9788 workspace.adjacent_pane(cx)
9789 } else {
9790 workspace.active_pane().clone()
9791 };
9792
9793 workspace.open_project_item(
9794 pane,
9795 target.buffer.clone(),
9796 true,
9797 true,
9798 cx,
9799 )
9800 });
9801 target_editor.update(cx, |target_editor, cx| {
9802 // When selecting a definition in a different buffer, disable the nav history
9803 // to avoid creating a history entry at the previous cursor location.
9804 pane.update(cx, |pane, _| pane.disable_history());
9805 let buffer = target.buffer.read(cx);
9806 let range = check_multiline_range(buffer, range);
9807 target_editor.change_selections(
9808 Some(Autoscroll::focused()),
9809 cx,
9810 |s| {
9811 s.select_ranges([range]);
9812 },
9813 );
9814 pane.update(cx, |pane, _| pane.enable_history());
9815 });
9816 });
9817 }
9818 Navigated::Yes
9819 })
9820 })
9821 } else if !definitions.is_empty() {
9822 cx.spawn(|editor, mut cx| async move {
9823 let (title, location_tasks, workspace) = editor
9824 .update(&mut cx, |editor, cx| {
9825 let tab_kind = match kind {
9826 Some(GotoDefinitionKind::Implementation) => "Implementations",
9827 _ => "Definitions",
9828 };
9829 let title = definitions
9830 .iter()
9831 .find_map(|definition| match definition {
9832 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9833 let buffer = origin.buffer.read(cx);
9834 format!(
9835 "{} for {}",
9836 tab_kind,
9837 buffer
9838 .text_for_range(origin.range.clone())
9839 .collect::<String>()
9840 )
9841 }),
9842 HoverLink::InlayHint(_, _) => None,
9843 HoverLink::Url(_) => None,
9844 HoverLink::File(_) => None,
9845 })
9846 .unwrap_or(tab_kind.to_string());
9847 let location_tasks = definitions
9848 .into_iter()
9849 .map(|definition| match definition {
9850 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9851 HoverLink::InlayHint(lsp_location, server_id) => {
9852 editor.compute_target_location(lsp_location, server_id, cx)
9853 }
9854 HoverLink::Url(_) => Task::ready(Ok(None)),
9855 HoverLink::File(_) => Task::ready(Ok(None)),
9856 })
9857 .collect::<Vec<_>>();
9858 (title, location_tasks, editor.workspace().clone())
9859 })
9860 .context("location tasks preparation")?;
9861
9862 let locations = future::join_all(location_tasks)
9863 .await
9864 .into_iter()
9865 .filter_map(|location| location.transpose())
9866 .collect::<Result<_>>()
9867 .context("location tasks")?;
9868
9869 let Some(workspace) = workspace else {
9870 return Ok(Navigated::No);
9871 };
9872 let opened = workspace
9873 .update(&mut cx, |workspace, cx| {
9874 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9875 })
9876 .ok();
9877
9878 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9879 })
9880 } else {
9881 Task::ready(Ok(Navigated::No))
9882 }
9883 }
9884
9885 fn compute_target_location(
9886 &self,
9887 lsp_location: lsp::Location,
9888 server_id: LanguageServerId,
9889 cx: &mut ViewContext<Editor>,
9890 ) -> Task<anyhow::Result<Option<Location>>> {
9891 let Some(project) = self.project.clone() else {
9892 return Task::Ready(Some(Ok(None)));
9893 };
9894
9895 cx.spawn(move |editor, mut cx| async move {
9896 let location_task = editor.update(&mut cx, |editor, cx| {
9897 project.update(cx, |project, cx| {
9898 let language_server_name =
9899 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9900 project
9901 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9902 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9903 });
9904 language_server_name.map(|language_server_name| {
9905 project.open_local_buffer_via_lsp(
9906 lsp_location.uri.clone(),
9907 server_id,
9908 language_server_name,
9909 cx,
9910 )
9911 })
9912 })
9913 })?;
9914 let location = match location_task {
9915 Some(task) => Some({
9916 let target_buffer_handle = task.await.context("open local buffer")?;
9917 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9918 let target_start = target_buffer
9919 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9920 let target_end = target_buffer
9921 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9922 target_buffer.anchor_after(target_start)
9923 ..target_buffer.anchor_before(target_end)
9924 })?;
9925 Location {
9926 buffer: target_buffer_handle,
9927 range,
9928 }
9929 }),
9930 None => None,
9931 };
9932 Ok(location)
9933 })
9934 }
9935
9936 pub fn find_all_references(
9937 &mut self,
9938 _: &FindAllReferences,
9939 cx: &mut ViewContext<Self>,
9940 ) -> Option<Task<Result<Navigated>>> {
9941 let multi_buffer = self.buffer.read(cx);
9942 let selection = self.selections.newest::<usize>(cx);
9943 let head = selection.head();
9944
9945 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9946 let head_anchor = multi_buffer_snapshot.anchor_at(
9947 head,
9948 if head < selection.tail() {
9949 Bias::Right
9950 } else {
9951 Bias::Left
9952 },
9953 );
9954
9955 match self
9956 .find_all_references_task_sources
9957 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9958 {
9959 Ok(_) => {
9960 log::info!(
9961 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9962 );
9963 return None;
9964 }
9965 Err(i) => {
9966 self.find_all_references_task_sources.insert(i, head_anchor);
9967 }
9968 }
9969
9970 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9971 let workspace = self.workspace()?;
9972 let project = workspace.read(cx).project().clone();
9973 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9974 Some(cx.spawn(|editor, mut cx| async move {
9975 let _cleanup = defer({
9976 let mut cx = cx.clone();
9977 move || {
9978 let _ = editor.update(&mut cx, |editor, _| {
9979 if let Ok(i) =
9980 editor
9981 .find_all_references_task_sources
9982 .binary_search_by(|anchor| {
9983 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9984 })
9985 {
9986 editor.find_all_references_task_sources.remove(i);
9987 }
9988 });
9989 }
9990 });
9991
9992 let locations = references.await?;
9993 if locations.is_empty() {
9994 return anyhow::Ok(Navigated::No);
9995 }
9996
9997 workspace.update(&mut cx, |workspace, cx| {
9998 let title = locations
9999 .first()
10000 .as_ref()
10001 .map(|location| {
10002 let buffer = location.buffer.read(cx);
10003 format!(
10004 "References to `{}`",
10005 buffer
10006 .text_for_range(location.range.clone())
10007 .collect::<String>()
10008 )
10009 })
10010 .unwrap();
10011 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10012 Navigated::Yes
10013 })
10014 }))
10015 }
10016
10017 /// Opens a multibuffer with the given project locations in it
10018 pub fn open_locations_in_multibuffer(
10019 workspace: &mut Workspace,
10020 mut locations: Vec<Location>,
10021 title: String,
10022 split: bool,
10023 cx: &mut ViewContext<Workspace>,
10024 ) {
10025 // If there are multiple definitions, open them in a multibuffer
10026 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10027 let mut locations = locations.into_iter().peekable();
10028 let mut ranges_to_highlight = Vec::new();
10029 let capability = workspace.project().read(cx).capability();
10030
10031 let excerpt_buffer = cx.new_model(|cx| {
10032 let mut multibuffer = MultiBuffer::new(capability);
10033 while let Some(location) = locations.next() {
10034 let buffer = location.buffer.read(cx);
10035 let mut ranges_for_buffer = Vec::new();
10036 let range = location.range.to_offset(buffer);
10037 ranges_for_buffer.push(range.clone());
10038
10039 while let Some(next_location) = locations.peek() {
10040 if next_location.buffer == location.buffer {
10041 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10042 locations.next();
10043 } else {
10044 break;
10045 }
10046 }
10047
10048 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10049 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10050 location.buffer.clone(),
10051 ranges_for_buffer,
10052 DEFAULT_MULTIBUFFER_CONTEXT,
10053 cx,
10054 ))
10055 }
10056
10057 multibuffer.with_title(title)
10058 });
10059
10060 let editor = cx.new_view(|cx| {
10061 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10062 });
10063 editor.update(cx, |editor, cx| {
10064 if let Some(first_range) = ranges_to_highlight.first() {
10065 editor.change_selections(None, cx, |selections| {
10066 selections.clear_disjoint();
10067 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10068 });
10069 }
10070 editor.highlight_background::<Self>(
10071 &ranges_to_highlight,
10072 |theme| theme.editor_highlighted_line_background,
10073 cx,
10074 );
10075 });
10076
10077 let item = Box::new(editor);
10078 let item_id = item.item_id();
10079
10080 if split {
10081 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10082 } else {
10083 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10084 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10085 pane.close_current_preview_item(cx)
10086 } else {
10087 None
10088 }
10089 });
10090 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10091 }
10092 workspace.active_pane().update(cx, |pane, cx| {
10093 pane.set_preview_item_id(Some(item_id), cx);
10094 });
10095 }
10096
10097 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10098 use language::ToOffset as _;
10099
10100 let provider = self.semantics_provider.clone()?;
10101 let selection = self.selections.newest_anchor().clone();
10102 let (cursor_buffer, cursor_buffer_position) = self
10103 .buffer
10104 .read(cx)
10105 .text_anchor_for_position(selection.head(), cx)?;
10106 let (tail_buffer, cursor_buffer_position_end) = self
10107 .buffer
10108 .read(cx)
10109 .text_anchor_for_position(selection.tail(), cx)?;
10110 if tail_buffer != cursor_buffer {
10111 return None;
10112 }
10113
10114 let snapshot = cursor_buffer.read(cx).snapshot();
10115 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10116 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10117 let prepare_rename = provider
10118 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10119 .unwrap_or_else(|| Task::ready(Ok(None)));
10120 drop(snapshot);
10121
10122 Some(cx.spawn(|this, mut cx| async move {
10123 let rename_range = if let Some(range) = prepare_rename.await? {
10124 Some(range)
10125 } else {
10126 this.update(&mut cx, |this, cx| {
10127 let buffer = this.buffer.read(cx).snapshot(cx);
10128 let mut buffer_highlights = this
10129 .document_highlights_for_position(selection.head(), &buffer)
10130 .filter(|highlight| {
10131 highlight.start.excerpt_id == selection.head().excerpt_id
10132 && highlight.end.excerpt_id == selection.head().excerpt_id
10133 });
10134 buffer_highlights
10135 .next()
10136 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10137 })?
10138 };
10139 if let Some(rename_range) = rename_range {
10140 this.update(&mut cx, |this, cx| {
10141 let snapshot = cursor_buffer.read(cx).snapshot();
10142 let rename_buffer_range = rename_range.to_offset(&snapshot);
10143 let cursor_offset_in_rename_range =
10144 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10145 let cursor_offset_in_rename_range_end =
10146 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10147
10148 this.take_rename(false, cx);
10149 let buffer = this.buffer.read(cx).read(cx);
10150 let cursor_offset = selection.head().to_offset(&buffer);
10151 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10152 let rename_end = rename_start + rename_buffer_range.len();
10153 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10154 let mut old_highlight_id = None;
10155 let old_name: Arc<str> = buffer
10156 .chunks(rename_start..rename_end, true)
10157 .map(|chunk| {
10158 if old_highlight_id.is_none() {
10159 old_highlight_id = chunk.syntax_highlight_id;
10160 }
10161 chunk.text
10162 })
10163 .collect::<String>()
10164 .into();
10165
10166 drop(buffer);
10167
10168 // Position the selection in the rename editor so that it matches the current selection.
10169 this.show_local_selections = false;
10170 let rename_editor = cx.new_view(|cx| {
10171 let mut editor = Editor::single_line(cx);
10172 editor.buffer.update(cx, |buffer, cx| {
10173 buffer.edit([(0..0, old_name.clone())], None, cx)
10174 });
10175 let rename_selection_range = match cursor_offset_in_rename_range
10176 .cmp(&cursor_offset_in_rename_range_end)
10177 {
10178 Ordering::Equal => {
10179 editor.select_all(&SelectAll, cx);
10180 return editor;
10181 }
10182 Ordering::Less => {
10183 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10184 }
10185 Ordering::Greater => {
10186 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10187 }
10188 };
10189 if rename_selection_range.end > old_name.len() {
10190 editor.select_all(&SelectAll, cx);
10191 } else {
10192 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10193 s.select_ranges([rename_selection_range]);
10194 });
10195 }
10196 editor
10197 });
10198 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10199 if e == &EditorEvent::Focused {
10200 cx.emit(EditorEvent::FocusedIn)
10201 }
10202 })
10203 .detach();
10204
10205 let write_highlights =
10206 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10207 let read_highlights =
10208 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10209 let ranges = write_highlights
10210 .iter()
10211 .flat_map(|(_, ranges)| ranges.iter())
10212 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10213 .cloned()
10214 .collect();
10215
10216 this.highlight_text::<Rename>(
10217 ranges,
10218 HighlightStyle {
10219 fade_out: Some(0.6),
10220 ..Default::default()
10221 },
10222 cx,
10223 );
10224 let rename_focus_handle = rename_editor.focus_handle(cx);
10225 cx.focus(&rename_focus_handle);
10226 let block_id = this.insert_blocks(
10227 [BlockProperties {
10228 style: BlockStyle::Flex,
10229 position: range.start,
10230 height: 1,
10231 render: Box::new({
10232 let rename_editor = rename_editor.clone();
10233 move |cx: &mut BlockContext| {
10234 let mut text_style = cx.editor_style.text.clone();
10235 if let Some(highlight_style) = old_highlight_id
10236 .and_then(|h| h.style(&cx.editor_style.syntax))
10237 {
10238 text_style = text_style.highlight(highlight_style);
10239 }
10240 div()
10241 .pl(cx.anchor_x)
10242 .child(EditorElement::new(
10243 &rename_editor,
10244 EditorStyle {
10245 background: cx.theme().system().transparent,
10246 local_player: cx.editor_style.local_player,
10247 text: text_style,
10248 scrollbar_width: cx.editor_style.scrollbar_width,
10249 syntax: cx.editor_style.syntax.clone(),
10250 status: cx.editor_style.status.clone(),
10251 inlay_hints_style: HighlightStyle {
10252 font_weight: Some(FontWeight::BOLD),
10253 ..make_inlay_hints_style(cx)
10254 },
10255 suggestions_style: HighlightStyle {
10256 color: Some(cx.theme().status().predictive),
10257 ..HighlightStyle::default()
10258 },
10259 ..EditorStyle::default()
10260 },
10261 ))
10262 .into_any_element()
10263 }
10264 }),
10265 disposition: BlockDisposition::Below,
10266 priority: 0,
10267 }],
10268 Some(Autoscroll::fit()),
10269 cx,
10270 )[0];
10271 this.pending_rename = Some(RenameState {
10272 range,
10273 old_name,
10274 editor: rename_editor,
10275 block_id,
10276 });
10277 })?;
10278 }
10279
10280 Ok(())
10281 }))
10282 }
10283
10284 pub fn confirm_rename(
10285 &mut self,
10286 _: &ConfirmRename,
10287 cx: &mut ViewContext<Self>,
10288 ) -> Option<Task<Result<()>>> {
10289 let rename = self.take_rename(false, cx)?;
10290 let workspace = self.workspace()?.downgrade();
10291 let (buffer, start) = self
10292 .buffer
10293 .read(cx)
10294 .text_anchor_for_position(rename.range.start, cx)?;
10295 let (end_buffer, _) = self
10296 .buffer
10297 .read(cx)
10298 .text_anchor_for_position(rename.range.end, cx)?;
10299 if buffer != end_buffer {
10300 return None;
10301 }
10302
10303 let old_name = rename.old_name;
10304 let new_name = rename.editor.read(cx).text(cx);
10305
10306 let rename = self.semantics_provider.as_ref()?.perform_rename(
10307 &buffer,
10308 start,
10309 new_name.clone(),
10310 cx,
10311 )?;
10312
10313 Some(cx.spawn(|editor, mut cx| async move {
10314 let project_transaction = rename.await?;
10315 Self::open_project_transaction(
10316 &editor,
10317 workspace,
10318 project_transaction,
10319 format!("Rename: {} → {}", old_name, new_name),
10320 cx.clone(),
10321 )
10322 .await?;
10323
10324 editor.update(&mut cx, |editor, cx| {
10325 editor.refresh_document_highlights(cx);
10326 })?;
10327 Ok(())
10328 }))
10329 }
10330
10331 fn take_rename(
10332 &mut self,
10333 moving_cursor: bool,
10334 cx: &mut ViewContext<Self>,
10335 ) -> Option<RenameState> {
10336 let rename = self.pending_rename.take()?;
10337 if rename.editor.focus_handle(cx).is_focused(cx) {
10338 cx.focus(&self.focus_handle);
10339 }
10340
10341 self.remove_blocks(
10342 [rename.block_id].into_iter().collect(),
10343 Some(Autoscroll::fit()),
10344 cx,
10345 );
10346 self.clear_highlights::<Rename>(cx);
10347 self.show_local_selections = true;
10348
10349 if moving_cursor {
10350 let rename_editor = rename.editor.read(cx);
10351 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10352
10353 // Update the selection to match the position of the selection inside
10354 // the rename editor.
10355 let snapshot = self.buffer.read(cx).read(cx);
10356 let rename_range = rename.range.to_offset(&snapshot);
10357 let cursor_in_editor = snapshot
10358 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10359 .min(rename_range.end);
10360 drop(snapshot);
10361
10362 self.change_selections(None, cx, |s| {
10363 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10364 });
10365 } else {
10366 self.refresh_document_highlights(cx);
10367 }
10368
10369 Some(rename)
10370 }
10371
10372 pub fn pending_rename(&self) -> Option<&RenameState> {
10373 self.pending_rename.as_ref()
10374 }
10375
10376 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10377 let project = match &self.project {
10378 Some(project) => project.clone(),
10379 None => return None,
10380 };
10381
10382 Some(self.perform_format(project, FormatTrigger::Manual, cx))
10383 }
10384
10385 fn perform_format(
10386 &mut self,
10387 project: Model<Project>,
10388 trigger: FormatTrigger,
10389 cx: &mut ViewContext<Self>,
10390 ) -> Task<Result<()>> {
10391 let buffer = self.buffer().clone();
10392 let mut buffers = buffer.read(cx).all_buffers();
10393 if trigger == FormatTrigger::Save {
10394 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10395 }
10396
10397 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10398 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10399
10400 cx.spawn(|_, mut cx| async move {
10401 let transaction = futures::select_biased! {
10402 () = timeout => {
10403 log::warn!("timed out waiting for formatting");
10404 None
10405 }
10406 transaction = format.log_err().fuse() => transaction,
10407 };
10408
10409 buffer
10410 .update(&mut cx, |buffer, cx| {
10411 if let Some(transaction) = transaction {
10412 if !buffer.is_singleton() {
10413 buffer.push_transaction(&transaction.0, cx);
10414 }
10415 }
10416
10417 cx.notify();
10418 })
10419 .ok();
10420
10421 Ok(())
10422 })
10423 }
10424
10425 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10426 if let Some(project) = self.project.clone() {
10427 self.buffer.update(cx, |multi_buffer, cx| {
10428 project.update(cx, |project, cx| {
10429 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10430 });
10431 })
10432 }
10433 }
10434
10435 fn cancel_language_server_work(
10436 &mut self,
10437 _: &CancelLanguageServerWork,
10438 cx: &mut ViewContext<Self>,
10439 ) {
10440 if let Some(project) = self.project.clone() {
10441 self.buffer.update(cx, |multi_buffer, cx| {
10442 project.update(cx, |project, cx| {
10443 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10444 });
10445 })
10446 }
10447 }
10448
10449 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10450 cx.show_character_palette();
10451 }
10452
10453 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10454 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10455 let buffer = self.buffer.read(cx).snapshot(cx);
10456 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10457 let is_valid = buffer
10458 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10459 .any(|entry| {
10460 entry.diagnostic.is_primary
10461 && !entry.range.is_empty()
10462 && entry.range.start == primary_range_start
10463 && entry.diagnostic.message == active_diagnostics.primary_message
10464 });
10465
10466 if is_valid != active_diagnostics.is_valid {
10467 active_diagnostics.is_valid = is_valid;
10468 let mut new_styles = HashMap::default();
10469 for (block_id, diagnostic) in &active_diagnostics.blocks {
10470 new_styles.insert(
10471 *block_id,
10472 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10473 );
10474 }
10475 self.display_map.update(cx, |display_map, _cx| {
10476 display_map.replace_blocks(new_styles)
10477 });
10478 }
10479 }
10480 }
10481
10482 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10483 self.dismiss_diagnostics(cx);
10484 let snapshot = self.snapshot(cx);
10485 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10486 let buffer = self.buffer.read(cx).snapshot(cx);
10487
10488 let mut primary_range = None;
10489 let mut primary_message = None;
10490 let mut group_end = Point::zero();
10491 let diagnostic_group = buffer
10492 .diagnostic_group::<MultiBufferPoint>(group_id)
10493 .filter_map(|entry| {
10494 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10495 && (entry.range.start.row == entry.range.end.row
10496 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10497 {
10498 return None;
10499 }
10500 if entry.range.end > group_end {
10501 group_end = entry.range.end;
10502 }
10503 if entry.diagnostic.is_primary {
10504 primary_range = Some(entry.range.clone());
10505 primary_message = Some(entry.diagnostic.message.clone());
10506 }
10507 Some(entry)
10508 })
10509 .collect::<Vec<_>>();
10510 let primary_range = primary_range?;
10511 let primary_message = primary_message?;
10512 let primary_range =
10513 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10514
10515 let blocks = display_map
10516 .insert_blocks(
10517 diagnostic_group.iter().map(|entry| {
10518 let diagnostic = entry.diagnostic.clone();
10519 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10520 BlockProperties {
10521 style: BlockStyle::Fixed,
10522 position: buffer.anchor_after(entry.range.start),
10523 height: message_height,
10524 render: diagnostic_block_renderer(diagnostic, None, true, true),
10525 disposition: BlockDisposition::Below,
10526 priority: 0,
10527 }
10528 }),
10529 cx,
10530 )
10531 .into_iter()
10532 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10533 .collect();
10534
10535 Some(ActiveDiagnosticGroup {
10536 primary_range,
10537 primary_message,
10538 group_id,
10539 blocks,
10540 is_valid: true,
10541 })
10542 });
10543 self.active_diagnostics.is_some()
10544 }
10545
10546 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10547 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10548 self.display_map.update(cx, |display_map, cx| {
10549 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10550 });
10551 cx.notify();
10552 }
10553 }
10554
10555 pub fn set_selections_from_remote(
10556 &mut self,
10557 selections: Vec<Selection<Anchor>>,
10558 pending_selection: Option<Selection<Anchor>>,
10559 cx: &mut ViewContext<Self>,
10560 ) {
10561 let old_cursor_position = self.selections.newest_anchor().head();
10562 self.selections.change_with(cx, |s| {
10563 s.select_anchors(selections);
10564 if let Some(pending_selection) = pending_selection {
10565 s.set_pending(pending_selection, SelectMode::Character);
10566 } else {
10567 s.clear_pending();
10568 }
10569 });
10570 self.selections_did_change(false, &old_cursor_position, true, cx);
10571 }
10572
10573 fn push_to_selection_history(&mut self) {
10574 self.selection_history.push(SelectionHistoryEntry {
10575 selections: self.selections.disjoint_anchors(),
10576 select_next_state: self.select_next_state.clone(),
10577 select_prev_state: self.select_prev_state.clone(),
10578 add_selections_state: self.add_selections_state.clone(),
10579 });
10580 }
10581
10582 pub fn transact(
10583 &mut self,
10584 cx: &mut ViewContext<Self>,
10585 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10586 ) -> Option<TransactionId> {
10587 self.start_transaction_at(Instant::now(), cx);
10588 update(self, cx);
10589 self.end_transaction_at(Instant::now(), cx)
10590 }
10591
10592 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10593 self.end_selection(cx);
10594 if let Some(tx_id) = self
10595 .buffer
10596 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10597 {
10598 self.selection_history
10599 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10600 cx.emit(EditorEvent::TransactionBegun {
10601 transaction_id: tx_id,
10602 })
10603 }
10604 }
10605
10606 fn end_transaction_at(
10607 &mut self,
10608 now: Instant,
10609 cx: &mut ViewContext<Self>,
10610 ) -> Option<TransactionId> {
10611 if let Some(transaction_id) = self
10612 .buffer
10613 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10614 {
10615 if let Some((_, end_selections)) =
10616 self.selection_history.transaction_mut(transaction_id)
10617 {
10618 *end_selections = Some(self.selections.disjoint_anchors());
10619 } else {
10620 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10621 }
10622
10623 cx.emit(EditorEvent::Edited { transaction_id });
10624 Some(transaction_id)
10625 } else {
10626 None
10627 }
10628 }
10629
10630 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10631 let selection = self.selections.newest::<Point>(cx);
10632
10633 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10634 let range = if selection.is_empty() {
10635 let point = selection.head().to_display_point(&display_map);
10636 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10637 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10638 .to_point(&display_map);
10639 start..end
10640 } else {
10641 selection.range()
10642 };
10643 if display_map.folds_in_range(range).next().is_some() {
10644 self.unfold_lines(&Default::default(), cx)
10645 } else {
10646 self.fold(&Default::default(), cx)
10647 }
10648 }
10649
10650 pub fn toggle_fold_recursive(
10651 &mut self,
10652 _: &actions::ToggleFoldRecursive,
10653 cx: &mut ViewContext<Self>,
10654 ) {
10655 let selection = self.selections.newest::<Point>(cx);
10656
10657 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10658 let range = if selection.is_empty() {
10659 let point = selection.head().to_display_point(&display_map);
10660 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10661 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10662 .to_point(&display_map);
10663 start..end
10664 } else {
10665 selection.range()
10666 };
10667 if display_map.folds_in_range(range).next().is_some() {
10668 self.unfold_recursive(&Default::default(), cx)
10669 } else {
10670 self.fold_recursive(&Default::default(), cx)
10671 }
10672 }
10673
10674 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10675 let mut fold_ranges = Vec::new();
10676 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10677 let selections = self.selections.all_adjusted(cx);
10678
10679 for selection in selections {
10680 let range = selection.range().sorted();
10681 let buffer_start_row = range.start.row;
10682
10683 if range.start.row != range.end.row {
10684 let mut found = false;
10685 let mut row = range.start.row;
10686 while row <= range.end.row {
10687 if let Some((foldable_range, fold_text)) =
10688 { display_map.foldable_range(MultiBufferRow(row)) }
10689 {
10690 found = true;
10691 row = foldable_range.end.row + 1;
10692 fold_ranges.push((foldable_range, fold_text));
10693 } else {
10694 row += 1
10695 }
10696 }
10697 if found {
10698 continue;
10699 }
10700 }
10701
10702 for row in (0..=range.start.row).rev() {
10703 if let Some((foldable_range, fold_text)) =
10704 display_map.foldable_range(MultiBufferRow(row))
10705 {
10706 if foldable_range.end.row >= buffer_start_row {
10707 fold_ranges.push((foldable_range, fold_text));
10708 if row <= range.start.row {
10709 break;
10710 }
10711 }
10712 }
10713 }
10714 }
10715
10716 self.fold_ranges(fold_ranges, true, cx);
10717 }
10718
10719 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10720 let mut fold_ranges = Vec::new();
10721 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10722
10723 for row in 0..display_map.max_buffer_row().0 {
10724 if let Some((foldable_range, fold_text)) =
10725 display_map.foldable_range(MultiBufferRow(row))
10726 {
10727 fold_ranges.push((foldable_range, fold_text));
10728 }
10729 }
10730
10731 self.fold_ranges(fold_ranges, true, cx);
10732 }
10733
10734 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10735 let mut fold_ranges = Vec::new();
10736 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10737 let selections = self.selections.all_adjusted(cx);
10738
10739 for selection in selections {
10740 let range = selection.range().sorted();
10741 let buffer_start_row = range.start.row;
10742
10743 if range.start.row != range.end.row {
10744 let mut found = false;
10745 for row in range.start.row..=range.end.row {
10746 if let Some((foldable_range, fold_text)) =
10747 { display_map.foldable_range(MultiBufferRow(row)) }
10748 {
10749 found = true;
10750 fold_ranges.push((foldable_range, fold_text));
10751 }
10752 }
10753 if found {
10754 continue;
10755 }
10756 }
10757
10758 for row in (0..=range.start.row).rev() {
10759 if let Some((foldable_range, fold_text)) =
10760 display_map.foldable_range(MultiBufferRow(row))
10761 {
10762 if foldable_range.end.row >= buffer_start_row {
10763 fold_ranges.push((foldable_range, fold_text));
10764 } else {
10765 break;
10766 }
10767 }
10768 }
10769 }
10770
10771 self.fold_ranges(fold_ranges, true, cx);
10772 }
10773
10774 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10775 let buffer_row = fold_at.buffer_row;
10776 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10777
10778 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10779 let autoscroll = self
10780 .selections
10781 .all::<Point>(cx)
10782 .iter()
10783 .any(|selection| fold_range.overlaps(&selection.range()));
10784
10785 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10786 }
10787 }
10788
10789 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10790 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10791 let buffer = &display_map.buffer_snapshot;
10792 let selections = self.selections.all::<Point>(cx);
10793 let ranges = selections
10794 .iter()
10795 .map(|s| {
10796 let range = s.display_range(&display_map).sorted();
10797 let mut start = range.start.to_point(&display_map);
10798 let mut end = range.end.to_point(&display_map);
10799 start.column = 0;
10800 end.column = buffer.line_len(MultiBufferRow(end.row));
10801 start..end
10802 })
10803 .collect::<Vec<_>>();
10804
10805 self.unfold_ranges(ranges, true, true, cx);
10806 }
10807
10808 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10809 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10810 let selections = self.selections.all::<Point>(cx);
10811 let ranges = selections
10812 .iter()
10813 .map(|s| {
10814 let mut range = s.display_range(&display_map).sorted();
10815 *range.start.column_mut() = 0;
10816 *range.end.column_mut() = display_map.line_len(range.end.row());
10817 let start = range.start.to_point(&display_map);
10818 let end = range.end.to_point(&display_map);
10819 start..end
10820 })
10821 .collect::<Vec<_>>();
10822
10823 self.unfold_ranges(ranges, true, true, cx);
10824 }
10825
10826 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10827 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10828
10829 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10830 ..Point::new(
10831 unfold_at.buffer_row.0,
10832 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10833 );
10834
10835 let autoscroll = self
10836 .selections
10837 .all::<Point>(cx)
10838 .iter()
10839 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10840
10841 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10842 }
10843
10844 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10845 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10846 self.unfold_ranges(
10847 [Point::zero()..display_map.max_point().to_point(&display_map)],
10848 true,
10849 true,
10850 cx,
10851 );
10852 }
10853
10854 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10855 let selections = self.selections.all::<Point>(cx);
10856 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10857 let line_mode = self.selections.line_mode;
10858 let ranges = selections.into_iter().map(|s| {
10859 if line_mode {
10860 let start = Point::new(s.start.row, 0);
10861 let end = Point::new(
10862 s.end.row,
10863 display_map
10864 .buffer_snapshot
10865 .line_len(MultiBufferRow(s.end.row)),
10866 );
10867 (start..end, display_map.fold_placeholder.clone())
10868 } else {
10869 (s.start..s.end, display_map.fold_placeholder.clone())
10870 }
10871 });
10872 self.fold_ranges(ranges, true, cx);
10873 }
10874
10875 pub fn fold_ranges<T: ToOffset + Clone>(
10876 &mut self,
10877 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10878 auto_scroll: bool,
10879 cx: &mut ViewContext<Self>,
10880 ) {
10881 let mut fold_ranges = Vec::new();
10882 let mut buffers_affected = HashMap::default();
10883 let multi_buffer = self.buffer().read(cx);
10884 for (fold_range, fold_text) in ranges {
10885 if let Some((_, buffer, _)) =
10886 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10887 {
10888 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10889 };
10890 fold_ranges.push((fold_range, fold_text));
10891 }
10892
10893 let mut ranges = fold_ranges.into_iter().peekable();
10894 if ranges.peek().is_some() {
10895 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10896
10897 if auto_scroll {
10898 self.request_autoscroll(Autoscroll::fit(), cx);
10899 }
10900
10901 for buffer in buffers_affected.into_values() {
10902 self.sync_expanded_diff_hunks(buffer, cx);
10903 }
10904
10905 cx.notify();
10906
10907 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10908 // Clear diagnostics block when folding a range that contains it.
10909 let snapshot = self.snapshot(cx);
10910 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10911 drop(snapshot);
10912 self.active_diagnostics = Some(active_diagnostics);
10913 self.dismiss_diagnostics(cx);
10914 } else {
10915 self.active_diagnostics = Some(active_diagnostics);
10916 }
10917 }
10918
10919 self.scrollbar_marker_state.dirty = true;
10920 }
10921 }
10922
10923 pub fn unfold_ranges<T: ToOffset + Clone>(
10924 &mut self,
10925 ranges: impl IntoIterator<Item = Range<T>>,
10926 inclusive: bool,
10927 auto_scroll: bool,
10928 cx: &mut ViewContext<Self>,
10929 ) {
10930 let mut unfold_ranges = Vec::new();
10931 let mut buffers_affected = HashMap::default();
10932 let multi_buffer = self.buffer().read(cx);
10933 for range in ranges {
10934 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10935 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10936 };
10937 unfold_ranges.push(range);
10938 }
10939
10940 let mut ranges = unfold_ranges.into_iter().peekable();
10941 if ranges.peek().is_some() {
10942 self.display_map
10943 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10944 if auto_scroll {
10945 self.request_autoscroll(Autoscroll::fit(), cx);
10946 }
10947
10948 for buffer in buffers_affected.into_values() {
10949 self.sync_expanded_diff_hunks(buffer, cx);
10950 }
10951
10952 cx.notify();
10953 self.scrollbar_marker_state.dirty = true;
10954 self.active_indent_guides_state.dirty = true;
10955 }
10956 }
10957
10958 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10959 self.display_map.read(cx).fold_placeholder.clone()
10960 }
10961
10962 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10963 if hovered != self.gutter_hovered {
10964 self.gutter_hovered = hovered;
10965 cx.notify();
10966 }
10967 }
10968
10969 pub fn insert_blocks(
10970 &mut self,
10971 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10972 autoscroll: Option<Autoscroll>,
10973 cx: &mut ViewContext<Self>,
10974 ) -> Vec<CustomBlockId> {
10975 let blocks = self
10976 .display_map
10977 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10978 if let Some(autoscroll) = autoscroll {
10979 self.request_autoscroll(autoscroll, cx);
10980 }
10981 cx.notify();
10982 blocks
10983 }
10984
10985 pub fn resize_blocks(
10986 &mut self,
10987 heights: HashMap<CustomBlockId, u32>,
10988 autoscroll: Option<Autoscroll>,
10989 cx: &mut ViewContext<Self>,
10990 ) {
10991 self.display_map
10992 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10993 if let Some(autoscroll) = autoscroll {
10994 self.request_autoscroll(autoscroll, cx);
10995 }
10996 cx.notify();
10997 }
10998
10999 pub fn replace_blocks(
11000 &mut self,
11001 renderers: HashMap<CustomBlockId, RenderBlock>,
11002 autoscroll: Option<Autoscroll>,
11003 cx: &mut ViewContext<Self>,
11004 ) {
11005 self.display_map
11006 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11007 if let Some(autoscroll) = autoscroll {
11008 self.request_autoscroll(autoscroll, cx);
11009 }
11010 cx.notify();
11011 }
11012
11013 pub fn remove_blocks(
11014 &mut self,
11015 block_ids: HashSet<CustomBlockId>,
11016 autoscroll: Option<Autoscroll>,
11017 cx: &mut ViewContext<Self>,
11018 ) {
11019 self.display_map.update(cx, |display_map, cx| {
11020 display_map.remove_blocks(block_ids, cx)
11021 });
11022 if let Some(autoscroll) = autoscroll {
11023 self.request_autoscroll(autoscroll, cx);
11024 }
11025 cx.notify();
11026 }
11027
11028 pub fn row_for_block(
11029 &self,
11030 block_id: CustomBlockId,
11031 cx: &mut ViewContext<Self>,
11032 ) -> Option<DisplayRow> {
11033 self.display_map
11034 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11035 }
11036
11037 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11038 self.focused_block = Some(focused_block);
11039 }
11040
11041 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11042 self.focused_block.take()
11043 }
11044
11045 pub fn insert_creases(
11046 &mut self,
11047 creases: impl IntoIterator<Item = Crease>,
11048 cx: &mut ViewContext<Self>,
11049 ) -> Vec<CreaseId> {
11050 self.display_map
11051 .update(cx, |map, cx| map.insert_creases(creases, cx))
11052 }
11053
11054 pub fn remove_creases(
11055 &mut self,
11056 ids: impl IntoIterator<Item = CreaseId>,
11057 cx: &mut ViewContext<Self>,
11058 ) {
11059 self.display_map
11060 .update(cx, |map, cx| map.remove_creases(ids, cx));
11061 }
11062
11063 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11064 self.display_map
11065 .update(cx, |map, cx| map.snapshot(cx))
11066 .longest_row()
11067 }
11068
11069 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11070 self.display_map
11071 .update(cx, |map, cx| map.snapshot(cx))
11072 .max_point()
11073 }
11074
11075 pub fn text(&self, cx: &AppContext) -> String {
11076 self.buffer.read(cx).read(cx).text()
11077 }
11078
11079 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11080 let text = self.text(cx);
11081 let text = text.trim();
11082
11083 if text.is_empty() {
11084 return None;
11085 }
11086
11087 Some(text.to_string())
11088 }
11089
11090 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11091 self.transact(cx, |this, cx| {
11092 this.buffer
11093 .read(cx)
11094 .as_singleton()
11095 .expect("you can only call set_text on editors for singleton buffers")
11096 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11097 });
11098 }
11099
11100 pub fn display_text(&self, cx: &mut AppContext) -> String {
11101 self.display_map
11102 .update(cx, |map, cx| map.snapshot(cx))
11103 .text()
11104 }
11105
11106 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11107 let mut wrap_guides = smallvec::smallvec![];
11108
11109 if self.show_wrap_guides == Some(false) {
11110 return wrap_guides;
11111 }
11112
11113 let settings = self.buffer.read(cx).settings_at(0, cx);
11114 if settings.show_wrap_guides {
11115 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11116 wrap_guides.push((soft_wrap as usize, true));
11117 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11118 wrap_guides.push((soft_wrap as usize, true));
11119 }
11120 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11121 }
11122
11123 wrap_guides
11124 }
11125
11126 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11127 let settings = self.buffer.read(cx).settings_at(0, cx);
11128 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11129 match mode {
11130 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11131 SoftWrap::None
11132 }
11133 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11134 language_settings::SoftWrap::PreferredLineLength => {
11135 SoftWrap::Column(settings.preferred_line_length)
11136 }
11137 language_settings::SoftWrap::Bounded => {
11138 SoftWrap::Bounded(settings.preferred_line_length)
11139 }
11140 }
11141 }
11142
11143 pub fn set_soft_wrap_mode(
11144 &mut self,
11145 mode: language_settings::SoftWrap,
11146 cx: &mut ViewContext<Self>,
11147 ) {
11148 self.soft_wrap_mode_override = Some(mode);
11149 cx.notify();
11150 }
11151
11152 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11153 let rem_size = cx.rem_size();
11154 self.display_map.update(cx, |map, cx| {
11155 map.set_font(
11156 style.text.font(),
11157 style.text.font_size.to_pixels(rem_size),
11158 cx,
11159 )
11160 });
11161 self.style = Some(style);
11162 }
11163
11164 pub fn style(&self) -> Option<&EditorStyle> {
11165 self.style.as_ref()
11166 }
11167
11168 // Called by the element. This method is not designed to be called outside of the editor
11169 // element's layout code because it does not notify when rewrapping is computed synchronously.
11170 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11171 self.display_map
11172 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11173 }
11174
11175 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11176 if self.soft_wrap_mode_override.is_some() {
11177 self.soft_wrap_mode_override.take();
11178 } else {
11179 let soft_wrap = match self.soft_wrap_mode(cx) {
11180 SoftWrap::GitDiff => return,
11181 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11182 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11183 language_settings::SoftWrap::None
11184 }
11185 };
11186 self.soft_wrap_mode_override = Some(soft_wrap);
11187 }
11188 cx.notify();
11189 }
11190
11191 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11192 let Some(workspace) = self.workspace() else {
11193 return;
11194 };
11195 let fs = workspace.read(cx).app_state().fs.clone();
11196 let current_show = TabBarSettings::get_global(cx).show;
11197 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11198 setting.show = Some(!current_show);
11199 });
11200 }
11201
11202 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11203 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11204 self.buffer
11205 .read(cx)
11206 .settings_at(0, cx)
11207 .indent_guides
11208 .enabled
11209 });
11210 self.show_indent_guides = Some(!currently_enabled);
11211 cx.notify();
11212 }
11213
11214 fn should_show_indent_guides(&self) -> Option<bool> {
11215 self.show_indent_guides
11216 }
11217
11218 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11219 let mut editor_settings = EditorSettings::get_global(cx).clone();
11220 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11221 EditorSettings::override_global(editor_settings, cx);
11222 }
11223
11224 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11225 self.use_relative_line_numbers
11226 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11227 }
11228
11229 pub fn toggle_relative_line_numbers(
11230 &mut self,
11231 _: &ToggleRelativeLineNumbers,
11232 cx: &mut ViewContext<Self>,
11233 ) {
11234 let is_relative = self.should_use_relative_line_numbers(cx);
11235 self.set_relative_line_number(Some(!is_relative), cx)
11236 }
11237
11238 pub fn set_relative_line_number(
11239 &mut self,
11240 is_relative: Option<bool>,
11241 cx: &mut ViewContext<Self>,
11242 ) {
11243 self.use_relative_line_numbers = is_relative;
11244 cx.notify();
11245 }
11246
11247 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11248 self.show_gutter = show_gutter;
11249 cx.notify();
11250 }
11251
11252 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11253 self.show_line_numbers = Some(show_line_numbers);
11254 cx.notify();
11255 }
11256
11257 pub fn set_show_git_diff_gutter(
11258 &mut self,
11259 show_git_diff_gutter: bool,
11260 cx: &mut ViewContext<Self>,
11261 ) {
11262 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11263 cx.notify();
11264 }
11265
11266 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11267 self.show_code_actions = Some(show_code_actions);
11268 cx.notify();
11269 }
11270
11271 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11272 self.show_runnables = Some(show_runnables);
11273 cx.notify();
11274 }
11275
11276 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11277 if self.display_map.read(cx).masked != masked {
11278 self.display_map.update(cx, |map, _| map.masked = masked);
11279 }
11280 cx.notify()
11281 }
11282
11283 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11284 self.show_wrap_guides = Some(show_wrap_guides);
11285 cx.notify();
11286 }
11287
11288 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11289 self.show_indent_guides = Some(show_indent_guides);
11290 cx.notify();
11291 }
11292
11293 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11294 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11295 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11296 if let Some(dir) = file.abs_path(cx).parent() {
11297 return Some(dir.to_owned());
11298 }
11299 }
11300
11301 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11302 return Some(project_path.path.to_path_buf());
11303 }
11304 }
11305
11306 None
11307 }
11308
11309 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11310 self.active_excerpt(cx)?
11311 .1
11312 .read(cx)
11313 .file()
11314 .and_then(|f| f.as_local())
11315 }
11316
11317 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11318 if let Some(target) = self.target_file(cx) {
11319 cx.reveal_path(&target.abs_path(cx));
11320 }
11321 }
11322
11323 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11324 if let Some(file) = self.target_file(cx) {
11325 if let Some(path) = file.abs_path(cx).to_str() {
11326 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11327 }
11328 }
11329 }
11330
11331 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11332 if let Some(file) = self.target_file(cx) {
11333 if let Some(path) = file.path().to_str() {
11334 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11335 }
11336 }
11337 }
11338
11339 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11340 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11341
11342 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11343 self.start_git_blame(true, cx);
11344 }
11345
11346 cx.notify();
11347 }
11348
11349 pub fn toggle_git_blame_inline(
11350 &mut self,
11351 _: &ToggleGitBlameInline,
11352 cx: &mut ViewContext<Self>,
11353 ) {
11354 self.toggle_git_blame_inline_internal(true, cx);
11355 cx.notify();
11356 }
11357
11358 pub fn git_blame_inline_enabled(&self) -> bool {
11359 self.git_blame_inline_enabled
11360 }
11361
11362 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11363 self.show_selection_menu = self
11364 .show_selection_menu
11365 .map(|show_selections_menu| !show_selections_menu)
11366 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11367
11368 cx.notify();
11369 }
11370
11371 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11372 self.show_selection_menu
11373 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11374 }
11375
11376 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11377 if let Some(project) = self.project.as_ref() {
11378 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11379 return;
11380 };
11381
11382 if buffer.read(cx).file().is_none() {
11383 return;
11384 }
11385
11386 let focused = self.focus_handle(cx).contains_focused(cx);
11387
11388 let project = project.clone();
11389 let blame =
11390 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11391 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11392 self.blame = Some(blame);
11393 }
11394 }
11395
11396 fn toggle_git_blame_inline_internal(
11397 &mut self,
11398 user_triggered: bool,
11399 cx: &mut ViewContext<Self>,
11400 ) {
11401 if self.git_blame_inline_enabled {
11402 self.git_blame_inline_enabled = false;
11403 self.show_git_blame_inline = false;
11404 self.show_git_blame_inline_delay_task.take();
11405 } else {
11406 self.git_blame_inline_enabled = true;
11407 self.start_git_blame_inline(user_triggered, cx);
11408 }
11409
11410 cx.notify();
11411 }
11412
11413 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11414 self.start_git_blame(user_triggered, cx);
11415
11416 if ProjectSettings::get_global(cx)
11417 .git
11418 .inline_blame_delay()
11419 .is_some()
11420 {
11421 self.start_inline_blame_timer(cx);
11422 } else {
11423 self.show_git_blame_inline = true
11424 }
11425 }
11426
11427 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11428 self.blame.as_ref()
11429 }
11430
11431 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11432 self.show_git_blame_gutter && self.has_blame_entries(cx)
11433 }
11434
11435 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11436 self.show_git_blame_inline
11437 && self.focus_handle.is_focused(cx)
11438 && !self.newest_selection_head_on_empty_line(cx)
11439 && self.has_blame_entries(cx)
11440 }
11441
11442 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11443 self.blame()
11444 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11445 }
11446
11447 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11448 let cursor_anchor = self.selections.newest_anchor().head();
11449
11450 let snapshot = self.buffer.read(cx).snapshot(cx);
11451 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11452
11453 snapshot.line_len(buffer_row) == 0
11454 }
11455
11456 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11457 let (path, selection, repo) = maybe!({
11458 let project_handle = self.project.as_ref()?.clone();
11459 let project = project_handle.read(cx);
11460
11461 let selection = self.selections.newest::<Point>(cx);
11462 let selection_range = selection.range();
11463
11464 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11465 (buffer, selection_range.start.row..selection_range.end.row)
11466 } else {
11467 let buffer_ranges = self
11468 .buffer()
11469 .read(cx)
11470 .range_to_buffer_ranges(selection_range, cx);
11471
11472 let (buffer, range, _) = if selection.reversed {
11473 buffer_ranges.first()
11474 } else {
11475 buffer_ranges.last()
11476 }?;
11477
11478 let snapshot = buffer.read(cx).snapshot();
11479 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11480 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11481 (buffer.clone(), selection)
11482 };
11483
11484 let path = buffer
11485 .read(cx)
11486 .file()?
11487 .as_local()?
11488 .path()
11489 .to_str()?
11490 .to_string();
11491 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11492 Some((path, selection, repo))
11493 })
11494 .ok_or_else(|| anyhow!("unable to open git repository"))?;
11495
11496 const REMOTE_NAME: &str = "origin";
11497 let origin_url = repo
11498 .remote_url(REMOTE_NAME)
11499 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11500 let sha = repo
11501 .head_sha()
11502 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11503
11504 let (provider, remote) =
11505 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11506 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11507
11508 Ok(provider.build_permalink(
11509 remote,
11510 BuildPermalinkParams {
11511 sha: &sha,
11512 path: &path,
11513 selection: Some(selection),
11514 },
11515 ))
11516 }
11517
11518 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11519 let permalink = self.get_permalink_to_line(cx);
11520
11521 match permalink {
11522 Ok(permalink) => {
11523 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11524 }
11525 Err(err) => {
11526 let message = format!("Failed to copy permalink: {err}");
11527
11528 Err::<(), anyhow::Error>(err).log_err();
11529
11530 if let Some(workspace) = self.workspace() {
11531 workspace.update(cx, |workspace, cx| {
11532 struct CopyPermalinkToLine;
11533
11534 workspace.show_toast(
11535 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11536 cx,
11537 )
11538 })
11539 }
11540 }
11541 }
11542 }
11543
11544 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11545 if let Some(file) = self.target_file(cx) {
11546 if let Some(path) = file.path().to_str() {
11547 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11548 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11549 }
11550 }
11551 }
11552
11553 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11554 let permalink = self.get_permalink_to_line(cx);
11555
11556 match permalink {
11557 Ok(permalink) => {
11558 cx.open_url(permalink.as_ref());
11559 }
11560 Err(err) => {
11561 let message = format!("Failed to open permalink: {err}");
11562
11563 Err::<(), anyhow::Error>(err).log_err();
11564
11565 if let Some(workspace) = self.workspace() {
11566 workspace.update(cx, |workspace, cx| {
11567 struct OpenPermalinkToLine;
11568
11569 workspace.show_toast(
11570 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11571 cx,
11572 )
11573 })
11574 }
11575 }
11576 }
11577 }
11578
11579 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11580 /// last highlight added will be used.
11581 ///
11582 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11583 pub fn highlight_rows<T: 'static>(
11584 &mut self,
11585 range: Range<Anchor>,
11586 color: Hsla,
11587 should_autoscroll: bool,
11588 cx: &mut ViewContext<Self>,
11589 ) {
11590 let snapshot = self.buffer().read(cx).snapshot(cx);
11591 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11592 let ix = row_highlights.binary_search_by(|highlight| {
11593 Ordering::Equal
11594 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11595 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11596 });
11597
11598 if let Err(mut ix) = ix {
11599 let index = post_inc(&mut self.highlight_order);
11600
11601 // If this range intersects with the preceding highlight, then merge it with
11602 // the preceding highlight. Otherwise insert a new highlight.
11603 let mut merged = false;
11604 if ix > 0 {
11605 let prev_highlight = &mut row_highlights[ix - 1];
11606 if prev_highlight
11607 .range
11608 .end
11609 .cmp(&range.start, &snapshot)
11610 .is_ge()
11611 {
11612 ix -= 1;
11613 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11614 prev_highlight.range.end = range.end;
11615 }
11616 merged = true;
11617 prev_highlight.index = index;
11618 prev_highlight.color = color;
11619 prev_highlight.should_autoscroll = should_autoscroll;
11620 }
11621 }
11622
11623 if !merged {
11624 row_highlights.insert(
11625 ix,
11626 RowHighlight {
11627 range: range.clone(),
11628 index,
11629 color,
11630 should_autoscroll,
11631 },
11632 );
11633 }
11634
11635 // If any of the following highlights intersect with this one, merge them.
11636 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11637 let highlight = &row_highlights[ix];
11638 if next_highlight
11639 .range
11640 .start
11641 .cmp(&highlight.range.end, &snapshot)
11642 .is_le()
11643 {
11644 if next_highlight
11645 .range
11646 .end
11647 .cmp(&highlight.range.end, &snapshot)
11648 .is_gt()
11649 {
11650 row_highlights[ix].range.end = next_highlight.range.end;
11651 }
11652 row_highlights.remove(ix + 1);
11653 } else {
11654 break;
11655 }
11656 }
11657 }
11658 }
11659
11660 /// Remove any highlighted row ranges of the given type that intersect the
11661 /// given ranges.
11662 pub fn remove_highlighted_rows<T: 'static>(
11663 &mut self,
11664 ranges_to_remove: Vec<Range<Anchor>>,
11665 cx: &mut ViewContext<Self>,
11666 ) {
11667 let snapshot = self.buffer().read(cx).snapshot(cx);
11668 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11669 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11670 row_highlights.retain(|highlight| {
11671 while let Some(range_to_remove) = ranges_to_remove.peek() {
11672 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11673 Ordering::Less | Ordering::Equal => {
11674 ranges_to_remove.next();
11675 }
11676 Ordering::Greater => {
11677 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11678 Ordering::Less | Ordering::Equal => {
11679 return false;
11680 }
11681 Ordering::Greater => break,
11682 }
11683 }
11684 }
11685 }
11686
11687 true
11688 })
11689 }
11690
11691 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11692 pub fn clear_row_highlights<T: 'static>(&mut self) {
11693 self.highlighted_rows.remove(&TypeId::of::<T>());
11694 }
11695
11696 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11697 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11698 self.highlighted_rows
11699 .get(&TypeId::of::<T>())
11700 .map_or(&[] as &[_], |vec| vec.as_slice())
11701 .iter()
11702 .map(|highlight| (highlight.range.clone(), highlight.color))
11703 }
11704
11705 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11706 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11707 /// Allows to ignore certain kinds of highlights.
11708 pub fn highlighted_display_rows(
11709 &mut self,
11710 cx: &mut WindowContext,
11711 ) -> BTreeMap<DisplayRow, Hsla> {
11712 let snapshot = self.snapshot(cx);
11713 let mut used_highlight_orders = HashMap::default();
11714 self.highlighted_rows
11715 .iter()
11716 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11717 .fold(
11718 BTreeMap::<DisplayRow, Hsla>::new(),
11719 |mut unique_rows, highlight| {
11720 let start = highlight.range.start.to_display_point(&snapshot);
11721 let end = highlight.range.end.to_display_point(&snapshot);
11722 let start_row = start.row().0;
11723 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11724 && end.column() == 0
11725 {
11726 end.row().0.saturating_sub(1)
11727 } else {
11728 end.row().0
11729 };
11730 for row in start_row..=end_row {
11731 let used_index =
11732 used_highlight_orders.entry(row).or_insert(highlight.index);
11733 if highlight.index >= *used_index {
11734 *used_index = highlight.index;
11735 unique_rows.insert(DisplayRow(row), highlight.color);
11736 }
11737 }
11738 unique_rows
11739 },
11740 )
11741 }
11742
11743 pub fn highlighted_display_row_for_autoscroll(
11744 &self,
11745 snapshot: &DisplaySnapshot,
11746 ) -> Option<DisplayRow> {
11747 self.highlighted_rows
11748 .values()
11749 .flat_map(|highlighted_rows| highlighted_rows.iter())
11750 .filter_map(|highlight| {
11751 if highlight.should_autoscroll {
11752 Some(highlight.range.start.to_display_point(snapshot).row())
11753 } else {
11754 None
11755 }
11756 })
11757 .min()
11758 }
11759
11760 pub fn set_search_within_ranges(
11761 &mut self,
11762 ranges: &[Range<Anchor>],
11763 cx: &mut ViewContext<Self>,
11764 ) {
11765 self.highlight_background::<SearchWithinRange>(
11766 ranges,
11767 |colors| colors.editor_document_highlight_read_background,
11768 cx,
11769 )
11770 }
11771
11772 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11773 self.breadcrumb_header = Some(new_header);
11774 }
11775
11776 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11777 self.clear_background_highlights::<SearchWithinRange>(cx);
11778 }
11779
11780 pub fn highlight_background<T: 'static>(
11781 &mut self,
11782 ranges: &[Range<Anchor>],
11783 color_fetcher: fn(&ThemeColors) -> Hsla,
11784 cx: &mut ViewContext<Self>,
11785 ) {
11786 self.background_highlights
11787 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11788 self.scrollbar_marker_state.dirty = true;
11789 cx.notify();
11790 }
11791
11792 pub fn clear_background_highlights<T: 'static>(
11793 &mut self,
11794 cx: &mut ViewContext<Self>,
11795 ) -> Option<BackgroundHighlight> {
11796 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11797 if !text_highlights.1.is_empty() {
11798 self.scrollbar_marker_state.dirty = true;
11799 cx.notify();
11800 }
11801 Some(text_highlights)
11802 }
11803
11804 pub fn highlight_gutter<T: 'static>(
11805 &mut self,
11806 ranges: &[Range<Anchor>],
11807 color_fetcher: fn(&AppContext) -> Hsla,
11808 cx: &mut ViewContext<Self>,
11809 ) {
11810 self.gutter_highlights
11811 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11812 cx.notify();
11813 }
11814
11815 pub fn clear_gutter_highlights<T: 'static>(
11816 &mut self,
11817 cx: &mut ViewContext<Self>,
11818 ) -> Option<GutterHighlight> {
11819 cx.notify();
11820 self.gutter_highlights.remove(&TypeId::of::<T>())
11821 }
11822
11823 #[cfg(feature = "test-support")]
11824 pub fn all_text_background_highlights(
11825 &mut self,
11826 cx: &mut ViewContext<Self>,
11827 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11828 let snapshot = self.snapshot(cx);
11829 let buffer = &snapshot.buffer_snapshot;
11830 let start = buffer.anchor_before(0);
11831 let end = buffer.anchor_after(buffer.len());
11832 let theme = cx.theme().colors();
11833 self.background_highlights_in_range(start..end, &snapshot, theme)
11834 }
11835
11836 #[cfg(feature = "test-support")]
11837 pub fn search_background_highlights(
11838 &mut self,
11839 cx: &mut ViewContext<Self>,
11840 ) -> Vec<Range<Point>> {
11841 let snapshot = self.buffer().read(cx).snapshot(cx);
11842
11843 let highlights = self
11844 .background_highlights
11845 .get(&TypeId::of::<items::BufferSearchHighlights>());
11846
11847 if let Some((_color, ranges)) = highlights {
11848 ranges
11849 .iter()
11850 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11851 .collect_vec()
11852 } else {
11853 vec![]
11854 }
11855 }
11856
11857 fn document_highlights_for_position<'a>(
11858 &'a self,
11859 position: Anchor,
11860 buffer: &'a MultiBufferSnapshot,
11861 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11862 let read_highlights = self
11863 .background_highlights
11864 .get(&TypeId::of::<DocumentHighlightRead>())
11865 .map(|h| &h.1);
11866 let write_highlights = self
11867 .background_highlights
11868 .get(&TypeId::of::<DocumentHighlightWrite>())
11869 .map(|h| &h.1);
11870 let left_position = position.bias_left(buffer);
11871 let right_position = position.bias_right(buffer);
11872 read_highlights
11873 .into_iter()
11874 .chain(write_highlights)
11875 .flat_map(move |ranges| {
11876 let start_ix = match ranges.binary_search_by(|probe| {
11877 let cmp = probe.end.cmp(&left_position, buffer);
11878 if cmp.is_ge() {
11879 Ordering::Greater
11880 } else {
11881 Ordering::Less
11882 }
11883 }) {
11884 Ok(i) | Err(i) => i,
11885 };
11886
11887 ranges[start_ix..]
11888 .iter()
11889 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11890 })
11891 }
11892
11893 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11894 self.background_highlights
11895 .get(&TypeId::of::<T>())
11896 .map_or(false, |(_, highlights)| !highlights.is_empty())
11897 }
11898
11899 pub fn background_highlights_in_range(
11900 &self,
11901 search_range: Range<Anchor>,
11902 display_snapshot: &DisplaySnapshot,
11903 theme: &ThemeColors,
11904 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11905 let mut results = Vec::new();
11906 for (color_fetcher, ranges) in self.background_highlights.values() {
11907 let color = color_fetcher(theme);
11908 let start_ix = match ranges.binary_search_by(|probe| {
11909 let cmp = probe
11910 .end
11911 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11912 if cmp.is_gt() {
11913 Ordering::Greater
11914 } else {
11915 Ordering::Less
11916 }
11917 }) {
11918 Ok(i) | Err(i) => i,
11919 };
11920 for range in &ranges[start_ix..] {
11921 if range
11922 .start
11923 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11924 .is_ge()
11925 {
11926 break;
11927 }
11928
11929 let start = range.start.to_display_point(display_snapshot);
11930 let end = range.end.to_display_point(display_snapshot);
11931 results.push((start..end, color))
11932 }
11933 }
11934 results
11935 }
11936
11937 pub fn background_highlight_row_ranges<T: 'static>(
11938 &self,
11939 search_range: Range<Anchor>,
11940 display_snapshot: &DisplaySnapshot,
11941 count: usize,
11942 ) -> Vec<RangeInclusive<DisplayPoint>> {
11943 let mut results = Vec::new();
11944 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11945 return vec![];
11946 };
11947
11948 let start_ix = match ranges.binary_search_by(|probe| {
11949 let cmp = probe
11950 .end
11951 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11952 if cmp.is_gt() {
11953 Ordering::Greater
11954 } else {
11955 Ordering::Less
11956 }
11957 }) {
11958 Ok(i) | Err(i) => i,
11959 };
11960 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11961 if let (Some(start_display), Some(end_display)) = (start, end) {
11962 results.push(
11963 start_display.to_display_point(display_snapshot)
11964 ..=end_display.to_display_point(display_snapshot),
11965 );
11966 }
11967 };
11968 let mut start_row: Option<Point> = None;
11969 let mut end_row: Option<Point> = None;
11970 if ranges.len() > count {
11971 return Vec::new();
11972 }
11973 for range in &ranges[start_ix..] {
11974 if range
11975 .start
11976 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11977 .is_ge()
11978 {
11979 break;
11980 }
11981 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11982 if let Some(current_row) = &end_row {
11983 if end.row == current_row.row {
11984 continue;
11985 }
11986 }
11987 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11988 if start_row.is_none() {
11989 assert_eq!(end_row, None);
11990 start_row = Some(start);
11991 end_row = Some(end);
11992 continue;
11993 }
11994 if let Some(current_end) = end_row.as_mut() {
11995 if start.row > current_end.row + 1 {
11996 push_region(start_row, end_row);
11997 start_row = Some(start);
11998 end_row = Some(end);
11999 } else {
12000 // Merge two hunks.
12001 *current_end = end;
12002 }
12003 } else {
12004 unreachable!();
12005 }
12006 }
12007 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12008 push_region(start_row, end_row);
12009 results
12010 }
12011
12012 pub fn gutter_highlights_in_range(
12013 &self,
12014 search_range: Range<Anchor>,
12015 display_snapshot: &DisplaySnapshot,
12016 cx: &AppContext,
12017 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12018 let mut results = Vec::new();
12019 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12020 let color = color_fetcher(cx);
12021 let start_ix = match ranges.binary_search_by(|probe| {
12022 let cmp = probe
12023 .end
12024 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12025 if cmp.is_gt() {
12026 Ordering::Greater
12027 } else {
12028 Ordering::Less
12029 }
12030 }) {
12031 Ok(i) | Err(i) => i,
12032 };
12033 for range in &ranges[start_ix..] {
12034 if range
12035 .start
12036 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12037 .is_ge()
12038 {
12039 break;
12040 }
12041
12042 let start = range.start.to_display_point(display_snapshot);
12043 let end = range.end.to_display_point(display_snapshot);
12044 results.push((start..end, color))
12045 }
12046 }
12047 results
12048 }
12049
12050 /// Get the text ranges corresponding to the redaction query
12051 pub fn redacted_ranges(
12052 &self,
12053 search_range: Range<Anchor>,
12054 display_snapshot: &DisplaySnapshot,
12055 cx: &WindowContext,
12056 ) -> Vec<Range<DisplayPoint>> {
12057 display_snapshot
12058 .buffer_snapshot
12059 .redacted_ranges(search_range, |file| {
12060 if let Some(file) = file {
12061 file.is_private()
12062 && EditorSettings::get(
12063 Some(SettingsLocation {
12064 worktree_id: file.worktree_id(cx),
12065 path: file.path().as_ref(),
12066 }),
12067 cx,
12068 )
12069 .redact_private_values
12070 } else {
12071 false
12072 }
12073 })
12074 .map(|range| {
12075 range.start.to_display_point(display_snapshot)
12076 ..range.end.to_display_point(display_snapshot)
12077 })
12078 .collect()
12079 }
12080
12081 pub fn highlight_text<T: 'static>(
12082 &mut self,
12083 ranges: Vec<Range<Anchor>>,
12084 style: HighlightStyle,
12085 cx: &mut ViewContext<Self>,
12086 ) {
12087 self.display_map.update(cx, |map, _| {
12088 map.highlight_text(TypeId::of::<T>(), ranges, style)
12089 });
12090 cx.notify();
12091 }
12092
12093 pub(crate) fn highlight_inlays<T: 'static>(
12094 &mut self,
12095 highlights: Vec<InlayHighlight>,
12096 style: HighlightStyle,
12097 cx: &mut ViewContext<Self>,
12098 ) {
12099 self.display_map.update(cx, |map, _| {
12100 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12101 });
12102 cx.notify();
12103 }
12104
12105 pub fn text_highlights<'a, T: 'static>(
12106 &'a self,
12107 cx: &'a AppContext,
12108 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12109 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12110 }
12111
12112 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12113 let cleared = self
12114 .display_map
12115 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12116 if cleared {
12117 cx.notify();
12118 }
12119 }
12120
12121 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12122 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12123 && self.focus_handle.is_focused(cx)
12124 }
12125
12126 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12127 self.show_cursor_when_unfocused = is_enabled;
12128 cx.notify();
12129 }
12130
12131 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12132 cx.notify();
12133 }
12134
12135 fn on_buffer_event(
12136 &mut self,
12137 multibuffer: Model<MultiBuffer>,
12138 event: &multi_buffer::Event,
12139 cx: &mut ViewContext<Self>,
12140 ) {
12141 match event {
12142 multi_buffer::Event::Edited {
12143 singleton_buffer_edited,
12144 } => {
12145 self.scrollbar_marker_state.dirty = true;
12146 self.active_indent_guides_state.dirty = true;
12147 self.refresh_active_diagnostics(cx);
12148 self.refresh_code_actions(cx);
12149 if self.has_active_inline_completion(cx) {
12150 self.update_visible_inline_completion(cx);
12151 }
12152 cx.emit(EditorEvent::BufferEdited);
12153 cx.emit(SearchEvent::MatchesInvalidated);
12154 if *singleton_buffer_edited {
12155 if let Some(project) = &self.project {
12156 let project = project.read(cx);
12157 #[allow(clippy::mutable_key_type)]
12158 let languages_affected = multibuffer
12159 .read(cx)
12160 .all_buffers()
12161 .into_iter()
12162 .filter_map(|buffer| {
12163 let buffer = buffer.read(cx);
12164 let language = buffer.language()?;
12165 if project.is_local()
12166 && project.language_servers_for_buffer(buffer, cx).count() == 0
12167 {
12168 None
12169 } else {
12170 Some(language)
12171 }
12172 })
12173 .cloned()
12174 .collect::<HashSet<_>>();
12175 if !languages_affected.is_empty() {
12176 self.refresh_inlay_hints(
12177 InlayHintRefreshReason::BufferEdited(languages_affected),
12178 cx,
12179 );
12180 }
12181 }
12182 }
12183
12184 let Some(project) = &self.project else { return };
12185 let (telemetry, is_via_ssh) = {
12186 let project = project.read(cx);
12187 let telemetry = project.client().telemetry().clone();
12188 let is_via_ssh = project.is_via_ssh();
12189 (telemetry, is_via_ssh)
12190 };
12191 refresh_linked_ranges(self, cx);
12192 telemetry.log_edit_event("editor", is_via_ssh);
12193 }
12194 multi_buffer::Event::ExcerptsAdded {
12195 buffer,
12196 predecessor,
12197 excerpts,
12198 } => {
12199 self.tasks_update_task = Some(self.refresh_runnables(cx));
12200 cx.emit(EditorEvent::ExcerptsAdded {
12201 buffer: buffer.clone(),
12202 predecessor: *predecessor,
12203 excerpts: excerpts.clone(),
12204 });
12205 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12206 }
12207 multi_buffer::Event::ExcerptsRemoved { ids } => {
12208 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12209 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12210 }
12211 multi_buffer::Event::ExcerptsEdited { ids } => {
12212 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12213 }
12214 multi_buffer::Event::ExcerptsExpanded { ids } => {
12215 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12216 }
12217 multi_buffer::Event::Reparsed(buffer_id) => {
12218 self.tasks_update_task = Some(self.refresh_runnables(cx));
12219
12220 cx.emit(EditorEvent::Reparsed(*buffer_id));
12221 }
12222 multi_buffer::Event::LanguageChanged(buffer_id) => {
12223 linked_editing_ranges::refresh_linked_ranges(self, cx);
12224 cx.emit(EditorEvent::Reparsed(*buffer_id));
12225 cx.notify();
12226 }
12227 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12228 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12229 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12230 cx.emit(EditorEvent::TitleChanged)
12231 }
12232 multi_buffer::Event::DiffBaseChanged => {
12233 self.scrollbar_marker_state.dirty = true;
12234 cx.emit(EditorEvent::DiffBaseChanged);
12235 cx.notify();
12236 }
12237 multi_buffer::Event::DiffUpdated { buffer } => {
12238 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12239 cx.notify();
12240 }
12241 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12242 multi_buffer::Event::DiagnosticsUpdated => {
12243 self.refresh_active_diagnostics(cx);
12244 self.scrollbar_marker_state.dirty = true;
12245 cx.notify();
12246 }
12247 _ => {}
12248 };
12249 }
12250
12251 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12252 cx.notify();
12253 }
12254
12255 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12256 self.tasks_update_task = Some(self.refresh_runnables(cx));
12257 self.refresh_inline_completion(true, false, cx);
12258 self.refresh_inlay_hints(
12259 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12260 self.selections.newest_anchor().head(),
12261 &self.buffer.read(cx).snapshot(cx),
12262 cx,
12263 )),
12264 cx,
12265 );
12266
12267 let old_cursor_shape = self.cursor_shape;
12268
12269 {
12270 let editor_settings = EditorSettings::get_global(cx);
12271 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12272 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12273 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12274 }
12275
12276 if old_cursor_shape != self.cursor_shape {
12277 cx.emit(EditorEvent::CursorShapeChanged);
12278 }
12279
12280 let project_settings = ProjectSettings::get_global(cx);
12281 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12282
12283 if self.mode == EditorMode::Full {
12284 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12285 if self.git_blame_inline_enabled != inline_blame_enabled {
12286 self.toggle_git_blame_inline_internal(false, cx);
12287 }
12288 }
12289
12290 cx.notify();
12291 }
12292
12293 pub fn set_searchable(&mut self, searchable: bool) {
12294 self.searchable = searchable;
12295 }
12296
12297 pub fn searchable(&self) -> bool {
12298 self.searchable
12299 }
12300
12301 fn open_proposed_changes_editor(
12302 &mut self,
12303 _: &OpenProposedChangesEditor,
12304 cx: &mut ViewContext<Self>,
12305 ) {
12306 let Some(workspace) = self.workspace() else {
12307 cx.propagate();
12308 return;
12309 };
12310
12311 let buffer = self.buffer.read(cx);
12312 let mut new_selections_by_buffer = HashMap::default();
12313 for selection in self.selections.all::<usize>(cx) {
12314 for (buffer, range, _) in
12315 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12316 {
12317 let mut range = range.to_point(buffer.read(cx));
12318 range.start.column = 0;
12319 range.end.column = buffer.read(cx).line_len(range.end.row);
12320 new_selections_by_buffer
12321 .entry(buffer)
12322 .or_insert(Vec::new())
12323 .push(range)
12324 }
12325 }
12326
12327 let proposed_changes_buffers = new_selections_by_buffer
12328 .into_iter()
12329 .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
12330 .collect::<Vec<_>>();
12331 let proposed_changes_editor = cx.new_view(|cx| {
12332 ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
12333 });
12334
12335 cx.window_context().defer(move |cx| {
12336 workspace.update(cx, |workspace, cx| {
12337 workspace.active_pane().update(cx, |pane, cx| {
12338 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12339 });
12340 });
12341 });
12342 }
12343
12344 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12345 self.open_excerpts_common(true, cx)
12346 }
12347
12348 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12349 self.open_excerpts_common(false, cx)
12350 }
12351
12352 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12353 let buffer = self.buffer.read(cx);
12354 if buffer.is_singleton() {
12355 cx.propagate();
12356 return;
12357 }
12358
12359 let Some(workspace) = self.workspace() else {
12360 cx.propagate();
12361 return;
12362 };
12363
12364 let mut new_selections_by_buffer = HashMap::default();
12365 for selection in self.selections.all::<usize>(cx) {
12366 for (mut buffer_handle, mut range, _) in
12367 buffer.range_to_buffer_ranges(selection.range(), cx)
12368 {
12369 // When editing branch buffers, jump to the corresponding location
12370 // in their base buffer.
12371 let buffer = buffer_handle.read(cx);
12372 if let Some(base_buffer) = buffer.diff_base_buffer() {
12373 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12374 buffer_handle = base_buffer;
12375 }
12376
12377 if selection.reversed {
12378 mem::swap(&mut range.start, &mut range.end);
12379 }
12380 new_selections_by_buffer
12381 .entry(buffer_handle)
12382 .or_insert(Vec::new())
12383 .push(range)
12384 }
12385 }
12386
12387 // We defer the pane interaction because we ourselves are a workspace item
12388 // and activating a new item causes the pane to call a method on us reentrantly,
12389 // which panics if we're on the stack.
12390 cx.window_context().defer(move |cx| {
12391 workspace.update(cx, |workspace, cx| {
12392 let pane = if split {
12393 workspace.adjacent_pane(cx)
12394 } else {
12395 workspace.active_pane().clone()
12396 };
12397
12398 for (buffer, ranges) in new_selections_by_buffer {
12399 let editor =
12400 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12401 editor.update(cx, |editor, cx| {
12402 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12403 s.select_ranges(ranges);
12404 });
12405 });
12406 }
12407 })
12408 });
12409 }
12410
12411 fn jump(
12412 &mut self,
12413 path: ProjectPath,
12414 position: Point,
12415 anchor: language::Anchor,
12416 offset_from_top: u32,
12417 cx: &mut ViewContext<Self>,
12418 ) {
12419 let workspace = self.workspace();
12420 cx.spawn(|_, mut cx| async move {
12421 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12422 let editor = workspace.update(&mut cx, |workspace, cx| {
12423 // Reset the preview item id before opening the new item
12424 workspace.active_pane().update(cx, |pane, cx| {
12425 pane.set_preview_item_id(None, cx);
12426 });
12427 workspace.open_path_preview(path, None, true, true, cx)
12428 })?;
12429 let editor = editor
12430 .await?
12431 .downcast::<Editor>()
12432 .ok_or_else(|| anyhow!("opened item was not an editor"))?
12433 .downgrade();
12434 editor.update(&mut cx, |editor, cx| {
12435 let buffer = editor
12436 .buffer()
12437 .read(cx)
12438 .as_singleton()
12439 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12440 let buffer = buffer.read(cx);
12441 let cursor = if buffer.can_resolve(&anchor) {
12442 language::ToPoint::to_point(&anchor, buffer)
12443 } else {
12444 buffer.clip_point(position, Bias::Left)
12445 };
12446
12447 let nav_history = editor.nav_history.take();
12448 editor.change_selections(
12449 Some(Autoscroll::top_relative(offset_from_top as usize)),
12450 cx,
12451 |s| {
12452 s.select_ranges([cursor..cursor]);
12453 },
12454 );
12455 editor.nav_history = nav_history;
12456
12457 anyhow::Ok(())
12458 })??;
12459
12460 anyhow::Ok(())
12461 })
12462 .detach_and_log_err(cx);
12463 }
12464
12465 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12466 let snapshot = self.buffer.read(cx).read(cx);
12467 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12468 Some(
12469 ranges
12470 .iter()
12471 .map(move |range| {
12472 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12473 })
12474 .collect(),
12475 )
12476 }
12477
12478 fn selection_replacement_ranges(
12479 &self,
12480 range: Range<OffsetUtf16>,
12481 cx: &AppContext,
12482 ) -> Vec<Range<OffsetUtf16>> {
12483 let selections = self.selections.all::<OffsetUtf16>(cx);
12484 let newest_selection = selections
12485 .iter()
12486 .max_by_key(|selection| selection.id)
12487 .unwrap();
12488 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12489 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12490 let snapshot = self.buffer.read(cx).read(cx);
12491 selections
12492 .into_iter()
12493 .map(|mut selection| {
12494 selection.start.0 =
12495 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12496 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12497 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12498 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12499 })
12500 .collect()
12501 }
12502
12503 fn report_editor_event(
12504 &self,
12505 operation: &'static str,
12506 file_extension: Option<String>,
12507 cx: &AppContext,
12508 ) {
12509 if cfg!(any(test, feature = "test-support")) {
12510 return;
12511 }
12512
12513 let Some(project) = &self.project else { return };
12514
12515 // If None, we are in a file without an extension
12516 let file = self
12517 .buffer
12518 .read(cx)
12519 .as_singleton()
12520 .and_then(|b| b.read(cx).file());
12521 let file_extension = file_extension.or(file
12522 .as_ref()
12523 .and_then(|file| Path::new(file.file_name(cx)).extension())
12524 .and_then(|e| e.to_str())
12525 .map(|a| a.to_string()));
12526
12527 let vim_mode = cx
12528 .global::<SettingsStore>()
12529 .raw_user_settings()
12530 .get("vim_mode")
12531 == Some(&serde_json::Value::Bool(true));
12532
12533 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12534 == language::language_settings::InlineCompletionProvider::Copilot;
12535 let copilot_enabled_for_language = self
12536 .buffer
12537 .read(cx)
12538 .settings_at(0, cx)
12539 .show_inline_completions;
12540
12541 let project = project.read(cx);
12542 let telemetry = project.client().telemetry().clone();
12543 telemetry.report_editor_event(
12544 file_extension,
12545 vim_mode,
12546 operation,
12547 copilot_enabled,
12548 copilot_enabled_for_language,
12549 project.is_via_ssh(),
12550 )
12551 }
12552
12553 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12554 /// with each line being an array of {text, highlight} objects.
12555 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12556 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12557 return;
12558 };
12559
12560 #[derive(Serialize)]
12561 struct Chunk<'a> {
12562 text: String,
12563 highlight: Option<&'a str>,
12564 }
12565
12566 let snapshot = buffer.read(cx).snapshot();
12567 let range = self
12568 .selected_text_range(false, cx)
12569 .and_then(|selection| {
12570 if selection.range.is_empty() {
12571 None
12572 } else {
12573 Some(selection.range)
12574 }
12575 })
12576 .unwrap_or_else(|| 0..snapshot.len());
12577
12578 let chunks = snapshot.chunks(range, true);
12579 let mut lines = Vec::new();
12580 let mut line: VecDeque<Chunk> = VecDeque::new();
12581
12582 let Some(style) = self.style.as_ref() else {
12583 return;
12584 };
12585
12586 for chunk in chunks {
12587 let highlight = chunk
12588 .syntax_highlight_id
12589 .and_then(|id| id.name(&style.syntax));
12590 let mut chunk_lines = chunk.text.split('\n').peekable();
12591 while let Some(text) = chunk_lines.next() {
12592 let mut merged_with_last_token = false;
12593 if let Some(last_token) = line.back_mut() {
12594 if last_token.highlight == highlight {
12595 last_token.text.push_str(text);
12596 merged_with_last_token = true;
12597 }
12598 }
12599
12600 if !merged_with_last_token {
12601 line.push_back(Chunk {
12602 text: text.into(),
12603 highlight,
12604 });
12605 }
12606
12607 if chunk_lines.peek().is_some() {
12608 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12609 line.pop_front();
12610 }
12611 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12612 line.pop_back();
12613 }
12614
12615 lines.push(mem::take(&mut line));
12616 }
12617 }
12618 }
12619
12620 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12621 return;
12622 };
12623 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12624 }
12625
12626 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12627 &self.inlay_hint_cache
12628 }
12629
12630 pub fn replay_insert_event(
12631 &mut self,
12632 text: &str,
12633 relative_utf16_range: Option<Range<isize>>,
12634 cx: &mut ViewContext<Self>,
12635 ) {
12636 if !self.input_enabled {
12637 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12638 return;
12639 }
12640 if let Some(relative_utf16_range) = relative_utf16_range {
12641 let selections = self.selections.all::<OffsetUtf16>(cx);
12642 self.change_selections(None, cx, |s| {
12643 let new_ranges = selections.into_iter().map(|range| {
12644 let start = OffsetUtf16(
12645 range
12646 .head()
12647 .0
12648 .saturating_add_signed(relative_utf16_range.start),
12649 );
12650 let end = OffsetUtf16(
12651 range
12652 .head()
12653 .0
12654 .saturating_add_signed(relative_utf16_range.end),
12655 );
12656 start..end
12657 });
12658 s.select_ranges(new_ranges);
12659 });
12660 }
12661
12662 self.handle_input(text, cx);
12663 }
12664
12665 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12666 let Some(provider) = self.semantics_provider.as_ref() else {
12667 return false;
12668 };
12669
12670 let mut supports = false;
12671 self.buffer().read(cx).for_each_buffer(|buffer| {
12672 supports |= provider.supports_inlay_hints(buffer, cx);
12673 });
12674 supports
12675 }
12676
12677 pub fn focus(&self, cx: &mut WindowContext) {
12678 cx.focus(&self.focus_handle)
12679 }
12680
12681 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12682 self.focus_handle.is_focused(cx)
12683 }
12684
12685 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12686 cx.emit(EditorEvent::Focused);
12687
12688 if let Some(descendant) = self
12689 .last_focused_descendant
12690 .take()
12691 .and_then(|descendant| descendant.upgrade())
12692 {
12693 cx.focus(&descendant);
12694 } else {
12695 if let Some(blame) = self.blame.as_ref() {
12696 blame.update(cx, GitBlame::focus)
12697 }
12698
12699 self.blink_manager.update(cx, BlinkManager::enable);
12700 self.show_cursor_names(cx);
12701 self.buffer.update(cx, |buffer, cx| {
12702 buffer.finalize_last_transaction(cx);
12703 if self.leader_peer_id.is_none() {
12704 buffer.set_active_selections(
12705 &self.selections.disjoint_anchors(),
12706 self.selections.line_mode,
12707 self.cursor_shape,
12708 cx,
12709 );
12710 }
12711 });
12712 }
12713 }
12714
12715 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12716 cx.emit(EditorEvent::FocusedIn)
12717 }
12718
12719 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12720 if event.blurred != self.focus_handle {
12721 self.last_focused_descendant = Some(event.blurred);
12722 }
12723 }
12724
12725 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12726 self.blink_manager.update(cx, BlinkManager::disable);
12727 self.buffer
12728 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12729
12730 if let Some(blame) = self.blame.as_ref() {
12731 blame.update(cx, GitBlame::blur)
12732 }
12733 if !self.hover_state.focused(cx) {
12734 hide_hover(self, cx);
12735 }
12736
12737 self.hide_context_menu(cx);
12738 cx.emit(EditorEvent::Blurred);
12739 cx.notify();
12740 }
12741
12742 pub fn register_action<A: Action>(
12743 &mut self,
12744 listener: impl Fn(&A, &mut WindowContext) + 'static,
12745 ) -> Subscription {
12746 let id = self.next_editor_action_id.post_inc();
12747 let listener = Arc::new(listener);
12748 self.editor_actions.borrow_mut().insert(
12749 id,
12750 Box::new(move |cx| {
12751 let cx = cx.window_context();
12752 let listener = listener.clone();
12753 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12754 let action = action.downcast_ref().unwrap();
12755 if phase == DispatchPhase::Bubble {
12756 listener(action, cx)
12757 }
12758 })
12759 }),
12760 );
12761
12762 let editor_actions = self.editor_actions.clone();
12763 Subscription::new(move || {
12764 editor_actions.borrow_mut().remove(&id);
12765 })
12766 }
12767
12768 pub fn file_header_size(&self) -> u32 {
12769 self.file_header_size
12770 }
12771
12772 pub fn revert(
12773 &mut self,
12774 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12775 cx: &mut ViewContext<Self>,
12776 ) {
12777 self.buffer().update(cx, |multi_buffer, cx| {
12778 for (buffer_id, changes) in revert_changes {
12779 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12780 buffer.update(cx, |buffer, cx| {
12781 buffer.edit(
12782 changes.into_iter().map(|(range, text)| {
12783 (range, text.to_string().map(Arc::<str>::from))
12784 }),
12785 None,
12786 cx,
12787 );
12788 });
12789 }
12790 }
12791 });
12792 self.change_selections(None, cx, |selections| selections.refresh());
12793 }
12794
12795 pub fn to_pixel_point(
12796 &mut self,
12797 source: multi_buffer::Anchor,
12798 editor_snapshot: &EditorSnapshot,
12799 cx: &mut ViewContext<Self>,
12800 ) -> Option<gpui::Point<Pixels>> {
12801 let source_point = source.to_display_point(editor_snapshot);
12802 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12803 }
12804
12805 pub fn display_to_pixel_point(
12806 &mut self,
12807 source: DisplayPoint,
12808 editor_snapshot: &EditorSnapshot,
12809 cx: &mut ViewContext<Self>,
12810 ) -> Option<gpui::Point<Pixels>> {
12811 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12812 let text_layout_details = self.text_layout_details(cx);
12813 let scroll_top = text_layout_details
12814 .scroll_anchor
12815 .scroll_position(editor_snapshot)
12816 .y;
12817
12818 if source.row().as_f32() < scroll_top.floor() {
12819 return None;
12820 }
12821 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12822 let source_y = line_height * (source.row().as_f32() - scroll_top);
12823 Some(gpui::Point::new(source_x, source_y))
12824 }
12825
12826 pub fn has_active_completions_menu(&self) -> bool {
12827 self.context_menu.read().as_ref().map_or(false, |menu| {
12828 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12829 })
12830 }
12831
12832 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12833 self.addons
12834 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12835 }
12836
12837 pub fn unregister_addon<T: Addon>(&mut self) {
12838 self.addons.remove(&std::any::TypeId::of::<T>());
12839 }
12840
12841 pub fn addon<T: Addon>(&self) -> Option<&T> {
12842 let type_id = std::any::TypeId::of::<T>();
12843 self.addons
12844 .get(&type_id)
12845 .and_then(|item| item.to_any().downcast_ref::<T>())
12846 }
12847}
12848
12849fn hunks_for_selections(
12850 multi_buffer_snapshot: &MultiBufferSnapshot,
12851 selections: &[Selection<Anchor>],
12852) -> Vec<MultiBufferDiffHunk> {
12853 let buffer_rows_for_selections = selections.iter().map(|selection| {
12854 let head = selection.head();
12855 let tail = selection.tail();
12856 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12857 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12858 if start > end {
12859 end..start
12860 } else {
12861 start..end
12862 }
12863 });
12864
12865 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12866}
12867
12868pub fn hunks_for_rows(
12869 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12870 multi_buffer_snapshot: &MultiBufferSnapshot,
12871) -> Vec<MultiBufferDiffHunk> {
12872 let mut hunks = Vec::new();
12873 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12874 HashMap::default();
12875 for selected_multi_buffer_rows in rows {
12876 let query_rows =
12877 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12878 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12879 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12880 // when the caret is just above or just below the deleted hunk.
12881 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12882 let related_to_selection = if allow_adjacent {
12883 hunk.row_range.overlaps(&query_rows)
12884 || hunk.row_range.start == query_rows.end
12885 || hunk.row_range.end == query_rows.start
12886 } else {
12887 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12888 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12889 hunk.row_range.overlaps(&selected_multi_buffer_rows)
12890 || selected_multi_buffer_rows.end == hunk.row_range.start
12891 };
12892 if related_to_selection {
12893 if !processed_buffer_rows
12894 .entry(hunk.buffer_id)
12895 .or_default()
12896 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12897 {
12898 continue;
12899 }
12900 hunks.push(hunk);
12901 }
12902 }
12903 }
12904
12905 hunks
12906}
12907
12908pub trait CollaborationHub {
12909 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12910 fn user_participant_indices<'a>(
12911 &self,
12912 cx: &'a AppContext,
12913 ) -> &'a HashMap<u64, ParticipantIndex>;
12914 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12915}
12916
12917impl CollaborationHub for Model<Project> {
12918 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12919 self.read(cx).collaborators()
12920 }
12921
12922 fn user_participant_indices<'a>(
12923 &self,
12924 cx: &'a AppContext,
12925 ) -> &'a HashMap<u64, ParticipantIndex> {
12926 self.read(cx).user_store().read(cx).participant_indices()
12927 }
12928
12929 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12930 let this = self.read(cx);
12931 let user_ids = this.collaborators().values().map(|c| c.user_id);
12932 this.user_store().read_with(cx, |user_store, cx| {
12933 user_store.participant_names(user_ids, cx)
12934 })
12935 }
12936}
12937
12938pub trait SemanticsProvider {
12939 fn hover(
12940 &self,
12941 buffer: &Model<Buffer>,
12942 position: text::Anchor,
12943 cx: &mut AppContext,
12944 ) -> Option<Task<Vec<project::Hover>>>;
12945
12946 fn inlay_hints(
12947 &self,
12948 buffer_handle: Model<Buffer>,
12949 range: Range<text::Anchor>,
12950 cx: &mut AppContext,
12951 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
12952
12953 fn resolve_inlay_hint(
12954 &self,
12955 hint: InlayHint,
12956 buffer_handle: Model<Buffer>,
12957 server_id: LanguageServerId,
12958 cx: &mut AppContext,
12959 ) -> Option<Task<anyhow::Result<InlayHint>>>;
12960
12961 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
12962
12963 fn document_highlights(
12964 &self,
12965 buffer: &Model<Buffer>,
12966 position: text::Anchor,
12967 cx: &mut AppContext,
12968 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
12969
12970 fn definitions(
12971 &self,
12972 buffer: &Model<Buffer>,
12973 position: text::Anchor,
12974 kind: GotoDefinitionKind,
12975 cx: &mut AppContext,
12976 ) -> Option<Task<Result<Vec<LocationLink>>>>;
12977
12978 fn range_for_rename(
12979 &self,
12980 buffer: &Model<Buffer>,
12981 position: text::Anchor,
12982 cx: &mut AppContext,
12983 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
12984
12985 fn perform_rename(
12986 &self,
12987 buffer: &Model<Buffer>,
12988 position: text::Anchor,
12989 new_name: String,
12990 cx: &mut AppContext,
12991 ) -> Option<Task<Result<ProjectTransaction>>>;
12992}
12993
12994pub trait CompletionProvider {
12995 fn completions(
12996 &self,
12997 buffer: &Model<Buffer>,
12998 buffer_position: text::Anchor,
12999 trigger: CompletionContext,
13000 cx: &mut ViewContext<Editor>,
13001 ) -> Task<Result<Vec<Completion>>>;
13002
13003 fn resolve_completions(
13004 &self,
13005 buffer: Model<Buffer>,
13006 completion_indices: Vec<usize>,
13007 completions: Arc<RwLock<Box<[Completion]>>>,
13008 cx: &mut ViewContext<Editor>,
13009 ) -> Task<Result<bool>>;
13010
13011 fn apply_additional_edits_for_completion(
13012 &self,
13013 buffer: Model<Buffer>,
13014 completion: Completion,
13015 push_to_history: bool,
13016 cx: &mut ViewContext<Editor>,
13017 ) -> Task<Result<Option<language::Transaction>>>;
13018
13019 fn is_completion_trigger(
13020 &self,
13021 buffer: &Model<Buffer>,
13022 position: language::Anchor,
13023 text: &str,
13024 trigger_in_words: bool,
13025 cx: &mut ViewContext<Editor>,
13026 ) -> bool;
13027
13028 fn sort_completions(&self) -> bool {
13029 true
13030 }
13031}
13032
13033pub trait CodeActionProvider {
13034 fn code_actions(
13035 &self,
13036 buffer: &Model<Buffer>,
13037 range: Range<text::Anchor>,
13038 cx: &mut WindowContext,
13039 ) -> Task<Result<Vec<CodeAction>>>;
13040
13041 fn apply_code_action(
13042 &self,
13043 buffer_handle: Model<Buffer>,
13044 action: CodeAction,
13045 excerpt_id: ExcerptId,
13046 push_to_history: bool,
13047 cx: &mut WindowContext,
13048 ) -> Task<Result<ProjectTransaction>>;
13049}
13050
13051impl CodeActionProvider for Model<Project> {
13052 fn code_actions(
13053 &self,
13054 buffer: &Model<Buffer>,
13055 range: Range<text::Anchor>,
13056 cx: &mut WindowContext,
13057 ) -> Task<Result<Vec<CodeAction>>> {
13058 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13059 }
13060
13061 fn apply_code_action(
13062 &self,
13063 buffer_handle: Model<Buffer>,
13064 action: CodeAction,
13065 _excerpt_id: ExcerptId,
13066 push_to_history: bool,
13067 cx: &mut WindowContext,
13068 ) -> Task<Result<ProjectTransaction>> {
13069 self.update(cx, |project, cx| {
13070 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13071 })
13072 }
13073}
13074
13075fn snippet_completions(
13076 project: &Project,
13077 buffer: &Model<Buffer>,
13078 buffer_position: text::Anchor,
13079 cx: &mut AppContext,
13080) -> Vec<Completion> {
13081 let language = buffer.read(cx).language_at(buffer_position);
13082 let language_name = language.as_ref().map(|language| language.lsp_id());
13083 let snippet_store = project.snippets().read(cx);
13084 let snippets = snippet_store.snippets_for(language_name, cx);
13085
13086 if snippets.is_empty() {
13087 return vec![];
13088 }
13089 let snapshot = buffer.read(cx).text_snapshot();
13090 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
13091
13092 let mut lines = chunks.lines();
13093 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
13094 return vec![];
13095 };
13096
13097 let scope = language.map(|language| language.default_scope());
13098 let classifier = CharClassifier::new(scope).for_completion(true);
13099 let mut last_word = line_at
13100 .chars()
13101 .rev()
13102 .take_while(|c| classifier.is_word(*c))
13103 .collect::<String>();
13104 last_word = last_word.chars().rev().collect();
13105 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13106 let to_lsp = |point: &text::Anchor| {
13107 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13108 point_to_lsp(end)
13109 };
13110 let lsp_end = to_lsp(&buffer_position);
13111 snippets
13112 .into_iter()
13113 .filter_map(|snippet| {
13114 let matching_prefix = snippet
13115 .prefix
13116 .iter()
13117 .find(|prefix| prefix.starts_with(&last_word))?;
13118 let start = as_offset - last_word.len();
13119 let start = snapshot.anchor_before(start);
13120 let range = start..buffer_position;
13121 let lsp_start = to_lsp(&start);
13122 let lsp_range = lsp::Range {
13123 start: lsp_start,
13124 end: lsp_end,
13125 };
13126 Some(Completion {
13127 old_range: range,
13128 new_text: snippet.body.clone(),
13129 label: CodeLabel {
13130 text: matching_prefix.clone(),
13131 runs: vec![],
13132 filter_range: 0..matching_prefix.len(),
13133 },
13134 server_id: LanguageServerId(usize::MAX),
13135 documentation: snippet.description.clone().map(Documentation::SingleLine),
13136 lsp_completion: lsp::CompletionItem {
13137 label: snippet.prefix.first().unwrap().clone(),
13138 kind: Some(CompletionItemKind::SNIPPET),
13139 label_details: snippet.description.as_ref().map(|description| {
13140 lsp::CompletionItemLabelDetails {
13141 detail: Some(description.clone()),
13142 description: None,
13143 }
13144 }),
13145 insert_text_format: Some(InsertTextFormat::SNIPPET),
13146 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13147 lsp::InsertReplaceEdit {
13148 new_text: snippet.body.clone(),
13149 insert: lsp_range,
13150 replace: lsp_range,
13151 },
13152 )),
13153 filter_text: Some(snippet.body.clone()),
13154 sort_text: Some(char::MAX.to_string()),
13155 ..Default::default()
13156 },
13157 confirm: None,
13158 })
13159 })
13160 .collect()
13161}
13162
13163impl CompletionProvider for Model<Project> {
13164 fn completions(
13165 &self,
13166 buffer: &Model<Buffer>,
13167 buffer_position: text::Anchor,
13168 options: CompletionContext,
13169 cx: &mut ViewContext<Editor>,
13170 ) -> Task<Result<Vec<Completion>>> {
13171 self.update(cx, |project, cx| {
13172 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13173 let project_completions = project.completions(buffer, buffer_position, options, cx);
13174 cx.background_executor().spawn(async move {
13175 let mut completions = project_completions.await?;
13176 //let snippets = snippets.into_iter().;
13177 completions.extend(snippets);
13178 Ok(completions)
13179 })
13180 })
13181 }
13182
13183 fn resolve_completions(
13184 &self,
13185 buffer: Model<Buffer>,
13186 completion_indices: Vec<usize>,
13187 completions: Arc<RwLock<Box<[Completion]>>>,
13188 cx: &mut ViewContext<Editor>,
13189 ) -> Task<Result<bool>> {
13190 self.update(cx, |project, cx| {
13191 project.resolve_completions(buffer, completion_indices, completions, cx)
13192 })
13193 }
13194
13195 fn apply_additional_edits_for_completion(
13196 &self,
13197 buffer: Model<Buffer>,
13198 completion: Completion,
13199 push_to_history: bool,
13200 cx: &mut ViewContext<Editor>,
13201 ) -> Task<Result<Option<language::Transaction>>> {
13202 self.update(cx, |project, cx| {
13203 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13204 })
13205 }
13206
13207 fn is_completion_trigger(
13208 &self,
13209 buffer: &Model<Buffer>,
13210 position: language::Anchor,
13211 text: &str,
13212 trigger_in_words: bool,
13213 cx: &mut ViewContext<Editor>,
13214 ) -> bool {
13215 if !EditorSettings::get_global(cx).show_completions_on_input {
13216 return false;
13217 }
13218
13219 let mut chars = text.chars();
13220 let char = if let Some(char) = chars.next() {
13221 char
13222 } else {
13223 return false;
13224 };
13225 if chars.next().is_some() {
13226 return false;
13227 }
13228
13229 let buffer = buffer.read(cx);
13230 let classifier = buffer
13231 .snapshot()
13232 .char_classifier_at(position)
13233 .for_completion(true);
13234 if trigger_in_words && classifier.is_word(char) {
13235 return true;
13236 }
13237
13238 buffer
13239 .completion_triggers()
13240 .iter()
13241 .any(|string| string == text)
13242 }
13243}
13244
13245impl SemanticsProvider for Model<Project> {
13246 fn hover(
13247 &self,
13248 buffer: &Model<Buffer>,
13249 position: text::Anchor,
13250 cx: &mut AppContext,
13251 ) -> Option<Task<Vec<project::Hover>>> {
13252 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13253 }
13254
13255 fn document_highlights(
13256 &self,
13257 buffer: &Model<Buffer>,
13258 position: text::Anchor,
13259 cx: &mut AppContext,
13260 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13261 Some(self.update(cx, |project, cx| {
13262 project.document_highlights(buffer, position, cx)
13263 }))
13264 }
13265
13266 fn definitions(
13267 &self,
13268 buffer: &Model<Buffer>,
13269 position: text::Anchor,
13270 kind: GotoDefinitionKind,
13271 cx: &mut AppContext,
13272 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13273 Some(self.update(cx, |project, cx| match kind {
13274 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13275 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13276 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13277 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13278 }))
13279 }
13280
13281 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13282 // TODO: make this work for remote projects
13283 self.read(cx)
13284 .language_servers_for_buffer(buffer.read(cx), cx)
13285 .any(
13286 |(_, server)| match server.capabilities().inlay_hint_provider {
13287 Some(lsp::OneOf::Left(enabled)) => enabled,
13288 Some(lsp::OneOf::Right(_)) => true,
13289 None => false,
13290 },
13291 )
13292 }
13293
13294 fn inlay_hints(
13295 &self,
13296 buffer_handle: Model<Buffer>,
13297 range: Range<text::Anchor>,
13298 cx: &mut AppContext,
13299 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13300 Some(self.update(cx, |project, cx| {
13301 project.inlay_hints(buffer_handle, range, cx)
13302 }))
13303 }
13304
13305 fn resolve_inlay_hint(
13306 &self,
13307 hint: InlayHint,
13308 buffer_handle: Model<Buffer>,
13309 server_id: LanguageServerId,
13310 cx: &mut AppContext,
13311 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13312 Some(self.update(cx, |project, cx| {
13313 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13314 }))
13315 }
13316
13317 fn range_for_rename(
13318 &self,
13319 buffer: &Model<Buffer>,
13320 position: text::Anchor,
13321 cx: &mut AppContext,
13322 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13323 Some(self.update(cx, |project, cx| {
13324 project.prepare_rename(buffer.clone(), position, cx)
13325 }))
13326 }
13327
13328 fn perform_rename(
13329 &self,
13330 buffer: &Model<Buffer>,
13331 position: text::Anchor,
13332 new_name: String,
13333 cx: &mut AppContext,
13334 ) -> Option<Task<Result<ProjectTransaction>>> {
13335 Some(self.update(cx, |project, cx| {
13336 project.perform_rename(buffer.clone(), position, new_name, cx)
13337 }))
13338 }
13339}
13340
13341fn inlay_hint_settings(
13342 location: Anchor,
13343 snapshot: &MultiBufferSnapshot,
13344 cx: &mut ViewContext<'_, Editor>,
13345) -> InlayHintSettings {
13346 let file = snapshot.file_at(location);
13347 let language = snapshot.language_at(location);
13348 let settings = all_language_settings(file, cx);
13349 settings
13350 .language(language.map(|l| l.name()).as_ref())
13351 .inlay_hints
13352}
13353
13354fn consume_contiguous_rows(
13355 contiguous_row_selections: &mut Vec<Selection<Point>>,
13356 selection: &Selection<Point>,
13357 display_map: &DisplaySnapshot,
13358 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13359) -> (MultiBufferRow, MultiBufferRow) {
13360 contiguous_row_selections.push(selection.clone());
13361 let start_row = MultiBufferRow(selection.start.row);
13362 let mut end_row = ending_row(selection, display_map);
13363
13364 while let Some(next_selection) = selections.peek() {
13365 if next_selection.start.row <= end_row.0 {
13366 end_row = ending_row(next_selection, display_map);
13367 contiguous_row_selections.push(selections.next().unwrap().clone());
13368 } else {
13369 break;
13370 }
13371 }
13372 (start_row, end_row)
13373}
13374
13375fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13376 if next_selection.end.column > 0 || next_selection.is_empty() {
13377 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13378 } else {
13379 MultiBufferRow(next_selection.end.row)
13380 }
13381}
13382
13383impl EditorSnapshot {
13384 pub fn remote_selections_in_range<'a>(
13385 &'a self,
13386 range: &'a Range<Anchor>,
13387 collaboration_hub: &dyn CollaborationHub,
13388 cx: &'a AppContext,
13389 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13390 let participant_names = collaboration_hub.user_names(cx);
13391 let participant_indices = collaboration_hub.user_participant_indices(cx);
13392 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13393 let collaborators_by_replica_id = collaborators_by_peer_id
13394 .iter()
13395 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13396 .collect::<HashMap<_, _>>();
13397 self.buffer_snapshot
13398 .selections_in_range(range, false)
13399 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13400 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13401 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13402 let user_name = participant_names.get(&collaborator.user_id).cloned();
13403 Some(RemoteSelection {
13404 replica_id,
13405 selection,
13406 cursor_shape,
13407 line_mode,
13408 participant_index,
13409 peer_id: collaborator.peer_id,
13410 user_name,
13411 })
13412 })
13413 }
13414
13415 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13416 self.display_snapshot.buffer_snapshot.language_at(position)
13417 }
13418
13419 pub fn is_focused(&self) -> bool {
13420 self.is_focused
13421 }
13422
13423 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13424 self.placeholder_text.as_ref()
13425 }
13426
13427 pub fn scroll_position(&self) -> gpui::Point<f32> {
13428 self.scroll_anchor.scroll_position(&self.display_snapshot)
13429 }
13430
13431 fn gutter_dimensions(
13432 &self,
13433 font_id: FontId,
13434 font_size: Pixels,
13435 em_width: Pixels,
13436 em_advance: Pixels,
13437 max_line_number_width: Pixels,
13438 cx: &AppContext,
13439 ) -> GutterDimensions {
13440 if !self.show_gutter {
13441 return GutterDimensions::default();
13442 }
13443 let descent = cx.text_system().descent(font_id, font_size);
13444
13445 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13446 matches!(
13447 ProjectSettings::get_global(cx).git.git_gutter,
13448 Some(GitGutterSetting::TrackedFiles)
13449 )
13450 });
13451 let gutter_settings = EditorSettings::get_global(cx).gutter;
13452 let show_line_numbers = self
13453 .show_line_numbers
13454 .unwrap_or(gutter_settings.line_numbers);
13455 let line_gutter_width = if show_line_numbers {
13456 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13457 let min_width_for_number_on_gutter = em_advance * 4.0;
13458 max_line_number_width.max(min_width_for_number_on_gutter)
13459 } else {
13460 0.0.into()
13461 };
13462
13463 let show_code_actions = self
13464 .show_code_actions
13465 .unwrap_or(gutter_settings.code_actions);
13466
13467 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13468
13469 let git_blame_entries_width =
13470 self.git_blame_gutter_max_author_length
13471 .map(|max_author_length| {
13472 // Length of the author name, but also space for the commit hash,
13473 // the spacing and the timestamp.
13474 let max_char_count = max_author_length
13475 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13476 + 7 // length of commit sha
13477 + 14 // length of max relative timestamp ("60 minutes ago")
13478 + 4; // gaps and margins
13479
13480 em_advance * max_char_count
13481 });
13482
13483 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13484 left_padding += if show_code_actions || show_runnables {
13485 em_width * 3.0
13486 } else if show_git_gutter && show_line_numbers {
13487 em_width * 2.0
13488 } else if show_git_gutter || show_line_numbers {
13489 em_width
13490 } else {
13491 px(0.)
13492 };
13493
13494 let right_padding = if gutter_settings.folds && show_line_numbers {
13495 em_width * 4.0
13496 } else if gutter_settings.folds {
13497 em_width * 3.0
13498 } else if show_line_numbers {
13499 em_width
13500 } else {
13501 px(0.)
13502 };
13503
13504 GutterDimensions {
13505 left_padding,
13506 right_padding,
13507 width: line_gutter_width + left_padding + right_padding,
13508 margin: -descent,
13509 git_blame_entries_width,
13510 }
13511 }
13512
13513 pub fn render_fold_toggle(
13514 &self,
13515 buffer_row: MultiBufferRow,
13516 row_contains_cursor: bool,
13517 editor: View<Editor>,
13518 cx: &mut WindowContext,
13519 ) -> Option<AnyElement> {
13520 let folded = self.is_line_folded(buffer_row);
13521
13522 if let Some(crease) = self
13523 .crease_snapshot
13524 .query_row(buffer_row, &self.buffer_snapshot)
13525 {
13526 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13527 if folded {
13528 editor.update(cx, |editor, cx| {
13529 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13530 });
13531 } else {
13532 editor.update(cx, |editor, cx| {
13533 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13534 });
13535 }
13536 });
13537
13538 Some((crease.render_toggle)(
13539 buffer_row,
13540 folded,
13541 toggle_callback,
13542 cx,
13543 ))
13544 } else if folded
13545 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13546 {
13547 Some(
13548 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13549 .selected(folded)
13550 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13551 if folded {
13552 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13553 } else {
13554 this.fold_at(&FoldAt { buffer_row }, cx);
13555 }
13556 }))
13557 .into_any_element(),
13558 )
13559 } else {
13560 None
13561 }
13562 }
13563
13564 pub fn render_crease_trailer(
13565 &self,
13566 buffer_row: MultiBufferRow,
13567 cx: &mut WindowContext,
13568 ) -> Option<AnyElement> {
13569 let folded = self.is_line_folded(buffer_row);
13570 let crease = self
13571 .crease_snapshot
13572 .query_row(buffer_row, &self.buffer_snapshot)?;
13573 Some((crease.render_trailer)(buffer_row, folded, cx))
13574 }
13575}
13576
13577impl Deref for EditorSnapshot {
13578 type Target = DisplaySnapshot;
13579
13580 fn deref(&self) -> &Self::Target {
13581 &self.display_snapshot
13582 }
13583}
13584
13585#[derive(Clone, Debug, PartialEq, Eq)]
13586pub enum EditorEvent {
13587 InputIgnored {
13588 text: Arc<str>,
13589 },
13590 InputHandled {
13591 utf16_range_to_replace: Option<Range<isize>>,
13592 text: Arc<str>,
13593 },
13594 ExcerptsAdded {
13595 buffer: Model<Buffer>,
13596 predecessor: ExcerptId,
13597 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13598 },
13599 ExcerptsRemoved {
13600 ids: Vec<ExcerptId>,
13601 },
13602 ExcerptsEdited {
13603 ids: Vec<ExcerptId>,
13604 },
13605 ExcerptsExpanded {
13606 ids: Vec<ExcerptId>,
13607 },
13608 BufferEdited,
13609 Edited {
13610 transaction_id: clock::Lamport,
13611 },
13612 Reparsed(BufferId),
13613 Focused,
13614 FocusedIn,
13615 Blurred,
13616 DirtyChanged,
13617 Saved,
13618 TitleChanged,
13619 DiffBaseChanged,
13620 SelectionsChanged {
13621 local: bool,
13622 },
13623 ScrollPositionChanged {
13624 local: bool,
13625 autoscroll: bool,
13626 },
13627 Closed,
13628 TransactionUndone {
13629 transaction_id: clock::Lamport,
13630 },
13631 TransactionBegun {
13632 transaction_id: clock::Lamport,
13633 },
13634 CursorShapeChanged,
13635}
13636
13637impl EventEmitter<EditorEvent> for Editor {}
13638
13639impl FocusableView for Editor {
13640 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13641 self.focus_handle.clone()
13642 }
13643}
13644
13645impl Render for Editor {
13646 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13647 let settings = ThemeSettings::get_global(cx);
13648
13649 let text_style = match self.mode {
13650 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13651 color: cx.theme().colors().editor_foreground,
13652 font_family: settings.ui_font.family.clone(),
13653 font_features: settings.ui_font.features.clone(),
13654 font_fallbacks: settings.ui_font.fallbacks.clone(),
13655 font_size: rems(0.875).into(),
13656 font_weight: settings.ui_font.weight,
13657 line_height: relative(settings.buffer_line_height.value()),
13658 ..Default::default()
13659 },
13660 EditorMode::Full => TextStyle {
13661 color: cx.theme().colors().editor_foreground,
13662 font_family: settings.buffer_font.family.clone(),
13663 font_features: settings.buffer_font.features.clone(),
13664 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13665 font_size: settings.buffer_font_size(cx).into(),
13666 font_weight: settings.buffer_font.weight,
13667 line_height: relative(settings.buffer_line_height.value()),
13668 ..Default::default()
13669 },
13670 };
13671
13672 let background = match self.mode {
13673 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13674 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13675 EditorMode::Full => cx.theme().colors().editor_background,
13676 };
13677
13678 EditorElement::new(
13679 cx.view(),
13680 EditorStyle {
13681 background,
13682 local_player: cx.theme().players().local(),
13683 text: text_style,
13684 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13685 syntax: cx.theme().syntax().clone(),
13686 status: cx.theme().status().clone(),
13687 inlay_hints_style: make_inlay_hints_style(cx),
13688 suggestions_style: HighlightStyle {
13689 color: Some(cx.theme().status().predictive),
13690 ..HighlightStyle::default()
13691 },
13692 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13693 },
13694 )
13695 }
13696}
13697
13698impl ViewInputHandler for Editor {
13699 fn text_for_range(
13700 &mut self,
13701 range_utf16: Range<usize>,
13702 cx: &mut ViewContext<Self>,
13703 ) -> Option<String> {
13704 Some(
13705 self.buffer
13706 .read(cx)
13707 .read(cx)
13708 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13709 .collect(),
13710 )
13711 }
13712
13713 fn selected_text_range(
13714 &mut self,
13715 ignore_disabled_input: bool,
13716 cx: &mut ViewContext<Self>,
13717 ) -> Option<UTF16Selection> {
13718 // Prevent the IME menu from appearing when holding down an alphabetic key
13719 // while input is disabled.
13720 if !ignore_disabled_input && !self.input_enabled {
13721 return None;
13722 }
13723
13724 let selection = self.selections.newest::<OffsetUtf16>(cx);
13725 let range = selection.range();
13726
13727 Some(UTF16Selection {
13728 range: range.start.0..range.end.0,
13729 reversed: selection.reversed,
13730 })
13731 }
13732
13733 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13734 let snapshot = self.buffer.read(cx).read(cx);
13735 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13736 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13737 }
13738
13739 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13740 self.clear_highlights::<InputComposition>(cx);
13741 self.ime_transaction.take();
13742 }
13743
13744 fn replace_text_in_range(
13745 &mut self,
13746 range_utf16: Option<Range<usize>>,
13747 text: &str,
13748 cx: &mut ViewContext<Self>,
13749 ) {
13750 if !self.input_enabled {
13751 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13752 return;
13753 }
13754
13755 self.transact(cx, |this, cx| {
13756 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13757 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13758 Some(this.selection_replacement_ranges(range_utf16, cx))
13759 } else {
13760 this.marked_text_ranges(cx)
13761 };
13762
13763 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13764 let newest_selection_id = this.selections.newest_anchor().id;
13765 this.selections
13766 .all::<OffsetUtf16>(cx)
13767 .iter()
13768 .zip(ranges_to_replace.iter())
13769 .find_map(|(selection, range)| {
13770 if selection.id == newest_selection_id {
13771 Some(
13772 (range.start.0 as isize - selection.head().0 as isize)
13773 ..(range.end.0 as isize - selection.head().0 as isize),
13774 )
13775 } else {
13776 None
13777 }
13778 })
13779 });
13780
13781 cx.emit(EditorEvent::InputHandled {
13782 utf16_range_to_replace: range_to_replace,
13783 text: text.into(),
13784 });
13785
13786 if let Some(new_selected_ranges) = new_selected_ranges {
13787 this.change_selections(None, cx, |selections| {
13788 selections.select_ranges(new_selected_ranges)
13789 });
13790 this.backspace(&Default::default(), cx);
13791 }
13792
13793 this.handle_input(text, cx);
13794 });
13795
13796 if let Some(transaction) = self.ime_transaction {
13797 self.buffer.update(cx, |buffer, cx| {
13798 buffer.group_until_transaction(transaction, cx);
13799 });
13800 }
13801
13802 self.unmark_text(cx);
13803 }
13804
13805 fn replace_and_mark_text_in_range(
13806 &mut self,
13807 range_utf16: Option<Range<usize>>,
13808 text: &str,
13809 new_selected_range_utf16: Option<Range<usize>>,
13810 cx: &mut ViewContext<Self>,
13811 ) {
13812 if !self.input_enabled {
13813 return;
13814 }
13815
13816 let transaction = self.transact(cx, |this, cx| {
13817 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13818 let snapshot = this.buffer.read(cx).read(cx);
13819 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13820 for marked_range in &mut marked_ranges {
13821 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13822 marked_range.start.0 += relative_range_utf16.start;
13823 marked_range.start =
13824 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13825 marked_range.end =
13826 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13827 }
13828 }
13829 Some(marked_ranges)
13830 } else if let Some(range_utf16) = range_utf16 {
13831 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13832 Some(this.selection_replacement_ranges(range_utf16, cx))
13833 } else {
13834 None
13835 };
13836
13837 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13838 let newest_selection_id = this.selections.newest_anchor().id;
13839 this.selections
13840 .all::<OffsetUtf16>(cx)
13841 .iter()
13842 .zip(ranges_to_replace.iter())
13843 .find_map(|(selection, range)| {
13844 if selection.id == newest_selection_id {
13845 Some(
13846 (range.start.0 as isize - selection.head().0 as isize)
13847 ..(range.end.0 as isize - selection.head().0 as isize),
13848 )
13849 } else {
13850 None
13851 }
13852 })
13853 });
13854
13855 cx.emit(EditorEvent::InputHandled {
13856 utf16_range_to_replace: range_to_replace,
13857 text: text.into(),
13858 });
13859
13860 if let Some(ranges) = ranges_to_replace {
13861 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13862 }
13863
13864 let marked_ranges = {
13865 let snapshot = this.buffer.read(cx).read(cx);
13866 this.selections
13867 .disjoint_anchors()
13868 .iter()
13869 .map(|selection| {
13870 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13871 })
13872 .collect::<Vec<_>>()
13873 };
13874
13875 if text.is_empty() {
13876 this.unmark_text(cx);
13877 } else {
13878 this.highlight_text::<InputComposition>(
13879 marked_ranges.clone(),
13880 HighlightStyle {
13881 underline: Some(UnderlineStyle {
13882 thickness: px(1.),
13883 color: None,
13884 wavy: false,
13885 }),
13886 ..Default::default()
13887 },
13888 cx,
13889 );
13890 }
13891
13892 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13893 let use_autoclose = this.use_autoclose;
13894 let use_auto_surround = this.use_auto_surround;
13895 this.set_use_autoclose(false);
13896 this.set_use_auto_surround(false);
13897 this.handle_input(text, cx);
13898 this.set_use_autoclose(use_autoclose);
13899 this.set_use_auto_surround(use_auto_surround);
13900
13901 if let Some(new_selected_range) = new_selected_range_utf16 {
13902 let snapshot = this.buffer.read(cx).read(cx);
13903 let new_selected_ranges = marked_ranges
13904 .into_iter()
13905 .map(|marked_range| {
13906 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13907 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13908 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13909 snapshot.clip_offset_utf16(new_start, Bias::Left)
13910 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13911 })
13912 .collect::<Vec<_>>();
13913
13914 drop(snapshot);
13915 this.change_selections(None, cx, |selections| {
13916 selections.select_ranges(new_selected_ranges)
13917 });
13918 }
13919 });
13920
13921 self.ime_transaction = self.ime_transaction.or(transaction);
13922 if let Some(transaction) = self.ime_transaction {
13923 self.buffer.update(cx, |buffer, cx| {
13924 buffer.group_until_transaction(transaction, cx);
13925 });
13926 }
13927
13928 if self.text_highlights::<InputComposition>(cx).is_none() {
13929 self.ime_transaction.take();
13930 }
13931 }
13932
13933 fn bounds_for_range(
13934 &mut self,
13935 range_utf16: Range<usize>,
13936 element_bounds: gpui::Bounds<Pixels>,
13937 cx: &mut ViewContext<Self>,
13938 ) -> Option<gpui::Bounds<Pixels>> {
13939 let text_layout_details = self.text_layout_details(cx);
13940 let style = &text_layout_details.editor_style;
13941 let font_id = cx.text_system().resolve_font(&style.text.font());
13942 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13943 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13944
13945 let em_width = cx
13946 .text_system()
13947 .typographic_bounds(font_id, font_size, 'm')
13948 .unwrap()
13949 .size
13950 .width;
13951
13952 let snapshot = self.snapshot(cx);
13953 let scroll_position = snapshot.scroll_position();
13954 let scroll_left = scroll_position.x * em_width;
13955
13956 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13957 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13958 + self.gutter_dimensions.width;
13959 let y = line_height * (start.row().as_f32() - scroll_position.y);
13960
13961 Some(Bounds {
13962 origin: element_bounds.origin + point(x, y),
13963 size: size(em_width, line_height),
13964 })
13965 }
13966}
13967
13968trait SelectionExt {
13969 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13970 fn spanned_rows(
13971 &self,
13972 include_end_if_at_line_start: bool,
13973 map: &DisplaySnapshot,
13974 ) -> Range<MultiBufferRow>;
13975}
13976
13977impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13978 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13979 let start = self
13980 .start
13981 .to_point(&map.buffer_snapshot)
13982 .to_display_point(map);
13983 let end = self
13984 .end
13985 .to_point(&map.buffer_snapshot)
13986 .to_display_point(map);
13987 if self.reversed {
13988 end..start
13989 } else {
13990 start..end
13991 }
13992 }
13993
13994 fn spanned_rows(
13995 &self,
13996 include_end_if_at_line_start: bool,
13997 map: &DisplaySnapshot,
13998 ) -> Range<MultiBufferRow> {
13999 let start = self.start.to_point(&map.buffer_snapshot);
14000 let mut end = self.end.to_point(&map.buffer_snapshot);
14001 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14002 end.row -= 1;
14003 }
14004
14005 let buffer_start = map.prev_line_boundary(start).0;
14006 let buffer_end = map.next_line_boundary(end).0;
14007 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14008 }
14009}
14010
14011impl<T: InvalidationRegion> InvalidationStack<T> {
14012 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14013 where
14014 S: Clone + ToOffset,
14015 {
14016 while let Some(region) = self.last() {
14017 let all_selections_inside_invalidation_ranges =
14018 if selections.len() == region.ranges().len() {
14019 selections
14020 .iter()
14021 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14022 .all(|(selection, invalidation_range)| {
14023 let head = selection.head().to_offset(buffer);
14024 invalidation_range.start <= head && invalidation_range.end >= head
14025 })
14026 } else {
14027 false
14028 };
14029
14030 if all_selections_inside_invalidation_ranges {
14031 break;
14032 } else {
14033 self.pop();
14034 }
14035 }
14036 }
14037}
14038
14039impl<T> Default for InvalidationStack<T> {
14040 fn default() -> Self {
14041 Self(Default::default())
14042 }
14043}
14044
14045impl<T> Deref for InvalidationStack<T> {
14046 type Target = Vec<T>;
14047
14048 fn deref(&self) -> &Self::Target {
14049 &self.0
14050 }
14051}
14052
14053impl<T> DerefMut for InvalidationStack<T> {
14054 fn deref_mut(&mut self) -> &mut Self::Target {
14055 &mut self.0
14056 }
14057}
14058
14059impl InvalidationRegion for SnippetState {
14060 fn ranges(&self) -> &[Range<Anchor>] {
14061 &self.ranges[self.active_index]
14062 }
14063}
14064
14065pub fn diagnostic_block_renderer(
14066 diagnostic: Diagnostic,
14067 max_message_rows: Option<u8>,
14068 allow_closing: bool,
14069 _is_valid: bool,
14070) -> RenderBlock {
14071 let (text_without_backticks, code_ranges) =
14072 highlight_diagnostic_message(&diagnostic, max_message_rows);
14073
14074 Box::new(move |cx: &mut BlockContext| {
14075 let group_id: SharedString = cx.block_id.to_string().into();
14076
14077 let mut text_style = cx.text_style().clone();
14078 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14079 let theme_settings = ThemeSettings::get_global(cx);
14080 text_style.font_family = theme_settings.buffer_font.family.clone();
14081 text_style.font_style = theme_settings.buffer_font.style;
14082 text_style.font_features = theme_settings.buffer_font.features.clone();
14083 text_style.font_weight = theme_settings.buffer_font.weight;
14084
14085 let multi_line_diagnostic = diagnostic.message.contains('\n');
14086
14087 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
14088 if multi_line_diagnostic {
14089 v_flex()
14090 } else {
14091 h_flex()
14092 }
14093 .when(allow_closing, |div| {
14094 div.children(diagnostic.is_primary.then(|| {
14095 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
14096 .icon_color(Color::Muted)
14097 .size(ButtonSize::Compact)
14098 .style(ButtonStyle::Transparent)
14099 .visible_on_hover(group_id.clone())
14100 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14101 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14102 }))
14103 })
14104 .child(
14105 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
14106 .icon_color(Color::Muted)
14107 .size(ButtonSize::Compact)
14108 .style(ButtonStyle::Transparent)
14109 .visible_on_hover(group_id.clone())
14110 .on_click({
14111 let message = diagnostic.message.clone();
14112 move |_click, cx| {
14113 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14114 }
14115 })
14116 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14117 )
14118 };
14119
14120 let icon_size = buttons(&diagnostic, cx.block_id)
14121 .into_any_element()
14122 .layout_as_root(AvailableSpace::min_size(), cx);
14123
14124 h_flex()
14125 .id(cx.block_id)
14126 .group(group_id.clone())
14127 .relative()
14128 .size_full()
14129 .pl(cx.gutter_dimensions.width)
14130 .w(cx.max_width + cx.gutter_dimensions.width)
14131 .child(
14132 div()
14133 .flex()
14134 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14135 .flex_shrink(),
14136 )
14137 .child(buttons(&diagnostic, cx.block_id))
14138 .child(div().flex().flex_shrink_0().child(
14139 StyledText::new(text_without_backticks.clone()).with_highlights(
14140 &text_style,
14141 code_ranges.iter().map(|range| {
14142 (
14143 range.clone(),
14144 HighlightStyle {
14145 font_weight: Some(FontWeight::BOLD),
14146 ..Default::default()
14147 },
14148 )
14149 }),
14150 ),
14151 ))
14152 .into_any_element()
14153 })
14154}
14155
14156pub fn highlight_diagnostic_message(
14157 diagnostic: &Diagnostic,
14158 mut max_message_rows: Option<u8>,
14159) -> (SharedString, Vec<Range<usize>>) {
14160 let mut text_without_backticks = String::new();
14161 let mut code_ranges = Vec::new();
14162
14163 if let Some(source) = &diagnostic.source {
14164 text_without_backticks.push_str(source);
14165 code_ranges.push(0..source.len());
14166 text_without_backticks.push_str(": ");
14167 }
14168
14169 let mut prev_offset = 0;
14170 let mut in_code_block = false;
14171 let has_row_limit = max_message_rows.is_some();
14172 let mut newline_indices = diagnostic
14173 .message
14174 .match_indices('\n')
14175 .filter(|_| has_row_limit)
14176 .map(|(ix, _)| ix)
14177 .fuse()
14178 .peekable();
14179
14180 for (quote_ix, _) in diagnostic
14181 .message
14182 .match_indices('`')
14183 .chain([(diagnostic.message.len(), "")])
14184 {
14185 let mut first_newline_ix = None;
14186 let mut last_newline_ix = None;
14187 while let Some(newline_ix) = newline_indices.peek() {
14188 if *newline_ix < quote_ix {
14189 if first_newline_ix.is_none() {
14190 first_newline_ix = Some(*newline_ix);
14191 }
14192 last_newline_ix = Some(*newline_ix);
14193
14194 if let Some(rows_left) = &mut max_message_rows {
14195 if *rows_left == 0 {
14196 break;
14197 } else {
14198 *rows_left -= 1;
14199 }
14200 }
14201 let _ = newline_indices.next();
14202 } else {
14203 break;
14204 }
14205 }
14206 let prev_len = text_without_backticks.len();
14207 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14208 text_without_backticks.push_str(new_text);
14209 if in_code_block {
14210 code_ranges.push(prev_len..text_without_backticks.len());
14211 }
14212 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14213 in_code_block = !in_code_block;
14214 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14215 text_without_backticks.push_str("...");
14216 break;
14217 }
14218 }
14219
14220 (text_without_backticks.into(), code_ranges)
14221}
14222
14223fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14224 match severity {
14225 DiagnosticSeverity::ERROR => colors.error,
14226 DiagnosticSeverity::WARNING => colors.warning,
14227 DiagnosticSeverity::INFORMATION => colors.info,
14228 DiagnosticSeverity::HINT => colors.info,
14229 _ => colors.ignored,
14230 }
14231}
14232
14233pub fn styled_runs_for_code_label<'a>(
14234 label: &'a CodeLabel,
14235 syntax_theme: &'a theme::SyntaxTheme,
14236) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14237 let fade_out = HighlightStyle {
14238 fade_out: Some(0.35),
14239 ..Default::default()
14240 };
14241
14242 let mut prev_end = label.filter_range.end;
14243 label
14244 .runs
14245 .iter()
14246 .enumerate()
14247 .flat_map(move |(ix, (range, highlight_id))| {
14248 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14249 style
14250 } else {
14251 return Default::default();
14252 };
14253 let mut muted_style = style;
14254 muted_style.highlight(fade_out);
14255
14256 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14257 if range.start >= label.filter_range.end {
14258 if range.start > prev_end {
14259 runs.push((prev_end..range.start, fade_out));
14260 }
14261 runs.push((range.clone(), muted_style));
14262 } else if range.end <= label.filter_range.end {
14263 runs.push((range.clone(), style));
14264 } else {
14265 runs.push((range.start..label.filter_range.end, style));
14266 runs.push((label.filter_range.end..range.end, muted_style));
14267 }
14268 prev_end = cmp::max(prev_end, range.end);
14269
14270 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14271 runs.push((prev_end..label.text.len(), fade_out));
14272 }
14273
14274 runs
14275 })
14276}
14277
14278pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14279 let mut prev_index = 0;
14280 let mut prev_codepoint: Option<char> = None;
14281 text.char_indices()
14282 .chain([(text.len(), '\0')])
14283 .filter_map(move |(index, codepoint)| {
14284 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14285 let is_boundary = index == text.len()
14286 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14287 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14288 if is_boundary {
14289 let chunk = &text[prev_index..index];
14290 prev_index = index;
14291 Some(chunk)
14292 } else {
14293 None
14294 }
14295 })
14296}
14297
14298pub trait RangeToAnchorExt: Sized {
14299 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14300
14301 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14302 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14303 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14304 }
14305}
14306
14307impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14308 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14309 let start_offset = self.start.to_offset(snapshot);
14310 let end_offset = self.end.to_offset(snapshot);
14311 if start_offset == end_offset {
14312 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14313 } else {
14314 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14315 }
14316 }
14317}
14318
14319pub trait RowExt {
14320 fn as_f32(&self) -> f32;
14321
14322 fn next_row(&self) -> Self;
14323
14324 fn previous_row(&self) -> Self;
14325
14326 fn minus(&self, other: Self) -> u32;
14327}
14328
14329impl RowExt for DisplayRow {
14330 fn as_f32(&self) -> f32 {
14331 self.0 as f32
14332 }
14333
14334 fn next_row(&self) -> Self {
14335 Self(self.0 + 1)
14336 }
14337
14338 fn previous_row(&self) -> Self {
14339 Self(self.0.saturating_sub(1))
14340 }
14341
14342 fn minus(&self, other: Self) -> u32 {
14343 self.0 - other.0
14344 }
14345}
14346
14347impl RowExt for MultiBufferRow {
14348 fn as_f32(&self) -> f32 {
14349 self.0 as f32
14350 }
14351
14352 fn next_row(&self) -> Self {
14353 Self(self.0 + 1)
14354 }
14355
14356 fn previous_row(&self) -> Self {
14357 Self(self.0.saturating_sub(1))
14358 }
14359
14360 fn minus(&self, other: Self) -> u32 {
14361 self.0 - other.0
14362 }
14363}
14364
14365trait RowRangeExt {
14366 type Row;
14367
14368 fn len(&self) -> usize;
14369
14370 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14371}
14372
14373impl RowRangeExt for Range<MultiBufferRow> {
14374 type Row = MultiBufferRow;
14375
14376 fn len(&self) -> usize {
14377 (self.end.0 - self.start.0) as usize
14378 }
14379
14380 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14381 (self.start.0..self.end.0).map(MultiBufferRow)
14382 }
14383}
14384
14385impl RowRangeExt for Range<DisplayRow> {
14386 type Row = DisplayRow;
14387
14388 fn len(&self) -> usize {
14389 (self.end.0 - self.start.0) as usize
14390 }
14391
14392 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14393 (self.start.0..self.end.0).map(DisplayRow)
14394 }
14395}
14396
14397fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14398 if hunk.diff_base_byte_range.is_empty() {
14399 DiffHunkStatus::Added
14400 } else if hunk.row_range.is_empty() {
14401 DiffHunkStatus::Removed
14402 } else {
14403 DiffHunkStatus::Modified
14404 }
14405}
14406
14407/// If select range has more than one line, we
14408/// just point the cursor to range.start.
14409fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14410 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14411 range
14412 } else {
14413 range.start..range.start
14414 }
14415}