1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31mod inline_completion_provider;
32pub mod items;
33mod linked_editing_ranges;
34mod lsp_ext;
35mod mouse_context_menu;
36pub mod movement;
37mod persistence;
38mod proposed_changes_editor;
39mod rust_analyzer_ext;
40pub mod scroll;
41mod selections_collection;
42pub mod tasks;
43
44#[cfg(test)]
45mod editor_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50use ::git::diff::DiffHunkStatus;
51pub(crate) use actions::*;
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use client::{Collaborator, ParticipantIndex};
56use clock::ReplicaId;
57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
58use convert_case::{Case, Casing};
59use debounced_delay::DebouncedDelay;
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
64};
65pub use editor_settings_controls::*;
66use element::LineWithInvisibles;
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::{future, FutureExt};
71use fuzzy::{StringMatch, StringMatchCandidate};
72use git::blame::GitBlame;
73use gpui::{
74 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
75 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
76 ClipboardItem, Context, DispatchPhase, ElementId, EventEmitter, FocusHandle, FocusOutEvent,
77 FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText, KeyContext,
78 ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render, SharedString,
79 Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle, UTF16Selection,
80 UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler, VisualContext,
81 WeakFocusHandle, WeakView, WindowContext,
82};
83use highlight_matching_bracket::refresh_matching_bracket_highlights;
84use hover_popover::{hide_hover, HoverState};
85pub(crate) use hunk_diff::HoveredHunk;
86use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
87use indent_guides::ActiveIndentGuidesState;
88use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
89pub use inline_completion_provider::*;
90pub use items::MAX_TAB_TITLE_LEN;
91use itertools::Itertools;
92use language::{
93 language_settings::{self, all_language_settings, language_settings, InlayHintSettings},
94 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
95 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
96 Point, Selection, SelectionGoal, TransactionId,
97};
98use language::{
99 point_to_lsp, BufferRow, CharClassifier, LanguageServerName, Runnable, RunnableRange,
100};
101use linked_editing_ranges::refresh_linked_ranges;
102pub use proposed_changes_editor::{
103 ProposedChangeLocation, ProposedChangesEditor, ProposedChangesEditorToolbar,
104};
105use similar::{ChangeTag, TextDiff};
106use task::{ResolvedTask, TaskTemplate, TaskVariables};
107
108use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
109pub use lsp::CompletionContext;
110use lsp::{
111 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
112 LanguageServerId,
113};
114use mouse_context_menu::MouseContextMenu;
115use movement::TextLayoutDetails;
116pub use multi_buffer::{
117 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
118 ToPoint,
119};
120use multi_buffer::{
121 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
122};
123use ordered_float::OrderedFloat;
124use parking_lot::{Mutex, RwLock};
125use project::{
126 lsp_store::{FormatTarget, FormatTrigger},
127 project_settings::{GitGutterSetting, ProjectSettings},
128 CodeAction, Completion, CompletionIntent, DocumentHighlight, InlayHint, Item, Location,
129 LocationLink, Project, ProjectPath, ProjectTransaction, TaskSourceKind,
130};
131use rand::prelude::*;
132use rpc::{proto::*, ErrorExt};
133use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
134use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
135use serde::{Deserialize, Serialize};
136use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
137use smallvec::SmallVec;
138use snippet::Snippet;
139use std::{
140 any::TypeId,
141 borrow::Cow,
142 cell::RefCell,
143 cmp::{self, Ordering, Reverse},
144 mem,
145 num::NonZeroU32,
146 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
147 path::{Path, PathBuf},
148 rc::Rc,
149 sync::Arc,
150 time::{Duration, Instant},
151};
152pub use sum_tree::Bias;
153use sum_tree::TreeMap;
154use text::{BufferId, OffsetUtf16, Rope};
155use theme::{
156 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
157 ThemeColors, ThemeSettings,
158};
159use ui::{
160 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
161 ListItem, Popover, PopoverMenuHandle, Tooltip,
162};
163use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
164use workspace::item::{ItemHandle, PreviewTabsSettings};
165use workspace::notifications::{DetachAndPromptErr, NotificationId, NotifyTaskExt};
166use workspace::{
167 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
168};
169use workspace::{Item as WorkspaceItem, OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
170
171use crate::hover_links::find_url;
172use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
173
174pub const FILE_HEADER_HEIGHT: u32 = 2;
175pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
176pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
177pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
178const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
179const MAX_LINE_LEN: usize = 1024;
180const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
181const MAX_SELECTION_HISTORY_LEN: usize = 1024;
182pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
183#[doc(hidden)]
184pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
185#[doc(hidden)]
186pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
187
188pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
189pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
190
191pub fn render_parsed_markdown(
192 element_id: impl Into<ElementId>,
193 parsed: &language::ParsedMarkdown,
194 editor_style: &EditorStyle,
195 workspace: Option<WeakView<Workspace>>,
196 cx: &mut WindowContext,
197) -> InteractiveText {
198 let code_span_background_color = cx
199 .theme()
200 .colors()
201 .editor_document_highlight_read_background;
202
203 let highlights = gpui::combine_highlights(
204 parsed.highlights.iter().filter_map(|(range, highlight)| {
205 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
206 Some((range.clone(), highlight))
207 }),
208 parsed
209 .regions
210 .iter()
211 .zip(&parsed.region_ranges)
212 .filter_map(|(region, range)| {
213 if region.code {
214 Some((
215 range.clone(),
216 HighlightStyle {
217 background_color: Some(code_span_background_color),
218 ..Default::default()
219 },
220 ))
221 } else {
222 None
223 }
224 }),
225 );
226
227 let mut links = Vec::new();
228 let mut link_ranges = Vec::new();
229 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
230 if let Some(link) = region.link.clone() {
231 links.push(link);
232 link_ranges.push(range.clone());
233 }
234 }
235
236 InteractiveText::new(
237 element_id,
238 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
239 )
240 .on_click(link_ranges, move |clicked_range_ix, cx| {
241 match &links[clicked_range_ix] {
242 markdown::Link::Web { url } => cx.open_url(url),
243 markdown::Link::Path { path } => {
244 if let Some(workspace) = &workspace {
245 _ = workspace.update(cx, |workspace, cx| {
246 workspace.open_abs_path(path.clone(), false, cx).detach();
247 });
248 }
249 }
250 }
251 })
252}
253
254#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
255pub(crate) enum InlayId {
256 Suggestion(usize),
257 Hint(usize),
258}
259
260impl InlayId {
261 fn id(&self) -> usize {
262 match self {
263 Self::Suggestion(id) => *id,
264 Self::Hint(id) => *id,
265 }
266 }
267}
268
269enum DiffRowHighlight {}
270enum DocumentHighlightRead {}
271enum DocumentHighlightWrite {}
272enum InputComposition {}
273
274#[derive(Copy, Clone, PartialEq, Eq)]
275pub enum Direction {
276 Prev,
277 Next,
278}
279
280#[derive(Debug, Copy, Clone, PartialEq, Eq)]
281pub enum Navigated {
282 Yes,
283 No,
284}
285
286impl Navigated {
287 pub fn from_bool(yes: bool) -> Navigated {
288 if yes {
289 Navigated::Yes
290 } else {
291 Navigated::No
292 }
293 }
294}
295
296pub fn init_settings(cx: &mut AppContext) {
297 EditorSettings::register(cx);
298}
299
300pub fn init(cx: &mut AppContext) {
301 init_settings(cx);
302
303 workspace::register_project_item::<Editor>(cx);
304 workspace::FollowableViewRegistry::register::<Editor>(cx);
305 workspace::register_serializable_item::<Editor>(cx);
306
307 cx.observe_new_views(
308 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
309 workspace.register_action(Editor::new_file);
310 workspace.register_action(Editor::new_file_vertical);
311 workspace.register_action(Editor::new_file_horizontal);
312 },
313 )
314 .detach();
315
316 cx.on_action(move |_: &workspace::NewFile, cx| {
317 let app_state = workspace::AppState::global(cx);
318 if let Some(app_state) = app_state.upgrade() {
319 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
320 Editor::new_file(workspace, &Default::default(), cx)
321 })
322 .detach();
323 }
324 });
325 cx.on_action(move |_: &workspace::NewWindow, cx| {
326 let app_state = workspace::AppState::global(cx);
327 if let Some(app_state) = app_state.upgrade() {
328 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
329 Editor::new_file(workspace, &Default::default(), cx)
330 })
331 .detach();
332 }
333 });
334}
335
336pub struct SearchWithinRange;
337
338trait InvalidationRegion {
339 fn ranges(&self) -> &[Range<Anchor>];
340}
341
342#[derive(Clone, Debug, PartialEq)]
343pub enum SelectPhase {
344 Begin {
345 position: DisplayPoint,
346 add: bool,
347 click_count: usize,
348 },
349 BeginColumnar {
350 position: DisplayPoint,
351 reset: bool,
352 goal_column: u32,
353 },
354 Extend {
355 position: DisplayPoint,
356 click_count: usize,
357 },
358 Update {
359 position: DisplayPoint,
360 goal_column: u32,
361 scroll_delta: gpui::Point<f32>,
362 },
363 End,
364}
365
366#[derive(Clone, Debug)]
367pub enum SelectMode {
368 Character,
369 Word(Range<Anchor>),
370 Line(Range<Anchor>),
371 All,
372}
373
374#[derive(Copy, Clone, PartialEq, Eq, Debug)]
375pub enum EditorMode {
376 SingleLine { auto_width: bool },
377 AutoHeight { max_lines: usize },
378 Full,
379}
380
381#[derive(Copy, Clone, Debug)]
382pub enum SoftWrap {
383 /// Prefer not to wrap at all.
384 ///
385 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
386 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
387 GitDiff,
388 /// Prefer a single line generally, unless an overly long line is encountered.
389 None,
390 /// Soft wrap lines that exceed the editor width.
391 EditorWidth,
392 /// Soft wrap lines at the preferred line length.
393 Column(u32),
394 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
395 Bounded(u32),
396}
397
398#[derive(Clone)]
399pub struct EditorStyle {
400 pub background: Hsla,
401 pub local_player: PlayerColor,
402 pub text: TextStyle,
403 pub scrollbar_width: Pixels,
404 pub syntax: Arc<SyntaxTheme>,
405 pub status: StatusColors,
406 pub inlay_hints_style: HighlightStyle,
407 pub suggestions_style: HighlightStyle,
408 pub unnecessary_code_fade: f32,
409}
410
411impl Default for EditorStyle {
412 fn default() -> Self {
413 Self {
414 background: Hsla::default(),
415 local_player: PlayerColor::default(),
416 text: TextStyle::default(),
417 scrollbar_width: Pixels::default(),
418 syntax: Default::default(),
419 // HACK: Status colors don't have a real default.
420 // We should look into removing the status colors from the editor
421 // style and retrieve them directly from the theme.
422 status: StatusColors::dark(),
423 inlay_hints_style: HighlightStyle::default(),
424 suggestions_style: HighlightStyle::default(),
425 unnecessary_code_fade: Default::default(),
426 }
427 }
428}
429
430pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
431 let show_background = language_settings::language_settings(None, None, cx)
432 .inlay_hints
433 .show_background;
434
435 HighlightStyle {
436 color: Some(cx.theme().status().hint),
437 background_color: show_background.then(|| cx.theme().status().hint_background),
438 ..HighlightStyle::default()
439 }
440}
441
442type CompletionId = usize;
443
444#[derive(Clone, Debug)]
445struct CompletionState {
446 // render_inlay_ids represents the inlay hints that are inserted
447 // for rendering the inline completions. They may be discontinuous
448 // in the event that the completion provider returns some intersection
449 // with the existing content.
450 render_inlay_ids: Vec<InlayId>,
451 // text is the resulting rope that is inserted when the user accepts a completion.
452 text: Rope,
453 // position is the position of the cursor when the completion was triggered.
454 position: multi_buffer::Anchor,
455 // delete_range is the range of text that this completion state covers.
456 // if the completion is accepted, this range should be deleted.
457 delete_range: Option<Range<multi_buffer::Anchor>>,
458}
459
460#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
461struct EditorActionId(usize);
462
463impl EditorActionId {
464 pub fn post_inc(&mut self) -> Self {
465 let answer = self.0;
466
467 *self = Self(answer + 1);
468
469 Self(answer)
470 }
471}
472
473// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
474// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
475
476type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
477type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
478
479#[derive(Default)]
480struct ScrollbarMarkerState {
481 scrollbar_size: Size<Pixels>,
482 dirty: bool,
483 markers: Arc<[PaintQuad]>,
484 pending_refresh: Option<Task<Result<()>>>,
485}
486
487impl ScrollbarMarkerState {
488 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
489 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
490 }
491}
492
493#[derive(Clone, Debug)]
494struct RunnableTasks {
495 templates: Vec<(TaskSourceKind, TaskTemplate)>,
496 offset: MultiBufferOffset,
497 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
498 column: u32,
499 // Values of all named captures, including those starting with '_'
500 extra_variables: HashMap<String, String>,
501 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
502 context_range: Range<BufferOffset>,
503}
504
505#[derive(Clone)]
506struct ResolvedTasks {
507 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
508 position: Anchor,
509}
510#[derive(Copy, Clone, Debug)]
511struct MultiBufferOffset(usize);
512#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
513struct BufferOffset(usize);
514
515// Addons allow storing per-editor state in other crates (e.g. Vim)
516pub trait Addon: 'static {
517 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
518
519 fn to_any(&self) -> &dyn std::any::Any;
520}
521
522/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
523///
524/// See the [module level documentation](self) for more information.
525pub struct Editor {
526 focus_handle: FocusHandle,
527 last_focused_descendant: Option<WeakFocusHandle>,
528 /// The text buffer being edited
529 buffer: Model<MultiBuffer>,
530 /// Map of how text in the buffer should be displayed.
531 /// Handles soft wraps, folds, fake inlay text insertions, etc.
532 pub display_map: Model<DisplayMap>,
533 pub selections: SelectionsCollection,
534 pub scroll_manager: ScrollManager,
535 /// When inline assist editors are linked, they all render cursors because
536 /// typing enters text into each of them, even the ones that aren't focused.
537 pub(crate) show_cursor_when_unfocused: bool,
538 columnar_selection_tail: Option<Anchor>,
539 add_selections_state: Option<AddSelectionsState>,
540 select_next_state: Option<SelectNextState>,
541 select_prev_state: Option<SelectNextState>,
542 selection_history: SelectionHistory,
543 autoclose_regions: Vec<AutocloseRegion>,
544 snippet_stack: InvalidationStack<SnippetState>,
545 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
546 ime_transaction: Option<TransactionId>,
547 active_diagnostics: Option<ActiveDiagnosticGroup>,
548 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
549 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 breadcrumb_header: Option<String>,
643 focused_block: Option<FocusedBlock>,
644 next_scroll_position: NextScrollCursorCenterTopBottom,
645 addons: HashMap<TypeId, Box<dyn Addon>>,
646 _scroll_cursor_center_top_bottom_task: Task<()>,
647}
648
649#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
650enum NextScrollCursorCenterTopBottom {
651 #[default]
652 Center,
653 Top,
654 Bottom,
655}
656
657impl NextScrollCursorCenterTopBottom {
658 fn next(&self) -> Self {
659 match self {
660 Self::Center => Self::Top,
661 Self::Top => Self::Bottom,
662 Self::Bottom => Self::Center,
663 }
664 }
665}
666
667#[derive(Clone)]
668pub struct EditorSnapshot {
669 pub mode: EditorMode,
670 show_gutter: bool,
671 show_line_numbers: Option<bool>,
672 show_git_diff_gutter: Option<bool>,
673 show_code_actions: Option<bool>,
674 show_runnables: Option<bool>,
675 git_blame_gutter_max_author_length: Option<usize>,
676 pub display_snapshot: DisplaySnapshot,
677 pub placeholder_text: Option<Arc<str>>,
678 is_focused: bool,
679 scroll_anchor: ScrollAnchor,
680 ongoing_scroll: OngoingScroll,
681 current_line_highlight: CurrentLineHighlight,
682 gutter_hovered: bool,
683}
684
685const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
686
687#[derive(Default, Debug, Clone, Copy)]
688pub struct GutterDimensions {
689 pub left_padding: Pixels,
690 pub right_padding: Pixels,
691 pub width: Pixels,
692 pub margin: Pixels,
693 pub git_blame_entries_width: Option<Pixels>,
694}
695
696impl GutterDimensions {
697 /// The full width of the space taken up by the gutter.
698 pub fn full_width(&self) -> Pixels {
699 self.margin + self.width
700 }
701
702 /// The width of the space reserved for the fold indicators,
703 /// use alongside 'justify_end' and `gutter_width` to
704 /// right align content with the line numbers
705 pub fn fold_area_width(&self) -> Pixels {
706 self.margin + self.right_padding
707 }
708}
709
710#[derive(Debug)]
711pub struct RemoteSelection {
712 pub replica_id: ReplicaId,
713 pub selection: Selection<Anchor>,
714 pub cursor_shape: CursorShape,
715 pub peer_id: PeerId,
716 pub line_mode: bool,
717 pub participant_index: Option<ParticipantIndex>,
718 pub user_name: Option<SharedString>,
719}
720
721#[derive(Clone, Debug)]
722struct SelectionHistoryEntry {
723 selections: Arc<[Selection<Anchor>]>,
724 select_next_state: Option<SelectNextState>,
725 select_prev_state: Option<SelectNextState>,
726 add_selections_state: Option<AddSelectionsState>,
727}
728
729enum SelectionHistoryMode {
730 Normal,
731 Undoing,
732 Redoing,
733}
734
735#[derive(Clone, PartialEq, Eq, Hash)]
736struct HoveredCursor {
737 replica_id: u16,
738 selection_id: usize,
739}
740
741impl Default for SelectionHistoryMode {
742 fn default() -> Self {
743 Self::Normal
744 }
745}
746
747#[derive(Default)]
748struct SelectionHistory {
749 #[allow(clippy::type_complexity)]
750 selections_by_transaction:
751 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
752 mode: SelectionHistoryMode,
753 undo_stack: VecDeque<SelectionHistoryEntry>,
754 redo_stack: VecDeque<SelectionHistoryEntry>,
755}
756
757impl SelectionHistory {
758 fn insert_transaction(
759 &mut self,
760 transaction_id: TransactionId,
761 selections: Arc<[Selection<Anchor>]>,
762 ) {
763 self.selections_by_transaction
764 .insert(transaction_id, (selections, None));
765 }
766
767 #[allow(clippy::type_complexity)]
768 fn transaction(
769 &self,
770 transaction_id: TransactionId,
771 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
772 self.selections_by_transaction.get(&transaction_id)
773 }
774
775 #[allow(clippy::type_complexity)]
776 fn transaction_mut(
777 &mut self,
778 transaction_id: TransactionId,
779 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
780 self.selections_by_transaction.get_mut(&transaction_id)
781 }
782
783 fn push(&mut self, entry: SelectionHistoryEntry) {
784 if !entry.selections.is_empty() {
785 match self.mode {
786 SelectionHistoryMode::Normal => {
787 self.push_undo(entry);
788 self.redo_stack.clear();
789 }
790 SelectionHistoryMode::Undoing => self.push_redo(entry),
791 SelectionHistoryMode::Redoing => self.push_undo(entry),
792 }
793 }
794 }
795
796 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
797 if self
798 .undo_stack
799 .back()
800 .map_or(true, |e| e.selections != entry.selections)
801 {
802 self.undo_stack.push_back(entry);
803 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
804 self.undo_stack.pop_front();
805 }
806 }
807 }
808
809 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
810 if self
811 .redo_stack
812 .back()
813 .map_or(true, |e| e.selections != entry.selections)
814 {
815 self.redo_stack.push_back(entry);
816 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
817 self.redo_stack.pop_front();
818 }
819 }
820 }
821}
822
823struct RowHighlight {
824 index: usize,
825 range: Range<Anchor>,
826 color: Hsla,
827 should_autoscroll: bool,
828}
829
830#[derive(Clone, Debug)]
831struct AddSelectionsState {
832 above: bool,
833 stack: Vec<usize>,
834}
835
836#[derive(Clone)]
837struct SelectNextState {
838 query: AhoCorasick,
839 wordwise: bool,
840 done: bool,
841}
842
843impl std::fmt::Debug for SelectNextState {
844 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
845 f.debug_struct(std::any::type_name::<Self>())
846 .field("wordwise", &self.wordwise)
847 .field("done", &self.done)
848 .finish()
849 }
850}
851
852#[derive(Debug)]
853struct AutocloseRegion {
854 selection_id: usize,
855 range: Range<Anchor>,
856 pair: BracketPair,
857}
858
859#[derive(Debug)]
860struct SnippetState {
861 ranges: Vec<Vec<Range<Anchor>>>,
862 active_index: usize,
863}
864
865#[doc(hidden)]
866pub struct RenameState {
867 pub range: Range<Anchor>,
868 pub old_name: Arc<str>,
869 pub editor: View<Editor>,
870 block_id: CustomBlockId,
871}
872
873struct InvalidationStack<T>(Vec<T>);
874
875struct RegisteredInlineCompletionProvider {
876 provider: Arc<dyn InlineCompletionProviderHandle>,
877 _subscription: Subscription,
878}
879
880enum ContextMenu {
881 Completions(CompletionsMenu),
882 CodeActions(CodeActionsMenu),
883}
884
885impl ContextMenu {
886 fn select_first(
887 &mut self,
888 provider: Option<&dyn CompletionProvider>,
889 cx: &mut ViewContext<Editor>,
890 ) -> bool {
891 if self.visible() {
892 match self {
893 ContextMenu::Completions(menu) => menu.select_first(provider, cx),
894 ContextMenu::CodeActions(menu) => menu.select_first(cx),
895 }
896 true
897 } else {
898 false
899 }
900 }
901
902 fn select_prev(
903 &mut self,
904 provider: Option<&dyn CompletionProvider>,
905 cx: &mut ViewContext<Editor>,
906 ) -> bool {
907 if self.visible() {
908 match self {
909 ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
910 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
911 }
912 true
913 } else {
914 false
915 }
916 }
917
918 fn select_next(
919 &mut self,
920 provider: Option<&dyn CompletionProvider>,
921 cx: &mut ViewContext<Editor>,
922 ) -> bool {
923 if self.visible() {
924 match self {
925 ContextMenu::Completions(menu) => menu.select_next(provider, cx),
926 ContextMenu::CodeActions(menu) => menu.select_next(cx),
927 }
928 true
929 } else {
930 false
931 }
932 }
933
934 fn select_last(
935 &mut self,
936 provider: Option<&dyn CompletionProvider>,
937 cx: &mut ViewContext<Editor>,
938 ) -> bool {
939 if self.visible() {
940 match self {
941 ContextMenu::Completions(menu) => menu.select_last(provider, cx),
942 ContextMenu::CodeActions(menu) => menu.select_last(cx),
943 }
944 true
945 } else {
946 false
947 }
948 }
949
950 fn visible(&self) -> bool {
951 match self {
952 ContextMenu::Completions(menu) => menu.visible(),
953 ContextMenu::CodeActions(menu) => menu.visible(),
954 }
955 }
956
957 fn render(
958 &self,
959 cursor_position: DisplayPoint,
960 style: &EditorStyle,
961 max_height: Pixels,
962 workspace: Option<WeakView<Workspace>>,
963 cx: &mut ViewContext<Editor>,
964 ) -> (ContextMenuOrigin, AnyElement) {
965 match self {
966 ContextMenu::Completions(menu) => (
967 ContextMenuOrigin::EditorPoint(cursor_position),
968 menu.render(style, max_height, workspace, cx),
969 ),
970 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
971 }
972 }
973}
974
975enum ContextMenuOrigin {
976 EditorPoint(DisplayPoint),
977 GutterIndicator(DisplayRow),
978}
979
980#[derive(Clone)]
981struct CompletionsMenu {
982 id: CompletionId,
983 sort_completions: bool,
984 initial_position: Anchor,
985 buffer: Model<Buffer>,
986 completions: Arc<RwLock<Box<[Completion]>>>,
987 match_candidates: Arc<[StringMatchCandidate]>,
988 matches: Arc<[StringMatch]>,
989 selected_item: usize,
990 scroll_handle: UniformListScrollHandle,
991 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
992}
993
994impl CompletionsMenu {
995 fn select_first(
996 &mut self,
997 provider: Option<&dyn CompletionProvider>,
998 cx: &mut ViewContext<Editor>,
999 ) {
1000 self.selected_item = 0;
1001 self.scroll_handle.scroll_to_item(self.selected_item);
1002 self.attempt_resolve_selected_completion_documentation(provider, cx);
1003 cx.notify();
1004 }
1005
1006 fn select_prev(
1007 &mut self,
1008 provider: Option<&dyn CompletionProvider>,
1009 cx: &mut ViewContext<Editor>,
1010 ) {
1011 if self.selected_item > 0 {
1012 self.selected_item -= 1;
1013 } else {
1014 self.selected_item = self.matches.len() - 1;
1015 }
1016 self.scroll_handle.scroll_to_item(self.selected_item);
1017 self.attempt_resolve_selected_completion_documentation(provider, cx);
1018 cx.notify();
1019 }
1020
1021 fn select_next(
1022 &mut self,
1023 provider: Option<&dyn CompletionProvider>,
1024 cx: &mut ViewContext<Editor>,
1025 ) {
1026 if self.selected_item + 1 < self.matches.len() {
1027 self.selected_item += 1;
1028 } else {
1029 self.selected_item = 0;
1030 }
1031 self.scroll_handle.scroll_to_item(self.selected_item);
1032 self.attempt_resolve_selected_completion_documentation(provider, cx);
1033 cx.notify();
1034 }
1035
1036 fn select_last(
1037 &mut self,
1038 provider: Option<&dyn CompletionProvider>,
1039 cx: &mut ViewContext<Editor>,
1040 ) {
1041 self.selected_item = self.matches.len() - 1;
1042 self.scroll_handle.scroll_to_item(self.selected_item);
1043 self.attempt_resolve_selected_completion_documentation(provider, cx);
1044 cx.notify();
1045 }
1046
1047 fn pre_resolve_completion_documentation(
1048 buffer: Model<Buffer>,
1049 completions: Arc<RwLock<Box<[Completion]>>>,
1050 matches: Arc<[StringMatch]>,
1051 editor: &Editor,
1052 cx: &mut ViewContext<Editor>,
1053 ) -> Task<()> {
1054 let settings = EditorSettings::get_global(cx);
1055 if !settings.show_completion_documentation {
1056 return Task::ready(());
1057 }
1058
1059 let Some(provider) = editor.completion_provider.as_ref() else {
1060 return Task::ready(());
1061 };
1062
1063 let resolve_task = provider.resolve_completions(
1064 buffer,
1065 matches.iter().map(|m| m.candidate_id).collect(),
1066 completions.clone(),
1067 cx,
1068 );
1069
1070 cx.spawn(move |this, mut cx| async move {
1071 if let Some(true) = resolve_task.await.log_err() {
1072 this.update(&mut cx, |_, cx| cx.notify()).ok();
1073 }
1074 })
1075 }
1076
1077 fn attempt_resolve_selected_completion_documentation(
1078 &mut self,
1079 provider: Option<&dyn CompletionProvider>,
1080 cx: &mut ViewContext<Editor>,
1081 ) {
1082 let settings = EditorSettings::get_global(cx);
1083 if !settings.show_completion_documentation {
1084 return;
1085 }
1086
1087 let completion_index = self.matches[self.selected_item].candidate_id;
1088 let Some(provider) = provider else {
1089 return;
1090 };
1091
1092 let resolve_task = provider.resolve_completions(
1093 self.buffer.clone(),
1094 vec![completion_index],
1095 self.completions.clone(),
1096 cx,
1097 );
1098
1099 let delay_ms =
1100 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1101 let delay = Duration::from_millis(delay_ms);
1102
1103 self.selected_completion_documentation_resolve_debounce
1104 .lock()
1105 .fire_new(delay, cx, |_, cx| {
1106 cx.spawn(move |this, mut cx| async move {
1107 if let Some(true) = resolve_task.await.log_err() {
1108 this.update(&mut cx, |_, cx| cx.notify()).ok();
1109 }
1110 })
1111 });
1112 }
1113
1114 fn visible(&self) -> bool {
1115 !self.matches.is_empty()
1116 }
1117
1118 fn render(
1119 &self,
1120 style: &EditorStyle,
1121 max_height: Pixels,
1122 workspace: Option<WeakView<Workspace>>,
1123 cx: &mut ViewContext<Editor>,
1124 ) -> AnyElement {
1125 let settings = EditorSettings::get_global(cx);
1126 let show_completion_documentation = settings.show_completion_documentation;
1127
1128 let widest_completion_ix = self
1129 .matches
1130 .iter()
1131 .enumerate()
1132 .max_by_key(|(_, mat)| {
1133 let completions = self.completions.read();
1134 let completion = &completions[mat.candidate_id];
1135 let documentation = &completion.documentation;
1136
1137 let mut len = completion.label.text.chars().count();
1138 if let Some(Documentation::SingleLine(text)) = documentation {
1139 if show_completion_documentation {
1140 len += text.chars().count();
1141 }
1142 }
1143
1144 len
1145 })
1146 .map(|(ix, _)| ix);
1147
1148 let completions = self.completions.clone();
1149 let matches = self.matches.clone();
1150 let selected_item = self.selected_item;
1151 let style = style.clone();
1152
1153 let multiline_docs = if show_completion_documentation {
1154 let mat = &self.matches[selected_item];
1155 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1156 Some(Documentation::MultiLinePlainText(text)) => {
1157 Some(div().child(SharedString::from(text.clone())))
1158 }
1159 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1160 Some(div().child(render_parsed_markdown(
1161 "completions_markdown",
1162 parsed,
1163 &style,
1164 workspace,
1165 cx,
1166 )))
1167 }
1168 _ => None,
1169 };
1170 multiline_docs.map(|div| {
1171 div.id("multiline_docs")
1172 .max_h(max_height)
1173 .flex_1()
1174 .px_1p5()
1175 .py_1()
1176 .min_w(px(260.))
1177 .max_w(px(640.))
1178 .w(px(500.))
1179 .overflow_y_scroll()
1180 .occlude()
1181 })
1182 } else {
1183 None
1184 };
1185
1186 let list = uniform_list(
1187 cx.view().clone(),
1188 "completions",
1189 matches.len(),
1190 move |_editor, range, cx| {
1191 let start_ix = range.start;
1192 let completions_guard = completions.read();
1193
1194 matches[range]
1195 .iter()
1196 .enumerate()
1197 .map(|(ix, mat)| {
1198 let item_ix = start_ix + ix;
1199 let candidate_id = mat.candidate_id;
1200 let completion = &completions_guard[candidate_id];
1201
1202 let documentation = if show_completion_documentation {
1203 &completion.documentation
1204 } else {
1205 &None
1206 };
1207
1208 let highlights = gpui::combine_highlights(
1209 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1210 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1211 |(range, mut highlight)| {
1212 // Ignore font weight for syntax highlighting, as we'll use it
1213 // for fuzzy matches.
1214 highlight.font_weight = None;
1215
1216 if completion.lsp_completion.deprecated.unwrap_or(false) {
1217 highlight.strikethrough = Some(StrikethroughStyle {
1218 thickness: 1.0.into(),
1219 ..Default::default()
1220 });
1221 highlight.color = Some(cx.theme().colors().text_muted);
1222 }
1223
1224 (range, highlight)
1225 },
1226 ),
1227 );
1228 let completion_label = StyledText::new(completion.label.text.clone())
1229 .with_highlights(&style.text, highlights);
1230 let documentation_label =
1231 if let Some(Documentation::SingleLine(text)) = documentation {
1232 if text.trim().is_empty() {
1233 None
1234 } else {
1235 Some(
1236 Label::new(text.clone())
1237 .ml_4()
1238 .size(LabelSize::Small)
1239 .color(Color::Muted),
1240 )
1241 }
1242 } else {
1243 None
1244 };
1245
1246 let color_swatch = completion
1247 .color()
1248 .map(|color| div().size_4().bg(color).rounded_sm());
1249
1250 div().min_w(px(220.)).max_w(px(540.)).child(
1251 ListItem::new(mat.candidate_id)
1252 .inset(true)
1253 .selected(item_ix == selected_item)
1254 .on_click(cx.listener(move |editor, _event, cx| {
1255 cx.stop_propagation();
1256 if let Some(task) = editor.confirm_completion(
1257 &ConfirmCompletion {
1258 item_ix: Some(item_ix),
1259 },
1260 cx,
1261 ) {
1262 task.detach_and_log_err(cx)
1263 }
1264 }))
1265 .start_slot::<Div>(color_swatch)
1266 .child(h_flex().overflow_hidden().child(completion_label))
1267 .end_slot::<Label>(documentation_label),
1268 )
1269 })
1270 .collect()
1271 },
1272 )
1273 .occlude()
1274 .max_h(max_height)
1275 .track_scroll(self.scroll_handle.clone())
1276 .with_width_from_item(widest_completion_ix)
1277 .with_sizing_behavior(ListSizingBehavior::Infer);
1278
1279 Popover::new()
1280 .child(list)
1281 .when_some(multiline_docs, |popover, multiline_docs| {
1282 popover.aside(multiline_docs)
1283 })
1284 .into_any_element()
1285 }
1286
1287 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1288 let mut matches = if let Some(query) = query {
1289 fuzzy::match_strings(
1290 &self.match_candidates,
1291 query,
1292 query.chars().any(|c| c.is_uppercase()),
1293 100,
1294 &Default::default(),
1295 executor,
1296 )
1297 .await
1298 } else {
1299 self.match_candidates
1300 .iter()
1301 .enumerate()
1302 .map(|(candidate_id, candidate)| StringMatch {
1303 candidate_id,
1304 score: Default::default(),
1305 positions: Default::default(),
1306 string: candidate.string.clone(),
1307 })
1308 .collect()
1309 };
1310
1311 // Remove all candidates where the query's start does not match the start of any word in the candidate
1312 if let Some(query) = query {
1313 if let Some(query_start) = query.chars().next() {
1314 matches.retain(|string_match| {
1315 split_words(&string_match.string).any(|word| {
1316 // Check that the first codepoint of the word as lowercase matches the first
1317 // codepoint of the query as lowercase
1318 word.chars()
1319 .flat_map(|codepoint| codepoint.to_lowercase())
1320 .zip(query_start.to_lowercase())
1321 .all(|(word_cp, query_cp)| word_cp == query_cp)
1322 })
1323 });
1324 }
1325 }
1326
1327 let completions = self.completions.read();
1328 if self.sort_completions {
1329 matches.sort_unstable_by_key(|mat| {
1330 // We do want to strike a balance here between what the language server tells us
1331 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1332 // `Creat` and there is a local variable called `CreateComponent`).
1333 // So what we do is: we bucket all matches into two buckets
1334 // - Strong matches
1335 // - Weak matches
1336 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1337 // and the Weak matches are the rest.
1338 //
1339 // For the strong matches, we sort by the language-servers score first and for the weak
1340 // matches, we prefer our fuzzy finder first.
1341 //
1342 // The thinking behind that: it's useless to take the sort_text the language-server gives
1343 // us into account when it's obviously a bad match.
1344
1345 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1346 enum MatchScore<'a> {
1347 Strong {
1348 sort_text: Option<&'a str>,
1349 score: Reverse<OrderedFloat<f64>>,
1350 sort_key: (usize, &'a str),
1351 },
1352 Weak {
1353 score: Reverse<OrderedFloat<f64>>,
1354 sort_text: Option<&'a str>,
1355 sort_key: (usize, &'a str),
1356 },
1357 }
1358
1359 let completion = &completions[mat.candidate_id];
1360 let sort_key = completion.sort_key();
1361 let sort_text = completion.lsp_completion.sort_text.as_deref();
1362 let score = Reverse(OrderedFloat(mat.score));
1363
1364 if mat.score >= 0.2 {
1365 MatchScore::Strong {
1366 sort_text,
1367 score,
1368 sort_key,
1369 }
1370 } else {
1371 MatchScore::Weak {
1372 score,
1373 sort_text,
1374 sort_key,
1375 }
1376 }
1377 });
1378 }
1379
1380 for mat in &mut matches {
1381 let completion = &completions[mat.candidate_id];
1382 mat.string.clone_from(&completion.label.text);
1383 for position in &mut mat.positions {
1384 *position += completion.label.filter_range.start;
1385 }
1386 }
1387 drop(completions);
1388
1389 self.matches = matches.into();
1390 self.selected_item = 0;
1391 }
1392}
1393
1394struct AvailableCodeAction {
1395 excerpt_id: ExcerptId,
1396 action: CodeAction,
1397 provider: Arc<dyn CodeActionProvider>,
1398}
1399
1400#[derive(Clone)]
1401struct CodeActionContents {
1402 tasks: Option<Arc<ResolvedTasks>>,
1403 actions: Option<Arc<[AvailableCodeAction]>>,
1404}
1405
1406impl CodeActionContents {
1407 fn len(&self) -> usize {
1408 match (&self.tasks, &self.actions) {
1409 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1410 (Some(tasks), None) => tasks.templates.len(),
1411 (None, Some(actions)) => actions.len(),
1412 (None, None) => 0,
1413 }
1414 }
1415
1416 fn is_empty(&self) -> bool {
1417 match (&self.tasks, &self.actions) {
1418 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1419 (Some(tasks), None) => tasks.templates.is_empty(),
1420 (None, Some(actions)) => actions.is_empty(),
1421 (None, None) => true,
1422 }
1423 }
1424
1425 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1426 self.tasks
1427 .iter()
1428 .flat_map(|tasks| {
1429 tasks
1430 .templates
1431 .iter()
1432 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1433 })
1434 .chain(self.actions.iter().flat_map(|actions| {
1435 actions.iter().map(|available| CodeActionsItem::CodeAction {
1436 excerpt_id: available.excerpt_id,
1437 action: available.action.clone(),
1438 provider: available.provider.clone(),
1439 })
1440 }))
1441 }
1442 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1443 match (&self.tasks, &self.actions) {
1444 (Some(tasks), Some(actions)) => {
1445 if index < tasks.templates.len() {
1446 tasks
1447 .templates
1448 .get(index)
1449 .cloned()
1450 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1451 } else {
1452 actions.get(index - tasks.templates.len()).map(|available| {
1453 CodeActionsItem::CodeAction {
1454 excerpt_id: available.excerpt_id,
1455 action: available.action.clone(),
1456 provider: available.provider.clone(),
1457 }
1458 })
1459 }
1460 }
1461 (Some(tasks), None) => tasks
1462 .templates
1463 .get(index)
1464 .cloned()
1465 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1466 (None, Some(actions)) => {
1467 actions
1468 .get(index)
1469 .map(|available| CodeActionsItem::CodeAction {
1470 excerpt_id: available.excerpt_id,
1471 action: available.action.clone(),
1472 provider: available.provider.clone(),
1473 })
1474 }
1475 (None, None) => None,
1476 }
1477 }
1478}
1479
1480#[allow(clippy::large_enum_variant)]
1481#[derive(Clone)]
1482enum CodeActionsItem {
1483 Task(TaskSourceKind, ResolvedTask),
1484 CodeAction {
1485 excerpt_id: ExcerptId,
1486 action: CodeAction,
1487 provider: Arc<dyn CodeActionProvider>,
1488 },
1489}
1490
1491impl CodeActionsItem {
1492 fn as_task(&self) -> Option<&ResolvedTask> {
1493 let Self::Task(_, task) = self else {
1494 return None;
1495 };
1496 Some(task)
1497 }
1498 fn as_code_action(&self) -> Option<&CodeAction> {
1499 let Self::CodeAction { action, .. } = self else {
1500 return None;
1501 };
1502 Some(action)
1503 }
1504 fn label(&self) -> String {
1505 match self {
1506 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1507 Self::Task(_, task) => task.resolved_label.clone(),
1508 }
1509 }
1510}
1511
1512struct CodeActionsMenu {
1513 actions: CodeActionContents,
1514 buffer: Model<Buffer>,
1515 selected_item: usize,
1516 scroll_handle: UniformListScrollHandle,
1517 deployed_from_indicator: Option<DisplayRow>,
1518}
1519
1520impl CodeActionsMenu {
1521 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1522 self.selected_item = 0;
1523 self.scroll_handle.scroll_to_item(self.selected_item);
1524 cx.notify()
1525 }
1526
1527 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1528 if self.selected_item > 0 {
1529 self.selected_item -= 1;
1530 } else {
1531 self.selected_item = self.actions.len() - 1;
1532 }
1533 self.scroll_handle.scroll_to_item(self.selected_item);
1534 cx.notify();
1535 }
1536
1537 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1538 if self.selected_item + 1 < self.actions.len() {
1539 self.selected_item += 1;
1540 } else {
1541 self.selected_item = 0;
1542 }
1543 self.scroll_handle.scroll_to_item(self.selected_item);
1544 cx.notify();
1545 }
1546
1547 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1548 self.selected_item = self.actions.len() - 1;
1549 self.scroll_handle.scroll_to_item(self.selected_item);
1550 cx.notify()
1551 }
1552
1553 fn visible(&self) -> bool {
1554 !self.actions.is_empty()
1555 }
1556
1557 fn render(
1558 &self,
1559 cursor_position: DisplayPoint,
1560 _style: &EditorStyle,
1561 max_height: Pixels,
1562 cx: &mut ViewContext<Editor>,
1563 ) -> (ContextMenuOrigin, AnyElement) {
1564 let actions = self.actions.clone();
1565 let selected_item = self.selected_item;
1566 let element = uniform_list(
1567 cx.view().clone(),
1568 "code_actions_menu",
1569 self.actions.len(),
1570 move |_this, range, cx| {
1571 actions
1572 .iter()
1573 .skip(range.start)
1574 .take(range.end - range.start)
1575 .enumerate()
1576 .map(|(ix, action)| {
1577 let item_ix = range.start + ix;
1578 let selected = selected_item == item_ix;
1579 let colors = cx.theme().colors();
1580 div()
1581 .px_1()
1582 .rounded_md()
1583 .text_color(colors.text)
1584 .when(selected, |style| {
1585 style
1586 .bg(colors.element_active)
1587 .text_color(colors.text_accent)
1588 })
1589 .hover(|style| {
1590 style
1591 .bg(colors.element_hover)
1592 .text_color(colors.text_accent)
1593 })
1594 .whitespace_nowrap()
1595 .when_some(action.as_code_action(), |this, action| {
1596 this.on_mouse_down(
1597 MouseButton::Left,
1598 cx.listener(move |editor, _, cx| {
1599 cx.stop_propagation();
1600 if let Some(task) = editor.confirm_code_action(
1601 &ConfirmCodeAction {
1602 item_ix: Some(item_ix),
1603 },
1604 cx,
1605 ) {
1606 task.detach_and_log_err(cx)
1607 }
1608 }),
1609 )
1610 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1611 .child(SharedString::from(action.lsp_action.title.clone()))
1612 })
1613 .when_some(action.as_task(), |this, task| {
1614 this.on_mouse_down(
1615 MouseButton::Left,
1616 cx.listener(move |editor, _, cx| {
1617 cx.stop_propagation();
1618 if let Some(task) = editor.confirm_code_action(
1619 &ConfirmCodeAction {
1620 item_ix: Some(item_ix),
1621 },
1622 cx,
1623 ) {
1624 task.detach_and_log_err(cx)
1625 }
1626 }),
1627 )
1628 .child(SharedString::from(task.resolved_label.clone()))
1629 })
1630 })
1631 .collect()
1632 },
1633 )
1634 .elevation_1(cx)
1635 .p_1()
1636 .max_h(max_height)
1637 .occlude()
1638 .track_scroll(self.scroll_handle.clone())
1639 .with_width_from_item(
1640 self.actions
1641 .iter()
1642 .enumerate()
1643 .max_by_key(|(_, action)| match action {
1644 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1645 CodeActionsItem::CodeAction { action, .. } => {
1646 action.lsp_action.title.chars().count()
1647 }
1648 })
1649 .map(|(ix, _)| ix),
1650 )
1651 .with_sizing_behavior(ListSizingBehavior::Infer)
1652 .into_any_element();
1653
1654 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1655 ContextMenuOrigin::GutterIndicator(row)
1656 } else {
1657 ContextMenuOrigin::EditorPoint(cursor_position)
1658 };
1659
1660 (cursor_position, element)
1661 }
1662}
1663
1664#[derive(Debug)]
1665struct ActiveDiagnosticGroup {
1666 primary_range: Range<Anchor>,
1667 primary_message: String,
1668 group_id: usize,
1669 blocks: HashMap<CustomBlockId, Diagnostic>,
1670 is_valid: bool,
1671}
1672
1673#[derive(Serialize, Deserialize, Clone, Debug)]
1674pub struct ClipboardSelection {
1675 pub len: usize,
1676 pub is_entire_line: bool,
1677 pub first_line_indent: u32,
1678}
1679
1680#[derive(Debug)]
1681pub(crate) struct NavigationData {
1682 cursor_anchor: Anchor,
1683 cursor_position: Point,
1684 scroll_anchor: ScrollAnchor,
1685 scroll_top_row: u32,
1686}
1687
1688#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1689pub enum GotoDefinitionKind {
1690 Symbol,
1691 Declaration,
1692 Type,
1693 Implementation,
1694}
1695
1696#[derive(Debug, Clone)]
1697enum InlayHintRefreshReason {
1698 Toggle(bool),
1699 SettingsChange(InlayHintSettings),
1700 NewLinesShown,
1701 BufferEdited(HashSet<Arc<Language>>),
1702 RefreshRequested,
1703 ExcerptsRemoved(Vec<ExcerptId>),
1704}
1705
1706impl InlayHintRefreshReason {
1707 fn description(&self) -> &'static str {
1708 match self {
1709 Self::Toggle(_) => "toggle",
1710 Self::SettingsChange(_) => "settings change",
1711 Self::NewLinesShown => "new lines shown",
1712 Self::BufferEdited(_) => "buffer edited",
1713 Self::RefreshRequested => "refresh requested",
1714 Self::ExcerptsRemoved(_) => "excerpts removed",
1715 }
1716 }
1717}
1718
1719pub(crate) struct FocusedBlock {
1720 id: BlockId,
1721 focus_handle: WeakFocusHandle,
1722}
1723
1724impl Editor {
1725 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1726 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1727 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1728 Self::new(
1729 EditorMode::SingleLine { auto_width: false },
1730 buffer,
1731 None,
1732 false,
1733 cx,
1734 )
1735 }
1736
1737 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1738 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1739 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1740 Self::new(EditorMode::Full, buffer, None, false, cx)
1741 }
1742
1743 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1744 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1745 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1746 Self::new(
1747 EditorMode::SingleLine { auto_width: true },
1748 buffer,
1749 None,
1750 false,
1751 cx,
1752 )
1753 }
1754
1755 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1756 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1757 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1758 Self::new(
1759 EditorMode::AutoHeight { max_lines },
1760 buffer,
1761 None,
1762 false,
1763 cx,
1764 )
1765 }
1766
1767 pub fn for_buffer(
1768 buffer: Model<Buffer>,
1769 project: Option<Model<Project>>,
1770 cx: &mut ViewContext<Self>,
1771 ) -> Self {
1772 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1773 Self::new(EditorMode::Full, buffer, project, false, cx)
1774 }
1775
1776 pub fn for_multibuffer(
1777 buffer: Model<MultiBuffer>,
1778 project: Option<Model<Project>>,
1779 show_excerpt_controls: bool,
1780 cx: &mut ViewContext<Self>,
1781 ) -> Self {
1782 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1783 }
1784
1785 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1786 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1787 let mut clone = Self::new(
1788 self.mode,
1789 self.buffer.clone(),
1790 self.project.clone(),
1791 show_excerpt_controls,
1792 cx,
1793 );
1794 self.display_map.update(cx, |display_map, cx| {
1795 let snapshot = display_map.snapshot(cx);
1796 clone.display_map.update(cx, |display_map, cx| {
1797 display_map.set_state(&snapshot, cx);
1798 });
1799 });
1800 clone.selections.clone_state(&self.selections);
1801 clone.scroll_manager.clone_state(&self.scroll_manager);
1802 clone.searchable = self.searchable;
1803 clone
1804 }
1805
1806 pub fn new(
1807 mode: EditorMode,
1808 buffer: Model<MultiBuffer>,
1809 project: Option<Model<Project>>,
1810 show_excerpt_controls: bool,
1811 cx: &mut ViewContext<Self>,
1812 ) -> Self {
1813 let style = cx.text_style();
1814 let font_size = style.font_size.to_pixels(cx.rem_size());
1815 let editor = cx.view().downgrade();
1816 let fold_placeholder = FoldPlaceholder {
1817 constrain_width: true,
1818 render: Arc::new(move |fold_id, fold_range, cx| {
1819 let editor = editor.clone();
1820 div()
1821 .id(fold_id)
1822 .bg(cx.theme().colors().ghost_element_background)
1823 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1824 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1825 .rounded_sm()
1826 .size_full()
1827 .cursor_pointer()
1828 .child("⋯")
1829 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1830 .on_click(move |_, cx| {
1831 editor
1832 .update(cx, |editor, cx| {
1833 editor.unfold_ranges(
1834 [fold_range.start..fold_range.end],
1835 true,
1836 false,
1837 cx,
1838 );
1839 cx.stop_propagation();
1840 })
1841 .ok();
1842 })
1843 .into_any()
1844 }),
1845 merge_adjacent: true,
1846 };
1847 let display_map = cx.new_model(|cx| {
1848 DisplayMap::new(
1849 buffer.clone(),
1850 style.font(),
1851 font_size,
1852 None,
1853 show_excerpt_controls,
1854 FILE_HEADER_HEIGHT,
1855 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1856 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1857 fold_placeholder,
1858 cx,
1859 )
1860 });
1861
1862 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1863
1864 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1865
1866 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1867 .then(|| language_settings::SoftWrap::None);
1868
1869 let mut project_subscriptions = Vec::new();
1870 if mode == EditorMode::Full {
1871 if let Some(project) = project.as_ref() {
1872 if buffer.read(cx).is_singleton() {
1873 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1874 cx.emit(EditorEvent::TitleChanged);
1875 }));
1876 }
1877 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1878 if let project::Event::RefreshInlayHints = event {
1879 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1880 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1881 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1882 let focus_handle = editor.focus_handle(cx);
1883 if focus_handle.is_focused(cx) {
1884 let snapshot = buffer.read(cx).snapshot();
1885 for (range, snippet) in snippet_edits {
1886 let editor_range =
1887 language::range_from_lsp(*range).to_offset(&snapshot);
1888 editor
1889 .insert_snippet(&[editor_range], snippet.clone(), cx)
1890 .ok();
1891 }
1892 }
1893 }
1894 }
1895 }));
1896 if let Some(task_inventory) = project
1897 .read(cx)
1898 .task_store()
1899 .read(cx)
1900 .task_inventory()
1901 .cloned()
1902 {
1903 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1904 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1905 }));
1906 }
1907 }
1908 }
1909
1910 let inlay_hint_settings = inlay_hint_settings(
1911 selections.newest_anchor().head(),
1912 &buffer.read(cx).snapshot(cx),
1913 cx,
1914 );
1915 let focus_handle = cx.focus_handle();
1916 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1917 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1918 .detach();
1919 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1920 .detach();
1921 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1922
1923 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1924 Some(false)
1925 } else {
1926 None
1927 };
1928
1929 let mut code_action_providers = Vec::new();
1930 if let Some(project) = project.clone() {
1931 code_action_providers.push(Arc::new(project) as Arc<_>);
1932 }
1933
1934 let mut this = Self {
1935 focus_handle,
1936 show_cursor_when_unfocused: false,
1937 last_focused_descendant: None,
1938 buffer: buffer.clone(),
1939 display_map: display_map.clone(),
1940 selections,
1941 scroll_manager: ScrollManager::new(cx),
1942 columnar_selection_tail: None,
1943 add_selections_state: None,
1944 select_next_state: None,
1945 select_prev_state: None,
1946 selection_history: Default::default(),
1947 autoclose_regions: Default::default(),
1948 snippet_stack: Default::default(),
1949 select_larger_syntax_node_stack: Vec::new(),
1950 ime_transaction: Default::default(),
1951 active_diagnostics: None,
1952 soft_wrap_mode_override,
1953 completion_provider: project.clone().map(|project| Box::new(project) as _),
1954 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1955 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1956 project,
1957 blink_manager: blink_manager.clone(),
1958 show_local_selections: true,
1959 mode,
1960 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1961 show_gutter: mode == EditorMode::Full,
1962 show_line_numbers: None,
1963 use_relative_line_numbers: None,
1964 show_git_diff_gutter: None,
1965 show_code_actions: None,
1966 show_runnables: None,
1967 show_wrap_guides: None,
1968 show_indent_guides,
1969 placeholder_text: None,
1970 highlight_order: 0,
1971 highlighted_rows: HashMap::default(),
1972 background_highlights: Default::default(),
1973 gutter_highlights: TreeMap::default(),
1974 scrollbar_marker_state: ScrollbarMarkerState::default(),
1975 active_indent_guides_state: ActiveIndentGuidesState::default(),
1976 nav_history: None,
1977 context_menu: RwLock::new(None),
1978 mouse_context_menu: None,
1979 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1980 completion_tasks: Default::default(),
1981 signature_help_state: SignatureHelpState::default(),
1982 auto_signature_help: None,
1983 find_all_references_task_sources: Vec::new(),
1984 next_completion_id: 0,
1985 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1986 next_inlay_id: 0,
1987 code_action_providers,
1988 available_code_actions: Default::default(),
1989 code_actions_task: Default::default(),
1990 document_highlights_task: Default::default(),
1991 linked_editing_range_task: Default::default(),
1992 pending_rename: Default::default(),
1993 searchable: true,
1994 cursor_shape: EditorSettings::get_global(cx)
1995 .cursor_shape
1996 .unwrap_or_default(),
1997 current_line_highlight: None,
1998 autoindent_mode: Some(AutoindentMode::EachLine),
1999 collapse_matches: false,
2000 workspace: None,
2001 input_enabled: true,
2002 use_modal_editing: mode == EditorMode::Full,
2003 read_only: false,
2004 use_autoclose: true,
2005 use_auto_surround: true,
2006 auto_replace_emoji_shortcode: false,
2007 leader_peer_id: None,
2008 remote_id: None,
2009 hover_state: Default::default(),
2010 hovered_link_state: Default::default(),
2011 inline_completion_provider: None,
2012 active_inline_completion: None,
2013 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
2014 expanded_hunks: ExpandedHunks::default(),
2015 gutter_hovered: false,
2016 pixel_position_of_newest_cursor: None,
2017 last_bounds: None,
2018 expect_bounds_change: None,
2019 gutter_dimensions: GutterDimensions::default(),
2020 style: None,
2021 show_cursor_names: false,
2022 hovered_cursors: Default::default(),
2023 next_editor_action_id: EditorActionId::default(),
2024 editor_actions: Rc::default(),
2025 show_inline_completions_override: None,
2026 enable_inline_completions: true,
2027 custom_context_menu: None,
2028 show_git_blame_gutter: false,
2029 show_git_blame_inline: false,
2030 show_selection_menu: None,
2031 show_git_blame_inline_delay_task: None,
2032 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2033 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2034 .session
2035 .restore_unsaved_buffers,
2036 blame: None,
2037 blame_subscription: None,
2038 tasks: Default::default(),
2039 _subscriptions: vec![
2040 cx.observe(&buffer, Self::on_buffer_changed),
2041 cx.subscribe(&buffer, Self::on_buffer_event),
2042 cx.observe(&display_map, Self::on_display_map_changed),
2043 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2044 cx.observe_global::<SettingsStore>(Self::settings_changed),
2045 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2046 cx.observe_window_activation(|editor, cx| {
2047 let active = cx.is_window_active();
2048 editor.blink_manager.update(cx, |blink_manager, cx| {
2049 if active {
2050 blink_manager.enable(cx);
2051 } else {
2052 blink_manager.disable(cx);
2053 }
2054 });
2055 }),
2056 ],
2057 tasks_update_task: None,
2058 linked_edit_ranges: Default::default(),
2059 previous_search_ranges: None,
2060 breadcrumb_header: None,
2061 focused_block: None,
2062 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2063 addons: HashMap::default(),
2064 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2065 };
2066 this.tasks_update_task = Some(this.refresh_runnables(cx));
2067 this._subscriptions.extend(project_subscriptions);
2068
2069 this.end_selection(cx);
2070 this.scroll_manager.show_scrollbar(cx);
2071
2072 if mode == EditorMode::Full {
2073 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2074 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2075
2076 if this.git_blame_inline_enabled {
2077 this.git_blame_inline_enabled = true;
2078 this.start_git_blame_inline(false, cx);
2079 }
2080 }
2081
2082 this.report_editor_event("open", None, cx);
2083 this
2084 }
2085
2086 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2087 self.mouse_context_menu
2088 .as_ref()
2089 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2090 }
2091
2092 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2093 let mut key_context = KeyContext::new_with_defaults();
2094 key_context.add("Editor");
2095 let mode = match self.mode {
2096 EditorMode::SingleLine { .. } => "single_line",
2097 EditorMode::AutoHeight { .. } => "auto_height",
2098 EditorMode::Full => "full",
2099 };
2100
2101 if EditorSettings::jupyter_enabled(cx) {
2102 key_context.add("jupyter");
2103 }
2104
2105 key_context.set("mode", mode);
2106 if self.pending_rename.is_some() {
2107 key_context.add("renaming");
2108 }
2109 if self.context_menu_visible() {
2110 match self.context_menu.read().as_ref() {
2111 Some(ContextMenu::Completions(_)) => {
2112 key_context.add("menu");
2113 key_context.add("showing_completions")
2114 }
2115 Some(ContextMenu::CodeActions(_)) => {
2116 key_context.add("menu");
2117 key_context.add("showing_code_actions")
2118 }
2119 None => {}
2120 }
2121 }
2122
2123 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2124 if !self.focus_handle(cx).contains_focused(cx)
2125 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2126 {
2127 for addon in self.addons.values() {
2128 addon.extend_key_context(&mut key_context, cx)
2129 }
2130 }
2131
2132 if let Some(extension) = self
2133 .buffer
2134 .read(cx)
2135 .as_singleton()
2136 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2137 {
2138 key_context.set("extension", extension.to_string());
2139 }
2140
2141 if self.has_active_inline_completion(cx) {
2142 key_context.add("copilot_suggestion");
2143 key_context.add("inline_completion");
2144 }
2145
2146 key_context
2147 }
2148
2149 pub fn new_file(
2150 workspace: &mut Workspace,
2151 _: &workspace::NewFile,
2152 cx: &mut ViewContext<Workspace>,
2153 ) {
2154 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2155 "Failed to create buffer",
2156 cx,
2157 |e, _| match e.error_code() {
2158 ErrorCode::RemoteUpgradeRequired => Some(format!(
2159 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2160 e.error_tag("required").unwrap_or("the latest version")
2161 )),
2162 _ => None,
2163 },
2164 );
2165 }
2166
2167 pub fn new_in_workspace(
2168 workspace: &mut Workspace,
2169 cx: &mut ViewContext<Workspace>,
2170 ) -> Task<Result<View<Editor>>> {
2171 let project = workspace.project().clone();
2172 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2173
2174 cx.spawn(|workspace, mut cx| async move {
2175 let buffer = create.await?;
2176 workspace.update(&mut cx, |workspace, cx| {
2177 let editor =
2178 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2179 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2180 editor
2181 })
2182 })
2183 }
2184
2185 fn new_file_vertical(
2186 workspace: &mut Workspace,
2187 _: &workspace::NewFileSplitVertical,
2188 cx: &mut ViewContext<Workspace>,
2189 ) {
2190 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2191 }
2192
2193 fn new_file_horizontal(
2194 workspace: &mut Workspace,
2195 _: &workspace::NewFileSplitHorizontal,
2196 cx: &mut ViewContext<Workspace>,
2197 ) {
2198 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2199 }
2200
2201 fn new_file_in_direction(
2202 workspace: &mut Workspace,
2203 direction: SplitDirection,
2204 cx: &mut ViewContext<Workspace>,
2205 ) {
2206 let project = workspace.project().clone();
2207 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2208
2209 cx.spawn(|workspace, mut cx| async move {
2210 let buffer = create.await?;
2211 workspace.update(&mut cx, move |workspace, cx| {
2212 workspace.split_item(
2213 direction,
2214 Box::new(
2215 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2216 ),
2217 cx,
2218 )
2219 })?;
2220 anyhow::Ok(())
2221 })
2222 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2223 ErrorCode::RemoteUpgradeRequired => Some(format!(
2224 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2225 e.error_tag("required").unwrap_or("the latest version")
2226 )),
2227 _ => None,
2228 });
2229 }
2230
2231 pub fn leader_peer_id(&self) -> Option<PeerId> {
2232 self.leader_peer_id
2233 }
2234
2235 pub fn buffer(&self) -> &Model<MultiBuffer> {
2236 &self.buffer
2237 }
2238
2239 pub fn workspace(&self) -> Option<View<Workspace>> {
2240 self.workspace.as_ref()?.0.upgrade()
2241 }
2242
2243 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2244 self.buffer().read(cx).title(cx)
2245 }
2246
2247 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2248 let git_blame_gutter_max_author_length = self
2249 .render_git_blame_gutter(cx)
2250 .then(|| {
2251 if let Some(blame) = self.blame.as_ref() {
2252 let max_author_length =
2253 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2254 Some(max_author_length)
2255 } else {
2256 None
2257 }
2258 })
2259 .flatten();
2260
2261 EditorSnapshot {
2262 mode: self.mode,
2263 show_gutter: self.show_gutter,
2264 show_line_numbers: self.show_line_numbers,
2265 show_git_diff_gutter: self.show_git_diff_gutter,
2266 show_code_actions: self.show_code_actions,
2267 show_runnables: self.show_runnables,
2268 git_blame_gutter_max_author_length,
2269 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2270 scroll_anchor: self.scroll_manager.anchor(),
2271 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2272 placeholder_text: self.placeholder_text.clone(),
2273 is_focused: self.focus_handle.is_focused(cx),
2274 current_line_highlight: self
2275 .current_line_highlight
2276 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2277 gutter_hovered: self.gutter_hovered,
2278 }
2279 }
2280
2281 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2282 self.buffer.read(cx).language_at(point, cx)
2283 }
2284
2285 pub fn file_at<T: ToOffset>(
2286 &self,
2287 point: T,
2288 cx: &AppContext,
2289 ) -> Option<Arc<dyn language::File>> {
2290 self.buffer.read(cx).read(cx).file_at(point).cloned()
2291 }
2292
2293 pub fn active_excerpt(
2294 &self,
2295 cx: &AppContext,
2296 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2297 self.buffer
2298 .read(cx)
2299 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2300 }
2301
2302 pub fn mode(&self) -> EditorMode {
2303 self.mode
2304 }
2305
2306 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2307 self.collaboration_hub.as_deref()
2308 }
2309
2310 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2311 self.collaboration_hub = Some(hub);
2312 }
2313
2314 pub fn set_custom_context_menu(
2315 &mut self,
2316 f: impl 'static
2317 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2318 ) {
2319 self.custom_context_menu = Some(Box::new(f))
2320 }
2321
2322 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2323 self.completion_provider = provider;
2324 }
2325
2326 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2327 self.semantics_provider.clone()
2328 }
2329
2330 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2331 self.semantics_provider = provider;
2332 }
2333
2334 pub fn set_inline_completion_provider<T>(
2335 &mut self,
2336 provider: Option<Model<T>>,
2337 cx: &mut ViewContext<Self>,
2338 ) where
2339 T: InlineCompletionProvider,
2340 {
2341 self.inline_completion_provider =
2342 provider.map(|provider| RegisteredInlineCompletionProvider {
2343 _subscription: cx.observe(&provider, |this, _, cx| {
2344 if this.focus_handle.is_focused(cx) {
2345 this.update_visible_inline_completion(cx);
2346 }
2347 }),
2348 provider: Arc::new(provider),
2349 });
2350 self.refresh_inline_completion(false, false, cx);
2351 }
2352
2353 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2354 self.placeholder_text.as_deref()
2355 }
2356
2357 pub fn set_placeholder_text(
2358 &mut self,
2359 placeholder_text: impl Into<Arc<str>>,
2360 cx: &mut ViewContext<Self>,
2361 ) {
2362 let placeholder_text = Some(placeholder_text.into());
2363 if self.placeholder_text != placeholder_text {
2364 self.placeholder_text = placeholder_text;
2365 cx.notify();
2366 }
2367 }
2368
2369 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2370 self.cursor_shape = cursor_shape;
2371
2372 // Disrupt blink for immediate user feedback that the cursor shape has changed
2373 self.blink_manager.update(cx, BlinkManager::show_cursor);
2374
2375 cx.notify();
2376 }
2377
2378 pub fn set_current_line_highlight(
2379 &mut self,
2380 current_line_highlight: Option<CurrentLineHighlight>,
2381 ) {
2382 self.current_line_highlight = current_line_highlight;
2383 }
2384
2385 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2386 self.collapse_matches = collapse_matches;
2387 }
2388
2389 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2390 if self.collapse_matches {
2391 return range.start..range.start;
2392 }
2393 range.clone()
2394 }
2395
2396 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2397 if self.display_map.read(cx).clip_at_line_ends != clip {
2398 self.display_map
2399 .update(cx, |map, _| map.clip_at_line_ends = clip);
2400 }
2401 }
2402
2403 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2404 self.input_enabled = input_enabled;
2405 }
2406
2407 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2408 self.enable_inline_completions = enabled;
2409 }
2410
2411 pub fn set_autoindent(&mut self, autoindent: bool) {
2412 if autoindent {
2413 self.autoindent_mode = Some(AutoindentMode::EachLine);
2414 } else {
2415 self.autoindent_mode = None;
2416 }
2417 }
2418
2419 pub fn read_only(&self, cx: &AppContext) -> bool {
2420 self.read_only || self.buffer.read(cx).read_only()
2421 }
2422
2423 pub fn set_read_only(&mut self, read_only: bool) {
2424 self.read_only = read_only;
2425 }
2426
2427 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2428 self.use_autoclose = autoclose;
2429 }
2430
2431 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2432 self.use_auto_surround = auto_surround;
2433 }
2434
2435 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2436 self.auto_replace_emoji_shortcode = auto_replace;
2437 }
2438
2439 pub fn toggle_inline_completions(
2440 &mut self,
2441 _: &ToggleInlineCompletions,
2442 cx: &mut ViewContext<Self>,
2443 ) {
2444 if self.show_inline_completions_override.is_some() {
2445 self.set_show_inline_completions(None, cx);
2446 } else {
2447 let cursor = self.selections.newest_anchor().head();
2448 if let Some((buffer, cursor_buffer_position)) =
2449 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2450 {
2451 let show_inline_completions =
2452 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2453 self.set_show_inline_completions(Some(show_inline_completions), cx);
2454 }
2455 }
2456 }
2457
2458 pub fn set_show_inline_completions(
2459 &mut self,
2460 show_inline_completions: Option<bool>,
2461 cx: &mut ViewContext<Self>,
2462 ) {
2463 self.show_inline_completions_override = show_inline_completions;
2464 self.refresh_inline_completion(false, true, cx);
2465 }
2466
2467 fn should_show_inline_completions(
2468 &self,
2469 buffer: &Model<Buffer>,
2470 buffer_position: language::Anchor,
2471 cx: &AppContext,
2472 ) -> bool {
2473 if let Some(provider) = self.inline_completion_provider() {
2474 if let Some(show_inline_completions) = self.show_inline_completions_override {
2475 show_inline_completions
2476 } else {
2477 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2478 }
2479 } else {
2480 false
2481 }
2482 }
2483
2484 pub fn set_use_modal_editing(&mut self, to: bool) {
2485 self.use_modal_editing = to;
2486 }
2487
2488 pub fn use_modal_editing(&self) -> bool {
2489 self.use_modal_editing
2490 }
2491
2492 fn selections_did_change(
2493 &mut self,
2494 local: bool,
2495 old_cursor_position: &Anchor,
2496 show_completions: bool,
2497 cx: &mut ViewContext<Self>,
2498 ) {
2499 cx.invalidate_character_coordinates();
2500
2501 // Copy selections to primary selection buffer
2502 #[cfg(target_os = "linux")]
2503 if local {
2504 let selections = self.selections.all::<usize>(cx);
2505 let buffer_handle = self.buffer.read(cx).read(cx);
2506
2507 let mut text = String::new();
2508 for (index, selection) in selections.iter().enumerate() {
2509 let text_for_selection = buffer_handle
2510 .text_for_range(selection.start..selection.end)
2511 .collect::<String>();
2512
2513 text.push_str(&text_for_selection);
2514 if index != selections.len() - 1 {
2515 text.push('\n');
2516 }
2517 }
2518
2519 if !text.is_empty() {
2520 cx.write_to_primary(ClipboardItem::new_string(text));
2521 }
2522 }
2523
2524 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2525 self.buffer.update(cx, |buffer, cx| {
2526 buffer.set_active_selections(
2527 &self.selections.disjoint_anchors(),
2528 self.selections.line_mode,
2529 self.cursor_shape,
2530 cx,
2531 )
2532 });
2533 }
2534 let display_map = self
2535 .display_map
2536 .update(cx, |display_map, cx| display_map.snapshot(cx));
2537 let buffer = &display_map.buffer_snapshot;
2538 self.add_selections_state = None;
2539 self.select_next_state = None;
2540 self.select_prev_state = None;
2541 self.select_larger_syntax_node_stack.clear();
2542 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2543 self.snippet_stack
2544 .invalidate(&self.selections.disjoint_anchors(), buffer);
2545 self.take_rename(false, cx);
2546
2547 let new_cursor_position = self.selections.newest_anchor().head();
2548
2549 self.push_to_nav_history(
2550 *old_cursor_position,
2551 Some(new_cursor_position.to_point(buffer)),
2552 cx,
2553 );
2554
2555 if local {
2556 let new_cursor_position = self.selections.newest_anchor().head();
2557 let mut context_menu = self.context_menu.write();
2558 let completion_menu = match context_menu.as_ref() {
2559 Some(ContextMenu::Completions(menu)) => Some(menu),
2560
2561 _ => {
2562 *context_menu = None;
2563 None
2564 }
2565 };
2566
2567 if let Some(completion_menu) = completion_menu {
2568 let cursor_position = new_cursor_position.to_offset(buffer);
2569 let (word_range, kind) =
2570 buffer.surrounding_word(completion_menu.initial_position, true);
2571 if kind == Some(CharKind::Word)
2572 && word_range.to_inclusive().contains(&cursor_position)
2573 {
2574 let mut completion_menu = completion_menu.clone();
2575 drop(context_menu);
2576
2577 let query = Self::completion_query(buffer, cursor_position);
2578 cx.spawn(move |this, mut cx| async move {
2579 completion_menu
2580 .filter(query.as_deref(), cx.background_executor().clone())
2581 .await;
2582
2583 this.update(&mut cx, |this, cx| {
2584 let mut context_menu = this.context_menu.write();
2585 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2586 return;
2587 };
2588
2589 if menu.id > completion_menu.id {
2590 return;
2591 }
2592
2593 *context_menu = Some(ContextMenu::Completions(completion_menu));
2594 drop(context_menu);
2595 cx.notify();
2596 })
2597 })
2598 .detach();
2599
2600 if show_completions {
2601 self.show_completions(&ShowCompletions { trigger: None }, cx);
2602 }
2603 } else {
2604 drop(context_menu);
2605 self.hide_context_menu(cx);
2606 }
2607 } else {
2608 drop(context_menu);
2609 }
2610
2611 hide_hover(self, cx);
2612
2613 if old_cursor_position.to_display_point(&display_map).row()
2614 != new_cursor_position.to_display_point(&display_map).row()
2615 {
2616 self.available_code_actions.take();
2617 }
2618 self.refresh_code_actions(cx);
2619 self.refresh_document_highlights(cx);
2620 refresh_matching_bracket_highlights(self, cx);
2621 self.discard_inline_completion(false, cx);
2622 linked_editing_ranges::refresh_linked_ranges(self, cx);
2623 if self.git_blame_inline_enabled {
2624 self.start_inline_blame_timer(cx);
2625 }
2626 }
2627
2628 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2629 cx.emit(EditorEvent::SelectionsChanged { local });
2630
2631 if self.selections.disjoint_anchors().len() == 1 {
2632 cx.emit(SearchEvent::ActiveMatchChanged)
2633 }
2634 cx.notify();
2635 }
2636
2637 pub fn change_selections<R>(
2638 &mut self,
2639 autoscroll: Option<Autoscroll>,
2640 cx: &mut ViewContext<Self>,
2641 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2642 ) -> R {
2643 self.change_selections_inner(autoscroll, true, cx, change)
2644 }
2645
2646 pub fn change_selections_inner<R>(
2647 &mut self,
2648 autoscroll: Option<Autoscroll>,
2649 request_completions: bool,
2650 cx: &mut ViewContext<Self>,
2651 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2652 ) -> R {
2653 let old_cursor_position = self.selections.newest_anchor().head();
2654 self.push_to_selection_history();
2655
2656 let (changed, result) = self.selections.change_with(cx, change);
2657
2658 if changed {
2659 if let Some(autoscroll) = autoscroll {
2660 self.request_autoscroll(autoscroll, cx);
2661 }
2662 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2663
2664 if self.should_open_signature_help_automatically(
2665 &old_cursor_position,
2666 self.signature_help_state.backspace_pressed(),
2667 cx,
2668 ) {
2669 self.show_signature_help(&ShowSignatureHelp, cx);
2670 }
2671 self.signature_help_state.set_backspace_pressed(false);
2672 }
2673
2674 result
2675 }
2676
2677 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2678 where
2679 I: IntoIterator<Item = (Range<S>, T)>,
2680 S: ToOffset,
2681 T: Into<Arc<str>>,
2682 {
2683 if self.read_only(cx) {
2684 return;
2685 }
2686
2687 self.buffer
2688 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2689 }
2690
2691 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2692 where
2693 I: IntoIterator<Item = (Range<S>, T)>,
2694 S: ToOffset,
2695 T: Into<Arc<str>>,
2696 {
2697 if self.read_only(cx) {
2698 return;
2699 }
2700
2701 self.buffer.update(cx, |buffer, cx| {
2702 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2703 });
2704 }
2705
2706 pub fn edit_with_block_indent<I, S, T>(
2707 &mut self,
2708 edits: I,
2709 original_indent_columns: Vec<u32>,
2710 cx: &mut ViewContext<Self>,
2711 ) where
2712 I: IntoIterator<Item = (Range<S>, T)>,
2713 S: ToOffset,
2714 T: Into<Arc<str>>,
2715 {
2716 if self.read_only(cx) {
2717 return;
2718 }
2719
2720 self.buffer.update(cx, |buffer, cx| {
2721 buffer.edit(
2722 edits,
2723 Some(AutoindentMode::Block {
2724 original_indent_columns,
2725 }),
2726 cx,
2727 )
2728 });
2729 }
2730
2731 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2732 self.hide_context_menu(cx);
2733
2734 match phase {
2735 SelectPhase::Begin {
2736 position,
2737 add,
2738 click_count,
2739 } => self.begin_selection(position, add, click_count, cx),
2740 SelectPhase::BeginColumnar {
2741 position,
2742 goal_column,
2743 reset,
2744 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2745 SelectPhase::Extend {
2746 position,
2747 click_count,
2748 } => self.extend_selection(position, click_count, cx),
2749 SelectPhase::Update {
2750 position,
2751 goal_column,
2752 scroll_delta,
2753 } => self.update_selection(position, goal_column, scroll_delta, cx),
2754 SelectPhase::End => self.end_selection(cx),
2755 }
2756 }
2757
2758 fn extend_selection(
2759 &mut self,
2760 position: DisplayPoint,
2761 click_count: usize,
2762 cx: &mut ViewContext<Self>,
2763 ) {
2764 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2765 let tail = self.selections.newest::<usize>(cx).tail();
2766 self.begin_selection(position, false, click_count, cx);
2767
2768 let position = position.to_offset(&display_map, Bias::Left);
2769 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2770
2771 let mut pending_selection = self
2772 .selections
2773 .pending_anchor()
2774 .expect("extend_selection not called with pending selection");
2775 if position >= tail {
2776 pending_selection.start = tail_anchor;
2777 } else {
2778 pending_selection.end = tail_anchor;
2779 pending_selection.reversed = true;
2780 }
2781
2782 let mut pending_mode = self.selections.pending_mode().unwrap();
2783 match &mut pending_mode {
2784 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2785 _ => {}
2786 }
2787
2788 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2789 s.set_pending(pending_selection, pending_mode)
2790 });
2791 }
2792
2793 fn begin_selection(
2794 &mut self,
2795 position: DisplayPoint,
2796 add: bool,
2797 click_count: usize,
2798 cx: &mut ViewContext<Self>,
2799 ) {
2800 if !self.focus_handle.is_focused(cx) {
2801 self.last_focused_descendant = None;
2802 cx.focus(&self.focus_handle);
2803 }
2804
2805 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2806 let buffer = &display_map.buffer_snapshot;
2807 let newest_selection = self.selections.newest_anchor().clone();
2808 let position = display_map.clip_point(position, Bias::Left);
2809
2810 let start;
2811 let end;
2812 let mode;
2813 let auto_scroll;
2814 match click_count {
2815 1 => {
2816 start = buffer.anchor_before(position.to_point(&display_map));
2817 end = start;
2818 mode = SelectMode::Character;
2819 auto_scroll = true;
2820 }
2821 2 => {
2822 let range = movement::surrounding_word(&display_map, position);
2823 start = buffer.anchor_before(range.start.to_point(&display_map));
2824 end = buffer.anchor_before(range.end.to_point(&display_map));
2825 mode = SelectMode::Word(start..end);
2826 auto_scroll = true;
2827 }
2828 3 => {
2829 let position = display_map
2830 .clip_point(position, Bias::Left)
2831 .to_point(&display_map);
2832 let line_start = display_map.prev_line_boundary(position).0;
2833 let next_line_start = buffer.clip_point(
2834 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2835 Bias::Left,
2836 );
2837 start = buffer.anchor_before(line_start);
2838 end = buffer.anchor_before(next_line_start);
2839 mode = SelectMode::Line(start..end);
2840 auto_scroll = true;
2841 }
2842 _ => {
2843 start = buffer.anchor_before(0);
2844 end = buffer.anchor_before(buffer.len());
2845 mode = SelectMode::All;
2846 auto_scroll = false;
2847 }
2848 }
2849
2850 let point_to_delete: Option<usize> = {
2851 let selected_points: Vec<Selection<Point>> =
2852 self.selections.disjoint_in_range(start..end, cx);
2853
2854 if !add || click_count > 1 {
2855 None
2856 } else if !selected_points.is_empty() {
2857 Some(selected_points[0].id)
2858 } else {
2859 let clicked_point_already_selected =
2860 self.selections.disjoint.iter().find(|selection| {
2861 selection.start.to_point(buffer) == start.to_point(buffer)
2862 || selection.end.to_point(buffer) == end.to_point(buffer)
2863 });
2864
2865 clicked_point_already_selected.map(|selection| selection.id)
2866 }
2867 };
2868
2869 let selections_count = self.selections.count();
2870
2871 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2872 if let Some(point_to_delete) = point_to_delete {
2873 s.delete(point_to_delete);
2874
2875 if selections_count == 1 {
2876 s.set_pending_anchor_range(start..end, mode);
2877 }
2878 } else {
2879 if !add {
2880 s.clear_disjoint();
2881 } else if click_count > 1 {
2882 s.delete(newest_selection.id)
2883 }
2884
2885 s.set_pending_anchor_range(start..end, mode);
2886 }
2887 });
2888 }
2889
2890 fn begin_columnar_selection(
2891 &mut self,
2892 position: DisplayPoint,
2893 goal_column: u32,
2894 reset: bool,
2895 cx: &mut ViewContext<Self>,
2896 ) {
2897 if !self.focus_handle.is_focused(cx) {
2898 self.last_focused_descendant = None;
2899 cx.focus(&self.focus_handle);
2900 }
2901
2902 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2903
2904 if reset {
2905 let pointer_position = display_map
2906 .buffer_snapshot
2907 .anchor_before(position.to_point(&display_map));
2908
2909 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2910 s.clear_disjoint();
2911 s.set_pending_anchor_range(
2912 pointer_position..pointer_position,
2913 SelectMode::Character,
2914 );
2915 });
2916 }
2917
2918 let tail = self.selections.newest::<Point>(cx).tail();
2919 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2920
2921 if !reset {
2922 self.select_columns(
2923 tail.to_display_point(&display_map),
2924 position,
2925 goal_column,
2926 &display_map,
2927 cx,
2928 );
2929 }
2930 }
2931
2932 fn update_selection(
2933 &mut self,
2934 position: DisplayPoint,
2935 goal_column: u32,
2936 scroll_delta: gpui::Point<f32>,
2937 cx: &mut ViewContext<Self>,
2938 ) {
2939 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2940
2941 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2942 let tail = tail.to_display_point(&display_map);
2943 self.select_columns(tail, position, goal_column, &display_map, cx);
2944 } else if let Some(mut pending) = self.selections.pending_anchor() {
2945 let buffer = self.buffer.read(cx).snapshot(cx);
2946 let head;
2947 let tail;
2948 let mode = self.selections.pending_mode().unwrap();
2949 match &mode {
2950 SelectMode::Character => {
2951 head = position.to_point(&display_map);
2952 tail = pending.tail().to_point(&buffer);
2953 }
2954 SelectMode::Word(original_range) => {
2955 let original_display_range = original_range.start.to_display_point(&display_map)
2956 ..original_range.end.to_display_point(&display_map);
2957 let original_buffer_range = original_display_range.start.to_point(&display_map)
2958 ..original_display_range.end.to_point(&display_map);
2959 if movement::is_inside_word(&display_map, position)
2960 || original_display_range.contains(&position)
2961 {
2962 let word_range = movement::surrounding_word(&display_map, position);
2963 if word_range.start < original_display_range.start {
2964 head = word_range.start.to_point(&display_map);
2965 } else {
2966 head = word_range.end.to_point(&display_map);
2967 }
2968 } else {
2969 head = position.to_point(&display_map);
2970 }
2971
2972 if head <= original_buffer_range.start {
2973 tail = original_buffer_range.end;
2974 } else {
2975 tail = original_buffer_range.start;
2976 }
2977 }
2978 SelectMode::Line(original_range) => {
2979 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2980
2981 let position = display_map
2982 .clip_point(position, Bias::Left)
2983 .to_point(&display_map);
2984 let line_start = display_map.prev_line_boundary(position).0;
2985 let next_line_start = buffer.clip_point(
2986 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2987 Bias::Left,
2988 );
2989
2990 if line_start < original_range.start {
2991 head = line_start
2992 } else {
2993 head = next_line_start
2994 }
2995
2996 if head <= original_range.start {
2997 tail = original_range.end;
2998 } else {
2999 tail = original_range.start;
3000 }
3001 }
3002 SelectMode::All => {
3003 return;
3004 }
3005 };
3006
3007 if head < tail {
3008 pending.start = buffer.anchor_before(head);
3009 pending.end = buffer.anchor_before(tail);
3010 pending.reversed = true;
3011 } else {
3012 pending.start = buffer.anchor_before(tail);
3013 pending.end = buffer.anchor_before(head);
3014 pending.reversed = false;
3015 }
3016
3017 self.change_selections(None, cx, |s| {
3018 s.set_pending(pending, mode);
3019 });
3020 } else {
3021 log::error!("update_selection dispatched with no pending selection");
3022 return;
3023 }
3024
3025 self.apply_scroll_delta(scroll_delta, cx);
3026 cx.notify();
3027 }
3028
3029 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3030 self.columnar_selection_tail.take();
3031 if self.selections.pending_anchor().is_some() {
3032 let selections = self.selections.all::<usize>(cx);
3033 self.change_selections(None, cx, |s| {
3034 s.select(selections);
3035 s.clear_pending();
3036 });
3037 }
3038 }
3039
3040 fn select_columns(
3041 &mut self,
3042 tail: DisplayPoint,
3043 head: DisplayPoint,
3044 goal_column: u32,
3045 display_map: &DisplaySnapshot,
3046 cx: &mut ViewContext<Self>,
3047 ) {
3048 let start_row = cmp::min(tail.row(), head.row());
3049 let end_row = cmp::max(tail.row(), head.row());
3050 let start_column = cmp::min(tail.column(), goal_column);
3051 let end_column = cmp::max(tail.column(), goal_column);
3052 let reversed = start_column < tail.column();
3053
3054 let selection_ranges = (start_row.0..=end_row.0)
3055 .map(DisplayRow)
3056 .filter_map(|row| {
3057 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3058 let start = display_map
3059 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3060 .to_point(display_map);
3061 let end = display_map
3062 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3063 .to_point(display_map);
3064 if reversed {
3065 Some(end..start)
3066 } else {
3067 Some(start..end)
3068 }
3069 } else {
3070 None
3071 }
3072 })
3073 .collect::<Vec<_>>();
3074
3075 self.change_selections(None, cx, |s| {
3076 s.select_ranges(selection_ranges);
3077 });
3078 cx.notify();
3079 }
3080
3081 pub fn has_pending_nonempty_selection(&self) -> bool {
3082 let pending_nonempty_selection = match self.selections.pending_anchor() {
3083 Some(Selection { start, end, .. }) => start != end,
3084 None => false,
3085 };
3086
3087 pending_nonempty_selection
3088 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3089 }
3090
3091 pub fn has_pending_selection(&self) -> bool {
3092 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3093 }
3094
3095 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3096 if self.clear_expanded_diff_hunks(cx) {
3097 cx.notify();
3098 return;
3099 }
3100 if self.dismiss_menus_and_popups(true, cx) {
3101 return;
3102 }
3103
3104 if self.mode == EditorMode::Full
3105 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3106 {
3107 return;
3108 }
3109
3110 cx.propagate();
3111 }
3112
3113 pub fn dismiss_menus_and_popups(
3114 &mut self,
3115 should_report_inline_completion_event: bool,
3116 cx: &mut ViewContext<Self>,
3117 ) -> bool {
3118 if self.take_rename(false, cx).is_some() {
3119 return true;
3120 }
3121
3122 if hide_hover(self, cx) {
3123 return true;
3124 }
3125
3126 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3127 return true;
3128 }
3129
3130 if self.hide_context_menu(cx).is_some() {
3131 return true;
3132 }
3133
3134 if self.mouse_context_menu.take().is_some() {
3135 return true;
3136 }
3137
3138 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3139 return true;
3140 }
3141
3142 if self.snippet_stack.pop().is_some() {
3143 return true;
3144 }
3145
3146 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3147 self.dismiss_diagnostics(cx);
3148 return true;
3149 }
3150
3151 false
3152 }
3153
3154 fn linked_editing_ranges_for(
3155 &self,
3156 selection: Range<text::Anchor>,
3157 cx: &AppContext,
3158 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3159 if self.linked_edit_ranges.is_empty() {
3160 return None;
3161 }
3162 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3163 selection.end.buffer_id.and_then(|end_buffer_id| {
3164 if selection.start.buffer_id != Some(end_buffer_id) {
3165 return None;
3166 }
3167 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3168 let snapshot = buffer.read(cx).snapshot();
3169 self.linked_edit_ranges
3170 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3171 .map(|ranges| (ranges, snapshot, buffer))
3172 })?;
3173 use text::ToOffset as TO;
3174 // find offset from the start of current range to current cursor position
3175 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3176
3177 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3178 let start_difference = start_offset - start_byte_offset;
3179 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3180 let end_difference = end_offset - start_byte_offset;
3181 // Current range has associated linked ranges.
3182 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3183 for range in linked_ranges.iter() {
3184 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3185 let end_offset = start_offset + end_difference;
3186 let start_offset = start_offset + start_difference;
3187 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3188 continue;
3189 }
3190 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3191 if s.start.buffer_id != selection.start.buffer_id
3192 || s.end.buffer_id != selection.end.buffer_id
3193 {
3194 return false;
3195 }
3196 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3197 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3198 }) {
3199 continue;
3200 }
3201 let start = buffer_snapshot.anchor_after(start_offset);
3202 let end = buffer_snapshot.anchor_after(end_offset);
3203 linked_edits
3204 .entry(buffer.clone())
3205 .or_default()
3206 .push(start..end);
3207 }
3208 Some(linked_edits)
3209 }
3210
3211 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3212 let text: Arc<str> = text.into();
3213
3214 if self.read_only(cx) {
3215 return;
3216 }
3217
3218 let selections = self.selections.all_adjusted(cx);
3219 let mut bracket_inserted = false;
3220 let mut edits = Vec::new();
3221 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3222 let mut new_selections = Vec::with_capacity(selections.len());
3223 let mut new_autoclose_regions = Vec::new();
3224 let snapshot = self.buffer.read(cx).read(cx);
3225
3226 for (selection, autoclose_region) in
3227 self.selections_with_autoclose_regions(selections, &snapshot)
3228 {
3229 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3230 // Determine if the inserted text matches the opening or closing
3231 // bracket of any of this language's bracket pairs.
3232 let mut bracket_pair = None;
3233 let mut is_bracket_pair_start = false;
3234 let mut is_bracket_pair_end = false;
3235 if !text.is_empty() {
3236 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3237 // and they are removing the character that triggered IME popup.
3238 for (pair, enabled) in scope.brackets() {
3239 if !pair.close && !pair.surround {
3240 continue;
3241 }
3242
3243 if enabled && pair.start.ends_with(text.as_ref()) {
3244 bracket_pair = Some(pair.clone());
3245 is_bracket_pair_start = true;
3246 break;
3247 }
3248 if pair.end.as_str() == text.as_ref() {
3249 bracket_pair = Some(pair.clone());
3250 is_bracket_pair_end = true;
3251 break;
3252 }
3253 }
3254 }
3255
3256 if let Some(bracket_pair) = bracket_pair {
3257 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3258 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3259 let auto_surround =
3260 self.use_auto_surround && snapshot_settings.use_auto_surround;
3261 if selection.is_empty() {
3262 if is_bracket_pair_start {
3263 let prefix_len = bracket_pair.start.len() - text.len();
3264
3265 // If the inserted text is a suffix of an opening bracket and the
3266 // selection is preceded by the rest of the opening bracket, then
3267 // insert the closing bracket.
3268 let following_text_allows_autoclose = snapshot
3269 .chars_at(selection.start)
3270 .next()
3271 .map_or(true, |c| scope.should_autoclose_before(c));
3272 let preceding_text_matches_prefix = prefix_len == 0
3273 || (selection.start.column >= (prefix_len as u32)
3274 && snapshot.contains_str_at(
3275 Point::new(
3276 selection.start.row,
3277 selection.start.column - (prefix_len as u32),
3278 ),
3279 &bracket_pair.start[..prefix_len],
3280 ));
3281
3282 if autoclose
3283 && bracket_pair.close
3284 && following_text_allows_autoclose
3285 && preceding_text_matches_prefix
3286 {
3287 let anchor = snapshot.anchor_before(selection.end);
3288 new_selections.push((selection.map(|_| anchor), text.len()));
3289 new_autoclose_regions.push((
3290 anchor,
3291 text.len(),
3292 selection.id,
3293 bracket_pair.clone(),
3294 ));
3295 edits.push((
3296 selection.range(),
3297 format!("{}{}", text, bracket_pair.end).into(),
3298 ));
3299 bracket_inserted = true;
3300 continue;
3301 }
3302 }
3303
3304 if let Some(region) = autoclose_region {
3305 // If the selection is followed by an auto-inserted closing bracket,
3306 // then don't insert that closing bracket again; just move the selection
3307 // past the closing bracket.
3308 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3309 && text.as_ref() == region.pair.end.as_str();
3310 if should_skip {
3311 let anchor = snapshot.anchor_after(selection.end);
3312 new_selections
3313 .push((selection.map(|_| anchor), region.pair.end.len()));
3314 continue;
3315 }
3316 }
3317
3318 let always_treat_brackets_as_autoclosed = snapshot
3319 .settings_at(selection.start, cx)
3320 .always_treat_brackets_as_autoclosed;
3321 if always_treat_brackets_as_autoclosed
3322 && is_bracket_pair_end
3323 && snapshot.contains_str_at(selection.end, text.as_ref())
3324 {
3325 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3326 // and the inserted text is a closing bracket and the selection is followed
3327 // by the closing bracket then move the selection past the closing bracket.
3328 let anchor = snapshot.anchor_after(selection.end);
3329 new_selections.push((selection.map(|_| anchor), text.len()));
3330 continue;
3331 }
3332 }
3333 // If an opening bracket is 1 character long and is typed while
3334 // text is selected, then surround that text with the bracket pair.
3335 else if auto_surround
3336 && bracket_pair.surround
3337 && is_bracket_pair_start
3338 && bracket_pair.start.chars().count() == 1
3339 {
3340 edits.push((selection.start..selection.start, text.clone()));
3341 edits.push((
3342 selection.end..selection.end,
3343 bracket_pair.end.as_str().into(),
3344 ));
3345 bracket_inserted = true;
3346 new_selections.push((
3347 Selection {
3348 id: selection.id,
3349 start: snapshot.anchor_after(selection.start),
3350 end: snapshot.anchor_before(selection.end),
3351 reversed: selection.reversed,
3352 goal: selection.goal,
3353 },
3354 0,
3355 ));
3356 continue;
3357 }
3358 }
3359 }
3360
3361 if self.auto_replace_emoji_shortcode
3362 && selection.is_empty()
3363 && text.as_ref().ends_with(':')
3364 {
3365 if let Some(possible_emoji_short_code) =
3366 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3367 {
3368 if !possible_emoji_short_code.is_empty() {
3369 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3370 let emoji_shortcode_start = Point::new(
3371 selection.start.row,
3372 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3373 );
3374
3375 // Remove shortcode from buffer
3376 edits.push((
3377 emoji_shortcode_start..selection.start,
3378 "".to_string().into(),
3379 ));
3380 new_selections.push((
3381 Selection {
3382 id: selection.id,
3383 start: snapshot.anchor_after(emoji_shortcode_start),
3384 end: snapshot.anchor_before(selection.start),
3385 reversed: selection.reversed,
3386 goal: selection.goal,
3387 },
3388 0,
3389 ));
3390
3391 // Insert emoji
3392 let selection_start_anchor = snapshot.anchor_after(selection.start);
3393 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3394 edits.push((selection.start..selection.end, emoji.to_string().into()));
3395
3396 continue;
3397 }
3398 }
3399 }
3400 }
3401
3402 // If not handling any auto-close operation, then just replace the selected
3403 // text with the given input and move the selection to the end of the
3404 // newly inserted text.
3405 let anchor = snapshot.anchor_after(selection.end);
3406 if !self.linked_edit_ranges.is_empty() {
3407 let start_anchor = snapshot.anchor_before(selection.start);
3408
3409 let is_word_char = text.chars().next().map_or(true, |char| {
3410 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3411 classifier.is_word(char)
3412 });
3413
3414 if is_word_char {
3415 if let Some(ranges) = self
3416 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3417 {
3418 for (buffer, edits) in ranges {
3419 linked_edits
3420 .entry(buffer.clone())
3421 .or_default()
3422 .extend(edits.into_iter().map(|range| (range, text.clone())));
3423 }
3424 }
3425 }
3426 }
3427
3428 new_selections.push((selection.map(|_| anchor), 0));
3429 edits.push((selection.start..selection.end, text.clone()));
3430 }
3431
3432 drop(snapshot);
3433
3434 self.transact(cx, |this, cx| {
3435 this.buffer.update(cx, |buffer, cx| {
3436 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3437 });
3438 for (buffer, edits) in linked_edits {
3439 buffer.update(cx, |buffer, cx| {
3440 let snapshot = buffer.snapshot();
3441 let edits = edits
3442 .into_iter()
3443 .map(|(range, text)| {
3444 use text::ToPoint as TP;
3445 let end_point = TP::to_point(&range.end, &snapshot);
3446 let start_point = TP::to_point(&range.start, &snapshot);
3447 (start_point..end_point, text)
3448 })
3449 .sorted_by_key(|(range, _)| range.start)
3450 .collect::<Vec<_>>();
3451 buffer.edit(edits, None, cx);
3452 })
3453 }
3454 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3455 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3456 let snapshot = this.buffer.read(cx).read(cx);
3457 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3458 .zip(new_selection_deltas)
3459 .map(|(selection, delta)| Selection {
3460 id: selection.id,
3461 start: selection.start + delta,
3462 end: selection.end + delta,
3463 reversed: selection.reversed,
3464 goal: SelectionGoal::None,
3465 })
3466 .collect::<Vec<_>>();
3467
3468 let mut i = 0;
3469 for (position, delta, selection_id, pair) in new_autoclose_regions {
3470 let position = position.to_offset(&snapshot) + delta;
3471 let start = snapshot.anchor_before(position);
3472 let end = snapshot.anchor_after(position);
3473 while let Some(existing_state) = this.autoclose_regions.get(i) {
3474 match existing_state.range.start.cmp(&start, &snapshot) {
3475 Ordering::Less => i += 1,
3476 Ordering::Greater => break,
3477 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3478 Ordering::Less => i += 1,
3479 Ordering::Equal => break,
3480 Ordering::Greater => break,
3481 },
3482 }
3483 }
3484 this.autoclose_regions.insert(
3485 i,
3486 AutocloseRegion {
3487 selection_id,
3488 range: start..end,
3489 pair,
3490 },
3491 );
3492 }
3493
3494 drop(snapshot);
3495 let had_active_inline_completion = this.has_active_inline_completion(cx);
3496 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3497 s.select(new_selections)
3498 });
3499
3500 if !bracket_inserted {
3501 if let Some(on_type_format_task) =
3502 this.trigger_on_type_formatting(text.to_string(), cx)
3503 {
3504 on_type_format_task.detach_and_log_err(cx);
3505 }
3506 }
3507
3508 let editor_settings = EditorSettings::get_global(cx);
3509 if bracket_inserted
3510 && (editor_settings.auto_signature_help
3511 || editor_settings.show_signature_help_after_edits)
3512 {
3513 this.show_signature_help(&ShowSignatureHelp, cx);
3514 }
3515
3516 let trigger_in_words = !had_active_inline_completion;
3517 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3518 linked_editing_ranges::refresh_linked_ranges(this, cx);
3519 this.refresh_inline_completion(true, false, cx);
3520 });
3521 }
3522
3523 fn find_possible_emoji_shortcode_at_position(
3524 snapshot: &MultiBufferSnapshot,
3525 position: Point,
3526 ) -> Option<String> {
3527 let mut chars = Vec::new();
3528 let mut found_colon = false;
3529 for char in snapshot.reversed_chars_at(position).take(100) {
3530 // Found a possible emoji shortcode in the middle of the buffer
3531 if found_colon {
3532 if char.is_whitespace() {
3533 chars.reverse();
3534 return Some(chars.iter().collect());
3535 }
3536 // If the previous character is not a whitespace, we are in the middle of a word
3537 // and we only want to complete the shortcode if the word is made up of other emojis
3538 let mut containing_word = String::new();
3539 for ch in snapshot
3540 .reversed_chars_at(position)
3541 .skip(chars.len() + 1)
3542 .take(100)
3543 {
3544 if ch.is_whitespace() {
3545 break;
3546 }
3547 containing_word.push(ch);
3548 }
3549 let containing_word = containing_word.chars().rev().collect::<String>();
3550 if util::word_consists_of_emojis(containing_word.as_str()) {
3551 chars.reverse();
3552 return Some(chars.iter().collect());
3553 }
3554 }
3555
3556 if char.is_whitespace() || !char.is_ascii() {
3557 return None;
3558 }
3559 if char == ':' {
3560 found_colon = true;
3561 } else {
3562 chars.push(char);
3563 }
3564 }
3565 // Found a possible emoji shortcode at the beginning of the buffer
3566 chars.reverse();
3567 Some(chars.iter().collect())
3568 }
3569
3570 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3571 self.transact(cx, |this, cx| {
3572 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3573 let selections = this.selections.all::<usize>(cx);
3574 let multi_buffer = this.buffer.read(cx);
3575 let buffer = multi_buffer.snapshot(cx);
3576 selections
3577 .iter()
3578 .map(|selection| {
3579 let start_point = selection.start.to_point(&buffer);
3580 let mut indent =
3581 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3582 indent.len = cmp::min(indent.len, start_point.column);
3583 let start = selection.start;
3584 let end = selection.end;
3585 let selection_is_empty = start == end;
3586 let language_scope = buffer.language_scope_at(start);
3587 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3588 &language_scope
3589 {
3590 let leading_whitespace_len = buffer
3591 .reversed_chars_at(start)
3592 .take_while(|c| c.is_whitespace() && *c != '\n')
3593 .map(|c| c.len_utf8())
3594 .sum::<usize>();
3595
3596 let trailing_whitespace_len = buffer
3597 .chars_at(end)
3598 .take_while(|c| c.is_whitespace() && *c != '\n')
3599 .map(|c| c.len_utf8())
3600 .sum::<usize>();
3601
3602 let insert_extra_newline =
3603 language.brackets().any(|(pair, enabled)| {
3604 let pair_start = pair.start.trim_end();
3605 let pair_end = pair.end.trim_start();
3606
3607 enabled
3608 && pair.newline
3609 && buffer.contains_str_at(
3610 end + trailing_whitespace_len,
3611 pair_end,
3612 )
3613 && buffer.contains_str_at(
3614 (start - leading_whitespace_len)
3615 .saturating_sub(pair_start.len()),
3616 pair_start,
3617 )
3618 });
3619
3620 // Comment extension on newline is allowed only for cursor selections
3621 let comment_delimiter = maybe!({
3622 if !selection_is_empty {
3623 return None;
3624 }
3625
3626 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3627 return None;
3628 }
3629
3630 let delimiters = language.line_comment_prefixes();
3631 let max_len_of_delimiter =
3632 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3633 let (snapshot, range) =
3634 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3635
3636 let mut index_of_first_non_whitespace = 0;
3637 let comment_candidate = snapshot
3638 .chars_for_range(range)
3639 .skip_while(|c| {
3640 let should_skip = c.is_whitespace();
3641 if should_skip {
3642 index_of_first_non_whitespace += 1;
3643 }
3644 should_skip
3645 })
3646 .take(max_len_of_delimiter)
3647 .collect::<String>();
3648 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3649 comment_candidate.starts_with(comment_prefix.as_ref())
3650 })?;
3651 let cursor_is_placed_after_comment_marker =
3652 index_of_first_non_whitespace + comment_prefix.len()
3653 <= start_point.column as usize;
3654 if cursor_is_placed_after_comment_marker {
3655 Some(comment_prefix.clone())
3656 } else {
3657 None
3658 }
3659 });
3660 (comment_delimiter, insert_extra_newline)
3661 } else {
3662 (None, false)
3663 };
3664
3665 let capacity_for_delimiter = comment_delimiter
3666 .as_deref()
3667 .map(str::len)
3668 .unwrap_or_default();
3669 let mut new_text =
3670 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3671 new_text.push('\n');
3672 new_text.extend(indent.chars());
3673 if let Some(delimiter) = &comment_delimiter {
3674 new_text.push_str(delimiter);
3675 }
3676 if insert_extra_newline {
3677 new_text = new_text.repeat(2);
3678 }
3679
3680 let anchor = buffer.anchor_after(end);
3681 let new_selection = selection.map(|_| anchor);
3682 (
3683 (start..end, new_text),
3684 (insert_extra_newline, new_selection),
3685 )
3686 })
3687 .unzip()
3688 };
3689
3690 this.edit_with_autoindent(edits, cx);
3691 let buffer = this.buffer.read(cx).snapshot(cx);
3692 let new_selections = selection_fixup_info
3693 .into_iter()
3694 .map(|(extra_newline_inserted, new_selection)| {
3695 let mut cursor = new_selection.end.to_point(&buffer);
3696 if extra_newline_inserted {
3697 cursor.row -= 1;
3698 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3699 }
3700 new_selection.map(|_| cursor)
3701 })
3702 .collect();
3703
3704 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3705 this.refresh_inline_completion(true, false, cx);
3706 });
3707 }
3708
3709 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3710 let buffer = self.buffer.read(cx);
3711 let snapshot = buffer.snapshot(cx);
3712
3713 let mut edits = Vec::new();
3714 let mut rows = Vec::new();
3715
3716 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3717 let cursor = selection.head();
3718 let row = cursor.row;
3719
3720 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3721
3722 let newline = "\n".to_string();
3723 edits.push((start_of_line..start_of_line, newline));
3724
3725 rows.push(row + rows_inserted as u32);
3726 }
3727
3728 self.transact(cx, |editor, cx| {
3729 editor.edit(edits, cx);
3730
3731 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3732 let mut index = 0;
3733 s.move_cursors_with(|map, _, _| {
3734 let row = rows[index];
3735 index += 1;
3736
3737 let point = Point::new(row, 0);
3738 let boundary = map.next_line_boundary(point).1;
3739 let clipped = map.clip_point(boundary, Bias::Left);
3740
3741 (clipped, SelectionGoal::None)
3742 });
3743 });
3744
3745 let mut indent_edits = Vec::new();
3746 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3747 for row in rows {
3748 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3749 for (row, indent) in indents {
3750 if indent.len == 0 {
3751 continue;
3752 }
3753
3754 let text = match indent.kind {
3755 IndentKind::Space => " ".repeat(indent.len as usize),
3756 IndentKind::Tab => "\t".repeat(indent.len as usize),
3757 };
3758 let point = Point::new(row.0, 0);
3759 indent_edits.push((point..point, text));
3760 }
3761 }
3762 editor.edit(indent_edits, cx);
3763 });
3764 }
3765
3766 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3767 let buffer = self.buffer.read(cx);
3768 let snapshot = buffer.snapshot(cx);
3769
3770 let mut edits = Vec::new();
3771 let mut rows = Vec::new();
3772 let mut rows_inserted = 0;
3773
3774 for selection in self.selections.all_adjusted(cx) {
3775 let cursor = selection.head();
3776 let row = cursor.row;
3777
3778 let point = Point::new(row + 1, 0);
3779 let start_of_line = snapshot.clip_point(point, Bias::Left);
3780
3781 let newline = "\n".to_string();
3782 edits.push((start_of_line..start_of_line, newline));
3783
3784 rows_inserted += 1;
3785 rows.push(row + rows_inserted);
3786 }
3787
3788 self.transact(cx, |editor, cx| {
3789 editor.edit(edits, cx);
3790
3791 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3792 let mut index = 0;
3793 s.move_cursors_with(|map, _, _| {
3794 let row = rows[index];
3795 index += 1;
3796
3797 let point = Point::new(row, 0);
3798 let boundary = map.next_line_boundary(point).1;
3799 let clipped = map.clip_point(boundary, Bias::Left);
3800
3801 (clipped, SelectionGoal::None)
3802 });
3803 });
3804
3805 let mut indent_edits = Vec::new();
3806 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3807 for row in rows {
3808 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3809 for (row, indent) in indents {
3810 if indent.len == 0 {
3811 continue;
3812 }
3813
3814 let text = match indent.kind {
3815 IndentKind::Space => " ".repeat(indent.len as usize),
3816 IndentKind::Tab => "\t".repeat(indent.len as usize),
3817 };
3818 let point = Point::new(row.0, 0);
3819 indent_edits.push((point..point, text));
3820 }
3821 }
3822 editor.edit(indent_edits, cx);
3823 });
3824 }
3825
3826 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3827 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3828 original_indent_columns: Vec::new(),
3829 });
3830 self.insert_with_autoindent_mode(text, autoindent, cx);
3831 }
3832
3833 fn insert_with_autoindent_mode(
3834 &mut self,
3835 text: &str,
3836 autoindent_mode: Option<AutoindentMode>,
3837 cx: &mut ViewContext<Self>,
3838 ) {
3839 if self.read_only(cx) {
3840 return;
3841 }
3842
3843 let text: Arc<str> = text.into();
3844 self.transact(cx, |this, cx| {
3845 let old_selections = this.selections.all_adjusted(cx);
3846 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3847 let anchors = {
3848 let snapshot = buffer.read(cx);
3849 old_selections
3850 .iter()
3851 .map(|s| {
3852 let anchor = snapshot.anchor_after(s.head());
3853 s.map(|_| anchor)
3854 })
3855 .collect::<Vec<_>>()
3856 };
3857 buffer.edit(
3858 old_selections
3859 .iter()
3860 .map(|s| (s.start..s.end, text.clone())),
3861 autoindent_mode,
3862 cx,
3863 );
3864 anchors
3865 });
3866
3867 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3868 s.select_anchors(selection_anchors);
3869 })
3870 });
3871 }
3872
3873 fn trigger_completion_on_input(
3874 &mut self,
3875 text: &str,
3876 trigger_in_words: bool,
3877 cx: &mut ViewContext<Self>,
3878 ) {
3879 if self.is_completion_trigger(text, trigger_in_words, cx) {
3880 self.show_completions(
3881 &ShowCompletions {
3882 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3883 },
3884 cx,
3885 );
3886 } else {
3887 self.hide_context_menu(cx);
3888 }
3889 }
3890
3891 fn is_completion_trigger(
3892 &self,
3893 text: &str,
3894 trigger_in_words: bool,
3895 cx: &mut ViewContext<Self>,
3896 ) -> bool {
3897 let position = self.selections.newest_anchor().head();
3898 let multibuffer = self.buffer.read(cx);
3899 let Some(buffer) = position
3900 .buffer_id
3901 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3902 else {
3903 return false;
3904 };
3905
3906 if let Some(completion_provider) = &self.completion_provider {
3907 completion_provider.is_completion_trigger(
3908 &buffer,
3909 position.text_anchor,
3910 text,
3911 trigger_in_words,
3912 cx,
3913 )
3914 } else {
3915 false
3916 }
3917 }
3918
3919 /// If any empty selections is touching the start of its innermost containing autoclose
3920 /// region, expand it to select the brackets.
3921 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3922 let selections = self.selections.all::<usize>(cx);
3923 let buffer = self.buffer.read(cx).read(cx);
3924 let new_selections = self
3925 .selections_with_autoclose_regions(selections, &buffer)
3926 .map(|(mut selection, region)| {
3927 if !selection.is_empty() {
3928 return selection;
3929 }
3930
3931 if let Some(region) = region {
3932 let mut range = region.range.to_offset(&buffer);
3933 if selection.start == range.start && range.start >= region.pair.start.len() {
3934 range.start -= region.pair.start.len();
3935 if buffer.contains_str_at(range.start, ®ion.pair.start)
3936 && buffer.contains_str_at(range.end, ®ion.pair.end)
3937 {
3938 range.end += region.pair.end.len();
3939 selection.start = range.start;
3940 selection.end = range.end;
3941
3942 return selection;
3943 }
3944 }
3945 }
3946
3947 let always_treat_brackets_as_autoclosed = buffer
3948 .settings_at(selection.start, cx)
3949 .always_treat_brackets_as_autoclosed;
3950
3951 if !always_treat_brackets_as_autoclosed {
3952 return selection;
3953 }
3954
3955 if let Some(scope) = buffer.language_scope_at(selection.start) {
3956 for (pair, enabled) in scope.brackets() {
3957 if !enabled || !pair.close {
3958 continue;
3959 }
3960
3961 if buffer.contains_str_at(selection.start, &pair.end) {
3962 let pair_start_len = pair.start.len();
3963 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3964 {
3965 selection.start -= pair_start_len;
3966 selection.end += pair.end.len();
3967
3968 return selection;
3969 }
3970 }
3971 }
3972 }
3973
3974 selection
3975 })
3976 .collect();
3977
3978 drop(buffer);
3979 self.change_selections(None, cx, |selections| selections.select(new_selections));
3980 }
3981
3982 /// Iterate the given selections, and for each one, find the smallest surrounding
3983 /// autoclose region. This uses the ordering of the selections and the autoclose
3984 /// regions to avoid repeated comparisons.
3985 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3986 &'a self,
3987 selections: impl IntoIterator<Item = Selection<D>>,
3988 buffer: &'a MultiBufferSnapshot,
3989 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3990 let mut i = 0;
3991 let mut regions = self.autoclose_regions.as_slice();
3992 selections.into_iter().map(move |selection| {
3993 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3994
3995 let mut enclosing = None;
3996 while let Some(pair_state) = regions.get(i) {
3997 if pair_state.range.end.to_offset(buffer) < range.start {
3998 regions = ®ions[i + 1..];
3999 i = 0;
4000 } else if pair_state.range.start.to_offset(buffer) > range.end {
4001 break;
4002 } else {
4003 if pair_state.selection_id == selection.id {
4004 enclosing = Some(pair_state);
4005 }
4006 i += 1;
4007 }
4008 }
4009
4010 (selection.clone(), enclosing)
4011 })
4012 }
4013
4014 /// Remove any autoclose regions that no longer contain their selection.
4015 fn invalidate_autoclose_regions(
4016 &mut self,
4017 mut selections: &[Selection<Anchor>],
4018 buffer: &MultiBufferSnapshot,
4019 ) {
4020 self.autoclose_regions.retain(|state| {
4021 let mut i = 0;
4022 while let Some(selection) = selections.get(i) {
4023 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4024 selections = &selections[1..];
4025 continue;
4026 }
4027 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4028 break;
4029 }
4030 if selection.id == state.selection_id {
4031 return true;
4032 } else {
4033 i += 1;
4034 }
4035 }
4036 false
4037 });
4038 }
4039
4040 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4041 let offset = position.to_offset(buffer);
4042 let (word_range, kind) = buffer.surrounding_word(offset, true);
4043 if offset > word_range.start && kind == Some(CharKind::Word) {
4044 Some(
4045 buffer
4046 .text_for_range(word_range.start..offset)
4047 .collect::<String>(),
4048 )
4049 } else {
4050 None
4051 }
4052 }
4053
4054 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4055 self.refresh_inlay_hints(
4056 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4057 cx,
4058 );
4059 }
4060
4061 pub fn inlay_hints_enabled(&self) -> bool {
4062 self.inlay_hint_cache.enabled
4063 }
4064
4065 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4066 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4067 return;
4068 }
4069
4070 let reason_description = reason.description();
4071 let ignore_debounce = matches!(
4072 reason,
4073 InlayHintRefreshReason::SettingsChange(_)
4074 | InlayHintRefreshReason::Toggle(_)
4075 | InlayHintRefreshReason::ExcerptsRemoved(_)
4076 );
4077 let (invalidate_cache, required_languages) = match reason {
4078 InlayHintRefreshReason::Toggle(enabled) => {
4079 self.inlay_hint_cache.enabled = enabled;
4080 if enabled {
4081 (InvalidationStrategy::RefreshRequested, None)
4082 } else {
4083 self.inlay_hint_cache.clear();
4084 self.splice_inlays(
4085 self.visible_inlay_hints(cx)
4086 .iter()
4087 .map(|inlay| inlay.id)
4088 .collect(),
4089 Vec::new(),
4090 cx,
4091 );
4092 return;
4093 }
4094 }
4095 InlayHintRefreshReason::SettingsChange(new_settings) => {
4096 match self.inlay_hint_cache.update_settings(
4097 &self.buffer,
4098 new_settings,
4099 self.visible_inlay_hints(cx),
4100 cx,
4101 ) {
4102 ControlFlow::Break(Some(InlaySplice {
4103 to_remove,
4104 to_insert,
4105 })) => {
4106 self.splice_inlays(to_remove, to_insert, cx);
4107 return;
4108 }
4109 ControlFlow::Break(None) => return,
4110 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4111 }
4112 }
4113 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4114 if let Some(InlaySplice {
4115 to_remove,
4116 to_insert,
4117 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4118 {
4119 self.splice_inlays(to_remove, to_insert, cx);
4120 }
4121 return;
4122 }
4123 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4124 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4125 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4126 }
4127 InlayHintRefreshReason::RefreshRequested => {
4128 (InvalidationStrategy::RefreshRequested, None)
4129 }
4130 };
4131
4132 if let Some(InlaySplice {
4133 to_remove,
4134 to_insert,
4135 }) = self.inlay_hint_cache.spawn_hint_refresh(
4136 reason_description,
4137 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4138 invalidate_cache,
4139 ignore_debounce,
4140 cx,
4141 ) {
4142 self.splice_inlays(to_remove, to_insert, cx);
4143 }
4144 }
4145
4146 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4147 self.display_map
4148 .read(cx)
4149 .current_inlays()
4150 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4151 .cloned()
4152 .collect()
4153 }
4154
4155 pub fn excerpts_for_inlay_hints_query(
4156 &self,
4157 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4158 cx: &mut ViewContext<Editor>,
4159 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4160 let Some(project) = self.project.as_ref() else {
4161 return HashMap::default();
4162 };
4163 let project = project.read(cx);
4164 let multi_buffer = self.buffer().read(cx);
4165 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4166 let multi_buffer_visible_start = self
4167 .scroll_manager
4168 .anchor()
4169 .anchor
4170 .to_point(&multi_buffer_snapshot);
4171 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4172 multi_buffer_visible_start
4173 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4174 Bias::Left,
4175 );
4176 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4177 multi_buffer
4178 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4179 .into_iter()
4180 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4181 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4182 let buffer = buffer_handle.read(cx);
4183 let buffer_file = project::File::from_dyn(buffer.file())?;
4184 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4185 let worktree_entry = buffer_worktree
4186 .read(cx)
4187 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4188 if worktree_entry.is_ignored {
4189 return None;
4190 }
4191
4192 let language = buffer.language()?;
4193 if let Some(restrict_to_languages) = restrict_to_languages {
4194 if !restrict_to_languages.contains(language) {
4195 return None;
4196 }
4197 }
4198 Some((
4199 excerpt_id,
4200 (
4201 buffer_handle,
4202 buffer.version().clone(),
4203 excerpt_visible_range,
4204 ),
4205 ))
4206 })
4207 .collect()
4208 }
4209
4210 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4211 TextLayoutDetails {
4212 text_system: cx.text_system().clone(),
4213 editor_style: self.style.clone().unwrap(),
4214 rem_size: cx.rem_size(),
4215 scroll_anchor: self.scroll_manager.anchor(),
4216 visible_rows: self.visible_line_count(),
4217 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4218 }
4219 }
4220
4221 fn splice_inlays(
4222 &self,
4223 to_remove: Vec<InlayId>,
4224 to_insert: Vec<Inlay>,
4225 cx: &mut ViewContext<Self>,
4226 ) {
4227 self.display_map.update(cx, |display_map, cx| {
4228 display_map.splice_inlays(to_remove, to_insert, cx);
4229 });
4230 cx.notify();
4231 }
4232
4233 fn trigger_on_type_formatting(
4234 &self,
4235 input: String,
4236 cx: &mut ViewContext<Self>,
4237 ) -> Option<Task<Result<()>>> {
4238 if input.len() != 1 {
4239 return None;
4240 }
4241
4242 let project = self.project.as_ref()?;
4243 let position = self.selections.newest_anchor().head();
4244 let (buffer, buffer_position) = self
4245 .buffer
4246 .read(cx)
4247 .text_anchor_for_position(position, cx)?;
4248
4249 let settings = language_settings::language_settings(
4250 buffer
4251 .read(cx)
4252 .language_at(buffer_position)
4253 .map(|l| l.name()),
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 reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6245 let Some(project) = self.project.clone() else {
6246 return;
6247 };
6248 self.reload(project, cx).detach_and_notify_err(cx);
6249 }
6250
6251 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6252 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6253 if !revert_changes.is_empty() {
6254 self.transact(cx, |editor, cx| {
6255 editor.revert(revert_changes, cx);
6256 });
6257 }
6258 }
6259
6260 fn apply_selected_diff_hunks(&mut self, _: &ApplyDiffHunk, cx: &mut ViewContext<Self>) {
6261 let snapshot = self.buffer.read(cx).snapshot(cx);
6262 let hunks = hunks_for_selections(&snapshot, &self.selections.disjoint_anchors());
6263 let mut ranges_by_buffer = HashMap::default();
6264 self.transact(cx, |editor, cx| {
6265 for hunk in hunks {
6266 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
6267 ranges_by_buffer
6268 .entry(buffer.clone())
6269 .or_insert_with(Vec::new)
6270 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
6271 }
6272 }
6273
6274 for (buffer, ranges) in ranges_by_buffer {
6275 buffer.update(cx, |buffer, cx| {
6276 buffer.merge_into_base(ranges, cx);
6277 });
6278 }
6279 });
6280 }
6281
6282 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6283 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6284 let project_path = buffer.read(cx).project_path(cx)?;
6285 let project = self.project.as_ref()?.read(cx);
6286 let entry = project.entry_for_path(&project_path, cx)?;
6287 let parent = match &entry.canonical_path {
6288 Some(canonical_path) => canonical_path.to_path_buf(),
6289 None => project.absolute_path(&project_path, cx)?,
6290 }
6291 .parent()?
6292 .to_path_buf();
6293 Some(parent)
6294 }) {
6295 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6296 }
6297 }
6298
6299 fn gather_revert_changes(
6300 &mut self,
6301 selections: &[Selection<Anchor>],
6302 cx: &mut ViewContext<'_, Editor>,
6303 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6304 let mut revert_changes = HashMap::default();
6305 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6306 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6307 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6308 }
6309 revert_changes
6310 }
6311
6312 pub fn prepare_revert_change(
6313 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6314 multi_buffer: &Model<MultiBuffer>,
6315 hunk: &MultiBufferDiffHunk,
6316 cx: &AppContext,
6317 ) -> Option<()> {
6318 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6319 let buffer = buffer.read(cx);
6320 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6321 let buffer_snapshot = buffer.snapshot();
6322 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6323 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6324 probe
6325 .0
6326 .start
6327 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6328 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6329 }) {
6330 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6331 Some(())
6332 } else {
6333 None
6334 }
6335 }
6336
6337 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6338 self.manipulate_lines(cx, |lines| lines.reverse())
6339 }
6340
6341 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6342 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6343 }
6344
6345 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6346 where
6347 Fn: FnMut(&mut Vec<&str>),
6348 {
6349 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6350 let buffer = self.buffer.read(cx).snapshot(cx);
6351
6352 let mut edits = Vec::new();
6353
6354 let selections = self.selections.all::<Point>(cx);
6355 let mut selections = selections.iter().peekable();
6356 let mut contiguous_row_selections = Vec::new();
6357 let mut new_selections = Vec::new();
6358 let mut added_lines = 0;
6359 let mut removed_lines = 0;
6360
6361 while let Some(selection) = selections.next() {
6362 let (start_row, end_row) = consume_contiguous_rows(
6363 &mut contiguous_row_selections,
6364 selection,
6365 &display_map,
6366 &mut selections,
6367 );
6368
6369 let start_point = Point::new(start_row.0, 0);
6370 let end_point = Point::new(
6371 end_row.previous_row().0,
6372 buffer.line_len(end_row.previous_row()),
6373 );
6374 let text = buffer
6375 .text_for_range(start_point..end_point)
6376 .collect::<String>();
6377
6378 let mut lines = text.split('\n').collect_vec();
6379
6380 let lines_before = lines.len();
6381 callback(&mut lines);
6382 let lines_after = lines.len();
6383
6384 edits.push((start_point..end_point, lines.join("\n")));
6385
6386 // Selections must change based on added and removed line count
6387 let start_row =
6388 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6389 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6390 new_selections.push(Selection {
6391 id: selection.id,
6392 start: start_row,
6393 end: end_row,
6394 goal: SelectionGoal::None,
6395 reversed: selection.reversed,
6396 });
6397
6398 if lines_after > lines_before {
6399 added_lines += lines_after - lines_before;
6400 } else if lines_before > lines_after {
6401 removed_lines += lines_before - lines_after;
6402 }
6403 }
6404
6405 self.transact(cx, |this, cx| {
6406 let buffer = this.buffer.update(cx, |buffer, cx| {
6407 buffer.edit(edits, None, cx);
6408 buffer.snapshot(cx)
6409 });
6410
6411 // Recalculate offsets on newly edited buffer
6412 let new_selections = new_selections
6413 .iter()
6414 .map(|s| {
6415 let start_point = Point::new(s.start.0, 0);
6416 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6417 Selection {
6418 id: s.id,
6419 start: buffer.point_to_offset(start_point),
6420 end: buffer.point_to_offset(end_point),
6421 goal: s.goal,
6422 reversed: s.reversed,
6423 }
6424 })
6425 .collect();
6426
6427 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6428 s.select(new_selections);
6429 });
6430
6431 this.request_autoscroll(Autoscroll::fit(), cx);
6432 });
6433 }
6434
6435 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6436 self.manipulate_text(cx, |text| text.to_uppercase())
6437 }
6438
6439 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6440 self.manipulate_text(cx, |text| text.to_lowercase())
6441 }
6442
6443 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6444 self.manipulate_text(cx, |text| {
6445 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6446 // https://github.com/rutrum/convert-case/issues/16
6447 text.split('\n')
6448 .map(|line| line.to_case(Case::Title))
6449 .join("\n")
6450 })
6451 }
6452
6453 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6454 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6455 }
6456
6457 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6458 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6459 }
6460
6461 pub fn convert_to_upper_camel_case(
6462 &mut self,
6463 _: &ConvertToUpperCamelCase,
6464 cx: &mut ViewContext<Self>,
6465 ) {
6466 self.manipulate_text(cx, |text| {
6467 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6468 // https://github.com/rutrum/convert-case/issues/16
6469 text.split('\n')
6470 .map(|line| line.to_case(Case::UpperCamel))
6471 .join("\n")
6472 })
6473 }
6474
6475 pub fn convert_to_lower_camel_case(
6476 &mut self,
6477 _: &ConvertToLowerCamelCase,
6478 cx: &mut ViewContext<Self>,
6479 ) {
6480 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6481 }
6482
6483 pub fn convert_to_opposite_case(
6484 &mut self,
6485 _: &ConvertToOppositeCase,
6486 cx: &mut ViewContext<Self>,
6487 ) {
6488 self.manipulate_text(cx, |text| {
6489 text.chars()
6490 .fold(String::with_capacity(text.len()), |mut t, c| {
6491 if c.is_uppercase() {
6492 t.extend(c.to_lowercase());
6493 } else {
6494 t.extend(c.to_uppercase());
6495 }
6496 t
6497 })
6498 })
6499 }
6500
6501 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6502 where
6503 Fn: FnMut(&str) -> String,
6504 {
6505 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6506 let buffer = self.buffer.read(cx).snapshot(cx);
6507
6508 let mut new_selections = Vec::new();
6509 let mut edits = Vec::new();
6510 let mut selection_adjustment = 0i32;
6511
6512 for selection in self.selections.all::<usize>(cx) {
6513 let selection_is_empty = selection.is_empty();
6514
6515 let (start, end) = if selection_is_empty {
6516 let word_range = movement::surrounding_word(
6517 &display_map,
6518 selection.start.to_display_point(&display_map),
6519 );
6520 let start = word_range.start.to_offset(&display_map, Bias::Left);
6521 let end = word_range.end.to_offset(&display_map, Bias::Left);
6522 (start, end)
6523 } else {
6524 (selection.start, selection.end)
6525 };
6526
6527 let text = buffer.text_for_range(start..end).collect::<String>();
6528 let old_length = text.len() as i32;
6529 let text = callback(&text);
6530
6531 new_selections.push(Selection {
6532 start: (start as i32 - selection_adjustment) as usize,
6533 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6534 goal: SelectionGoal::None,
6535 ..selection
6536 });
6537
6538 selection_adjustment += old_length - text.len() as i32;
6539
6540 edits.push((start..end, text));
6541 }
6542
6543 self.transact(cx, |this, cx| {
6544 this.buffer.update(cx, |buffer, cx| {
6545 buffer.edit(edits, None, cx);
6546 });
6547
6548 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6549 s.select(new_selections);
6550 });
6551
6552 this.request_autoscroll(Autoscroll::fit(), cx);
6553 });
6554 }
6555
6556 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6557 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6558 let buffer = &display_map.buffer_snapshot;
6559 let selections = self.selections.all::<Point>(cx);
6560
6561 let mut edits = Vec::new();
6562 let mut selections_iter = selections.iter().peekable();
6563 while let Some(selection) = selections_iter.next() {
6564 // Avoid duplicating the same lines twice.
6565 let mut rows = selection.spanned_rows(false, &display_map);
6566
6567 while let Some(next_selection) = selections_iter.peek() {
6568 let next_rows = next_selection.spanned_rows(false, &display_map);
6569 if next_rows.start < rows.end {
6570 rows.end = next_rows.end;
6571 selections_iter.next().unwrap();
6572 } else {
6573 break;
6574 }
6575 }
6576
6577 // Copy the text from the selected row region and splice it either at the start
6578 // or end of the region.
6579 let start = Point::new(rows.start.0, 0);
6580 let end = Point::new(
6581 rows.end.previous_row().0,
6582 buffer.line_len(rows.end.previous_row()),
6583 );
6584 let text = buffer
6585 .text_for_range(start..end)
6586 .chain(Some("\n"))
6587 .collect::<String>();
6588 let insert_location = if upwards {
6589 Point::new(rows.end.0, 0)
6590 } else {
6591 start
6592 };
6593 edits.push((insert_location..insert_location, text));
6594 }
6595
6596 self.transact(cx, |this, cx| {
6597 this.buffer.update(cx, |buffer, cx| {
6598 buffer.edit(edits, None, cx);
6599 });
6600
6601 this.request_autoscroll(Autoscroll::fit(), cx);
6602 });
6603 }
6604
6605 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6606 self.duplicate_line(true, cx);
6607 }
6608
6609 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6610 self.duplicate_line(false, cx);
6611 }
6612
6613 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6614 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6615 let buffer = self.buffer.read(cx).snapshot(cx);
6616
6617 let mut edits = Vec::new();
6618 let mut unfold_ranges = Vec::new();
6619 let mut refold_ranges = Vec::new();
6620
6621 let selections = self.selections.all::<Point>(cx);
6622 let mut selections = selections.iter().peekable();
6623 let mut contiguous_row_selections = Vec::new();
6624 let mut new_selections = Vec::new();
6625
6626 while let Some(selection) = selections.next() {
6627 // Find all the selections that span a contiguous row range
6628 let (start_row, end_row) = consume_contiguous_rows(
6629 &mut contiguous_row_selections,
6630 selection,
6631 &display_map,
6632 &mut selections,
6633 );
6634
6635 // Move the text spanned by the row range to be before the line preceding the row range
6636 if start_row.0 > 0 {
6637 let range_to_move = Point::new(
6638 start_row.previous_row().0,
6639 buffer.line_len(start_row.previous_row()),
6640 )
6641 ..Point::new(
6642 end_row.previous_row().0,
6643 buffer.line_len(end_row.previous_row()),
6644 );
6645 let insertion_point = display_map
6646 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6647 .0;
6648
6649 // Don't move lines across excerpts
6650 if buffer
6651 .excerpt_boundaries_in_range((
6652 Bound::Excluded(insertion_point),
6653 Bound::Included(range_to_move.end),
6654 ))
6655 .next()
6656 .is_none()
6657 {
6658 let text = buffer
6659 .text_for_range(range_to_move.clone())
6660 .flat_map(|s| s.chars())
6661 .skip(1)
6662 .chain(['\n'])
6663 .collect::<String>();
6664
6665 edits.push((
6666 buffer.anchor_after(range_to_move.start)
6667 ..buffer.anchor_before(range_to_move.end),
6668 String::new(),
6669 ));
6670 let insertion_anchor = buffer.anchor_after(insertion_point);
6671 edits.push((insertion_anchor..insertion_anchor, text));
6672
6673 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6674
6675 // Move selections up
6676 new_selections.extend(contiguous_row_selections.drain(..).map(
6677 |mut selection| {
6678 selection.start.row -= row_delta;
6679 selection.end.row -= row_delta;
6680 selection
6681 },
6682 ));
6683
6684 // Move folds up
6685 unfold_ranges.push(range_to_move.clone());
6686 for fold in display_map.folds_in_range(
6687 buffer.anchor_before(range_to_move.start)
6688 ..buffer.anchor_after(range_to_move.end),
6689 ) {
6690 let mut start = fold.range.start.to_point(&buffer);
6691 let mut end = fold.range.end.to_point(&buffer);
6692 start.row -= row_delta;
6693 end.row -= row_delta;
6694 refold_ranges.push((start..end, fold.placeholder.clone()));
6695 }
6696 }
6697 }
6698
6699 // If we didn't move line(s), preserve the existing selections
6700 new_selections.append(&mut contiguous_row_selections);
6701 }
6702
6703 self.transact(cx, |this, cx| {
6704 this.unfold_ranges(unfold_ranges, true, true, cx);
6705 this.buffer.update(cx, |buffer, cx| {
6706 for (range, text) in edits {
6707 buffer.edit([(range, text)], None, cx);
6708 }
6709 });
6710 this.fold_ranges(refold_ranges, true, cx);
6711 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6712 s.select(new_selections);
6713 })
6714 });
6715 }
6716
6717 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6718 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6719 let buffer = self.buffer.read(cx).snapshot(cx);
6720
6721 let mut edits = Vec::new();
6722 let mut unfold_ranges = Vec::new();
6723 let mut refold_ranges = Vec::new();
6724
6725 let selections = self.selections.all::<Point>(cx);
6726 let mut selections = selections.iter().peekable();
6727 let mut contiguous_row_selections = Vec::new();
6728 let mut new_selections = Vec::new();
6729
6730 while let Some(selection) = selections.next() {
6731 // Find all the selections that span a contiguous row range
6732 let (start_row, end_row) = consume_contiguous_rows(
6733 &mut contiguous_row_selections,
6734 selection,
6735 &display_map,
6736 &mut selections,
6737 );
6738
6739 // Move the text spanned by the row range to be after the last line of the row range
6740 if end_row.0 <= buffer.max_point().row {
6741 let range_to_move =
6742 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6743 let insertion_point = display_map
6744 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6745 .0;
6746
6747 // Don't move lines across excerpt boundaries
6748 if buffer
6749 .excerpt_boundaries_in_range((
6750 Bound::Excluded(range_to_move.start),
6751 Bound::Included(insertion_point),
6752 ))
6753 .next()
6754 .is_none()
6755 {
6756 let mut text = String::from("\n");
6757 text.extend(buffer.text_for_range(range_to_move.clone()));
6758 text.pop(); // Drop trailing newline
6759 edits.push((
6760 buffer.anchor_after(range_to_move.start)
6761 ..buffer.anchor_before(range_to_move.end),
6762 String::new(),
6763 ));
6764 let insertion_anchor = buffer.anchor_after(insertion_point);
6765 edits.push((insertion_anchor..insertion_anchor, text));
6766
6767 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6768
6769 // Move selections down
6770 new_selections.extend(contiguous_row_selections.drain(..).map(
6771 |mut selection| {
6772 selection.start.row += row_delta;
6773 selection.end.row += row_delta;
6774 selection
6775 },
6776 ));
6777
6778 // Move folds down
6779 unfold_ranges.push(range_to_move.clone());
6780 for fold in display_map.folds_in_range(
6781 buffer.anchor_before(range_to_move.start)
6782 ..buffer.anchor_after(range_to_move.end),
6783 ) {
6784 let mut start = fold.range.start.to_point(&buffer);
6785 let mut end = fold.range.end.to_point(&buffer);
6786 start.row += row_delta;
6787 end.row += row_delta;
6788 refold_ranges.push((start..end, fold.placeholder.clone()));
6789 }
6790 }
6791 }
6792
6793 // If we didn't move line(s), preserve the existing selections
6794 new_selections.append(&mut contiguous_row_selections);
6795 }
6796
6797 self.transact(cx, |this, cx| {
6798 this.unfold_ranges(unfold_ranges, true, true, cx);
6799 this.buffer.update(cx, |buffer, cx| {
6800 for (range, text) in edits {
6801 buffer.edit([(range, text)], None, cx);
6802 }
6803 });
6804 this.fold_ranges(refold_ranges, true, cx);
6805 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6806 });
6807 }
6808
6809 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6810 let text_layout_details = &self.text_layout_details(cx);
6811 self.transact(cx, |this, cx| {
6812 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6813 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6814 let line_mode = s.line_mode;
6815 s.move_with(|display_map, selection| {
6816 if !selection.is_empty() || line_mode {
6817 return;
6818 }
6819
6820 let mut head = selection.head();
6821 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6822 if head.column() == display_map.line_len(head.row()) {
6823 transpose_offset = display_map
6824 .buffer_snapshot
6825 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6826 }
6827
6828 if transpose_offset == 0 {
6829 return;
6830 }
6831
6832 *head.column_mut() += 1;
6833 head = display_map.clip_point(head, Bias::Right);
6834 let goal = SelectionGoal::HorizontalPosition(
6835 display_map
6836 .x_for_display_point(head, text_layout_details)
6837 .into(),
6838 );
6839 selection.collapse_to(head, goal);
6840
6841 let transpose_start = display_map
6842 .buffer_snapshot
6843 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6844 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6845 let transpose_end = display_map
6846 .buffer_snapshot
6847 .clip_offset(transpose_offset + 1, Bias::Right);
6848 if let Some(ch) =
6849 display_map.buffer_snapshot.chars_at(transpose_start).next()
6850 {
6851 edits.push((transpose_start..transpose_offset, String::new()));
6852 edits.push((transpose_end..transpose_end, ch.to_string()));
6853 }
6854 }
6855 });
6856 edits
6857 });
6858 this.buffer
6859 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6860 let selections = this.selections.all::<usize>(cx);
6861 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6862 s.select(selections);
6863 });
6864 });
6865 }
6866
6867 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6868 self.rewrap_impl(true, cx)
6869 }
6870
6871 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6872 let buffer = self.buffer.read(cx).snapshot(cx);
6873 let selections = self.selections.all::<Point>(cx);
6874 let mut selections = selections.iter().peekable();
6875
6876 let mut edits = Vec::new();
6877 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6878
6879 while let Some(selection) = selections.next() {
6880 let mut start_row = selection.start.row;
6881 let mut end_row = selection.end.row;
6882
6883 // Skip selections that overlap with a range that has already been rewrapped.
6884 let selection_range = start_row..end_row;
6885 if rewrapped_row_ranges
6886 .iter()
6887 .any(|range| range.overlaps(&selection_range))
6888 {
6889 continue;
6890 }
6891
6892 let mut should_rewrap = !only_text;
6893
6894 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6895 match language_scope.language_name().0.as_ref() {
6896 "Markdown" | "Plain Text" => {
6897 should_rewrap = true;
6898 }
6899 _ => {}
6900 }
6901 }
6902
6903 // Since not all lines in the selection may be at the same indent
6904 // level, choose the indent size that is the most common between all
6905 // of the lines.
6906 //
6907 // If there is a tie, we use the deepest indent.
6908 let (indent_size, indent_end) = {
6909 let mut indent_size_occurrences = HashMap::default();
6910 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6911
6912 for row in start_row..=end_row {
6913 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6914 rows_by_indent_size.entry(indent).or_default().push(row);
6915 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6916 }
6917
6918 let indent_size = indent_size_occurrences
6919 .into_iter()
6920 .max_by_key(|(indent, count)| (*count, indent.len))
6921 .map(|(indent, _)| indent)
6922 .unwrap_or_default();
6923 let row = rows_by_indent_size[&indent_size][0];
6924 let indent_end = Point::new(row, indent_size.len);
6925
6926 (indent_size, indent_end)
6927 };
6928
6929 let mut line_prefix = indent_size.chars().collect::<String>();
6930
6931 if let Some(comment_prefix) =
6932 buffer
6933 .language_scope_at(selection.head())
6934 .and_then(|language| {
6935 language
6936 .line_comment_prefixes()
6937 .iter()
6938 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6939 .cloned()
6940 })
6941 {
6942 line_prefix.push_str(&comment_prefix);
6943 should_rewrap = true;
6944 }
6945
6946 if selection.is_empty() {
6947 'expand_upwards: while start_row > 0 {
6948 let prev_row = start_row - 1;
6949 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6950 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6951 {
6952 start_row = prev_row;
6953 } else {
6954 break 'expand_upwards;
6955 }
6956 }
6957
6958 'expand_downwards: while end_row < buffer.max_point().row {
6959 let next_row = end_row + 1;
6960 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6961 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6962 {
6963 end_row = next_row;
6964 } else {
6965 break 'expand_downwards;
6966 }
6967 }
6968 }
6969
6970 if !should_rewrap {
6971 continue;
6972 }
6973
6974 let start = Point::new(start_row, 0);
6975 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6976 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6977 let Some(lines_without_prefixes) = selection_text
6978 .lines()
6979 .map(|line| {
6980 line.strip_prefix(&line_prefix)
6981 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6982 .ok_or_else(|| {
6983 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6984 })
6985 })
6986 .collect::<Result<Vec<_>, _>>()
6987 .log_err()
6988 else {
6989 continue;
6990 };
6991
6992 let unwrapped_text = lines_without_prefixes.join(" ");
6993 let wrap_column = buffer
6994 .settings_at(Point::new(start_row, 0), cx)
6995 .preferred_line_length as usize;
6996 let mut wrapped_text = String::new();
6997 let mut current_line = line_prefix.clone();
6998 for word in unwrapped_text.split_whitespace() {
6999 if current_line.len() + word.len() >= wrap_column {
7000 wrapped_text.push_str(¤t_line);
7001 wrapped_text.push('\n');
7002 current_line.truncate(line_prefix.len());
7003 }
7004
7005 if current_line.len() > line_prefix.len() {
7006 current_line.push(' ');
7007 }
7008
7009 current_line.push_str(word);
7010 }
7011
7012 if !current_line.is_empty() {
7013 wrapped_text.push_str(¤t_line);
7014 }
7015
7016 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
7017 let mut offset = start.to_offset(&buffer);
7018 let mut moved_since_edit = true;
7019
7020 for change in diff.iter_all_changes() {
7021 let value = change.value();
7022 match change.tag() {
7023 ChangeTag::Equal => {
7024 offset += value.len();
7025 moved_since_edit = true;
7026 }
7027 ChangeTag::Delete => {
7028 let start = buffer.anchor_after(offset);
7029 let end = buffer.anchor_before(offset + value.len());
7030
7031 if moved_since_edit {
7032 edits.push((start..end, String::new()));
7033 } else {
7034 edits.last_mut().unwrap().0.end = end;
7035 }
7036
7037 offset += value.len();
7038 moved_since_edit = false;
7039 }
7040 ChangeTag::Insert => {
7041 if moved_since_edit {
7042 let anchor = buffer.anchor_after(offset);
7043 edits.push((anchor..anchor, value.to_string()));
7044 } else {
7045 edits.last_mut().unwrap().1.push_str(value);
7046 }
7047
7048 moved_since_edit = false;
7049 }
7050 }
7051 }
7052
7053 rewrapped_row_ranges.push(start_row..=end_row);
7054 }
7055
7056 self.buffer
7057 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7058 }
7059
7060 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7061 let mut text = String::new();
7062 let buffer = self.buffer.read(cx).snapshot(cx);
7063 let mut selections = self.selections.all::<Point>(cx);
7064 let mut clipboard_selections = Vec::with_capacity(selections.len());
7065 {
7066 let max_point = buffer.max_point();
7067 let mut is_first = true;
7068 for selection in &mut selections {
7069 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7070 if is_entire_line {
7071 selection.start = Point::new(selection.start.row, 0);
7072 if !selection.is_empty() && selection.end.column == 0 {
7073 selection.end = cmp::min(max_point, selection.end);
7074 } else {
7075 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7076 }
7077 selection.goal = SelectionGoal::None;
7078 }
7079 if is_first {
7080 is_first = false;
7081 } else {
7082 text += "\n";
7083 }
7084 let mut len = 0;
7085 for chunk in buffer.text_for_range(selection.start..selection.end) {
7086 text.push_str(chunk);
7087 len += chunk.len();
7088 }
7089 clipboard_selections.push(ClipboardSelection {
7090 len,
7091 is_entire_line,
7092 first_line_indent: buffer
7093 .indent_size_for_line(MultiBufferRow(selection.start.row))
7094 .len,
7095 });
7096 }
7097 }
7098
7099 self.transact(cx, |this, cx| {
7100 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7101 s.select(selections);
7102 });
7103 this.insert("", cx);
7104 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7105 text,
7106 clipboard_selections,
7107 ));
7108 });
7109 }
7110
7111 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7112 let selections = self.selections.all::<Point>(cx);
7113 let buffer = self.buffer.read(cx).read(cx);
7114 let mut text = String::new();
7115
7116 let mut clipboard_selections = Vec::with_capacity(selections.len());
7117 {
7118 let max_point = buffer.max_point();
7119 let mut is_first = true;
7120 for selection in selections.iter() {
7121 let mut start = selection.start;
7122 let mut end = selection.end;
7123 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7124 if is_entire_line {
7125 start = Point::new(start.row, 0);
7126 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7127 }
7128 if is_first {
7129 is_first = false;
7130 } else {
7131 text += "\n";
7132 }
7133 let mut len = 0;
7134 for chunk in buffer.text_for_range(start..end) {
7135 text.push_str(chunk);
7136 len += chunk.len();
7137 }
7138 clipboard_selections.push(ClipboardSelection {
7139 len,
7140 is_entire_line,
7141 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7142 });
7143 }
7144 }
7145
7146 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7147 text,
7148 clipboard_selections,
7149 ));
7150 }
7151
7152 pub fn do_paste(
7153 &mut self,
7154 text: &String,
7155 clipboard_selections: Option<Vec<ClipboardSelection>>,
7156 handle_entire_lines: bool,
7157 cx: &mut ViewContext<Self>,
7158 ) {
7159 if self.read_only(cx) {
7160 return;
7161 }
7162
7163 let clipboard_text = Cow::Borrowed(text);
7164
7165 self.transact(cx, |this, cx| {
7166 if let Some(mut clipboard_selections) = clipboard_selections {
7167 let old_selections = this.selections.all::<usize>(cx);
7168 let all_selections_were_entire_line =
7169 clipboard_selections.iter().all(|s| s.is_entire_line);
7170 let first_selection_indent_column =
7171 clipboard_selections.first().map(|s| s.first_line_indent);
7172 if clipboard_selections.len() != old_selections.len() {
7173 clipboard_selections.drain(..);
7174 }
7175
7176 this.buffer.update(cx, |buffer, cx| {
7177 let snapshot = buffer.read(cx);
7178 let mut start_offset = 0;
7179 let mut edits = Vec::new();
7180 let mut original_indent_columns = Vec::new();
7181 for (ix, selection) in old_selections.iter().enumerate() {
7182 let to_insert;
7183 let entire_line;
7184 let original_indent_column;
7185 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7186 let end_offset = start_offset + clipboard_selection.len;
7187 to_insert = &clipboard_text[start_offset..end_offset];
7188 entire_line = clipboard_selection.is_entire_line;
7189 start_offset = end_offset + 1;
7190 original_indent_column = Some(clipboard_selection.first_line_indent);
7191 } else {
7192 to_insert = clipboard_text.as_str();
7193 entire_line = all_selections_were_entire_line;
7194 original_indent_column = first_selection_indent_column
7195 }
7196
7197 // If the corresponding selection was empty when this slice of the
7198 // clipboard text was written, then the entire line containing the
7199 // selection was copied. If this selection is also currently empty,
7200 // then paste the line before the current line of the buffer.
7201 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7202 let column = selection.start.to_point(&snapshot).column as usize;
7203 let line_start = selection.start - column;
7204 line_start..line_start
7205 } else {
7206 selection.range()
7207 };
7208
7209 edits.push((range, to_insert));
7210 original_indent_columns.extend(original_indent_column);
7211 }
7212 drop(snapshot);
7213
7214 buffer.edit(
7215 edits,
7216 Some(AutoindentMode::Block {
7217 original_indent_columns,
7218 }),
7219 cx,
7220 );
7221 });
7222
7223 let selections = this.selections.all::<usize>(cx);
7224 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7225 } else {
7226 this.insert(&clipboard_text, cx);
7227 }
7228 });
7229 }
7230
7231 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7232 if let Some(item) = cx.read_from_clipboard() {
7233 let entries = item.entries();
7234
7235 match entries.first() {
7236 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7237 // of all the pasted entries.
7238 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7239 .do_paste(
7240 clipboard_string.text(),
7241 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7242 true,
7243 cx,
7244 ),
7245 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7246 }
7247 }
7248 }
7249
7250 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7251 if self.read_only(cx) {
7252 return;
7253 }
7254
7255 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7256 if let Some((selections, _)) =
7257 self.selection_history.transaction(transaction_id).cloned()
7258 {
7259 self.change_selections(None, cx, |s| {
7260 s.select_anchors(selections.to_vec());
7261 });
7262 }
7263 self.request_autoscroll(Autoscroll::fit(), cx);
7264 self.unmark_text(cx);
7265 self.refresh_inline_completion(true, false, cx);
7266 cx.emit(EditorEvent::Edited { transaction_id });
7267 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7268 }
7269 }
7270
7271 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7272 if self.read_only(cx) {
7273 return;
7274 }
7275
7276 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7277 if let Some((_, Some(selections))) =
7278 self.selection_history.transaction(transaction_id).cloned()
7279 {
7280 self.change_selections(None, cx, |s| {
7281 s.select_anchors(selections.to_vec());
7282 });
7283 }
7284 self.request_autoscroll(Autoscroll::fit(), cx);
7285 self.unmark_text(cx);
7286 self.refresh_inline_completion(true, false, cx);
7287 cx.emit(EditorEvent::Edited { transaction_id });
7288 }
7289 }
7290
7291 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7292 self.buffer
7293 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7294 }
7295
7296 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7297 self.buffer
7298 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7299 }
7300
7301 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7302 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7303 let line_mode = s.line_mode;
7304 s.move_with(|map, selection| {
7305 let cursor = if selection.is_empty() && !line_mode {
7306 movement::left(map, selection.start)
7307 } else {
7308 selection.start
7309 };
7310 selection.collapse_to(cursor, SelectionGoal::None);
7311 });
7312 })
7313 }
7314
7315 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7316 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7317 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7318 })
7319 }
7320
7321 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7322 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7323 let line_mode = s.line_mode;
7324 s.move_with(|map, selection| {
7325 let cursor = if selection.is_empty() && !line_mode {
7326 movement::right(map, selection.end)
7327 } else {
7328 selection.end
7329 };
7330 selection.collapse_to(cursor, SelectionGoal::None)
7331 });
7332 })
7333 }
7334
7335 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7336 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7337 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7338 })
7339 }
7340
7341 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7342 if self.take_rename(true, cx).is_some() {
7343 return;
7344 }
7345
7346 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7347 cx.propagate();
7348 return;
7349 }
7350
7351 let text_layout_details = &self.text_layout_details(cx);
7352 let selection_count = self.selections.count();
7353 let first_selection = self.selections.first_anchor();
7354
7355 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7356 let line_mode = s.line_mode;
7357 s.move_with(|map, selection| {
7358 if !selection.is_empty() && !line_mode {
7359 selection.goal = SelectionGoal::None;
7360 }
7361 let (cursor, goal) = movement::up(
7362 map,
7363 selection.start,
7364 selection.goal,
7365 false,
7366 text_layout_details,
7367 );
7368 selection.collapse_to(cursor, goal);
7369 });
7370 });
7371
7372 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7373 {
7374 cx.propagate();
7375 }
7376 }
7377
7378 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7379 if self.take_rename(true, cx).is_some() {
7380 return;
7381 }
7382
7383 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7384 cx.propagate();
7385 return;
7386 }
7387
7388 let text_layout_details = &self.text_layout_details(cx);
7389
7390 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7391 let line_mode = s.line_mode;
7392 s.move_with(|map, selection| {
7393 if !selection.is_empty() && !line_mode {
7394 selection.goal = SelectionGoal::None;
7395 }
7396 let (cursor, goal) = movement::up_by_rows(
7397 map,
7398 selection.start,
7399 action.lines,
7400 selection.goal,
7401 false,
7402 text_layout_details,
7403 );
7404 selection.collapse_to(cursor, goal);
7405 });
7406 })
7407 }
7408
7409 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7410 if self.take_rename(true, cx).is_some() {
7411 return;
7412 }
7413
7414 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7415 cx.propagate();
7416 return;
7417 }
7418
7419 let text_layout_details = &self.text_layout_details(cx);
7420
7421 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7422 let line_mode = s.line_mode;
7423 s.move_with(|map, selection| {
7424 if !selection.is_empty() && !line_mode {
7425 selection.goal = SelectionGoal::None;
7426 }
7427 let (cursor, goal) = movement::down_by_rows(
7428 map,
7429 selection.start,
7430 action.lines,
7431 selection.goal,
7432 false,
7433 text_layout_details,
7434 );
7435 selection.collapse_to(cursor, goal);
7436 });
7437 })
7438 }
7439
7440 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7441 let text_layout_details = &self.text_layout_details(cx);
7442 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7443 s.move_heads_with(|map, head, goal| {
7444 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7445 })
7446 })
7447 }
7448
7449 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7450 let text_layout_details = &self.text_layout_details(cx);
7451 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7452 s.move_heads_with(|map, head, goal| {
7453 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7454 })
7455 })
7456 }
7457
7458 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7459 let Some(row_count) = self.visible_row_count() else {
7460 return;
7461 };
7462
7463 let text_layout_details = &self.text_layout_details(cx);
7464
7465 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7466 s.move_heads_with(|map, head, goal| {
7467 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7468 })
7469 })
7470 }
7471
7472 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7473 if self.take_rename(true, cx).is_some() {
7474 return;
7475 }
7476
7477 if self
7478 .context_menu
7479 .write()
7480 .as_mut()
7481 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7482 .unwrap_or(false)
7483 {
7484 return;
7485 }
7486
7487 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7488 cx.propagate();
7489 return;
7490 }
7491
7492 let Some(row_count) = self.visible_row_count() else {
7493 return;
7494 };
7495
7496 let autoscroll = if action.center_cursor {
7497 Autoscroll::center()
7498 } else {
7499 Autoscroll::fit()
7500 };
7501
7502 let text_layout_details = &self.text_layout_details(cx);
7503
7504 self.change_selections(Some(autoscroll), cx, |s| {
7505 let line_mode = s.line_mode;
7506 s.move_with(|map, selection| {
7507 if !selection.is_empty() && !line_mode {
7508 selection.goal = SelectionGoal::None;
7509 }
7510 let (cursor, goal) = movement::up_by_rows(
7511 map,
7512 selection.end,
7513 row_count,
7514 selection.goal,
7515 false,
7516 text_layout_details,
7517 );
7518 selection.collapse_to(cursor, goal);
7519 });
7520 });
7521 }
7522
7523 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7524 let text_layout_details = &self.text_layout_details(cx);
7525 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7526 s.move_heads_with(|map, head, goal| {
7527 movement::up(map, head, goal, false, text_layout_details)
7528 })
7529 })
7530 }
7531
7532 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7533 self.take_rename(true, cx);
7534
7535 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7536 cx.propagate();
7537 return;
7538 }
7539
7540 let text_layout_details = &self.text_layout_details(cx);
7541 let selection_count = self.selections.count();
7542 let first_selection = self.selections.first_anchor();
7543
7544 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7545 let line_mode = s.line_mode;
7546 s.move_with(|map, selection| {
7547 if !selection.is_empty() && !line_mode {
7548 selection.goal = SelectionGoal::None;
7549 }
7550 let (cursor, goal) = movement::down(
7551 map,
7552 selection.end,
7553 selection.goal,
7554 false,
7555 text_layout_details,
7556 );
7557 selection.collapse_to(cursor, goal);
7558 });
7559 });
7560
7561 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7562 {
7563 cx.propagate();
7564 }
7565 }
7566
7567 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7568 let Some(row_count) = self.visible_row_count() else {
7569 return;
7570 };
7571
7572 let text_layout_details = &self.text_layout_details(cx);
7573
7574 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7575 s.move_heads_with(|map, head, goal| {
7576 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7577 })
7578 })
7579 }
7580
7581 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7582 if self.take_rename(true, cx).is_some() {
7583 return;
7584 }
7585
7586 if self
7587 .context_menu
7588 .write()
7589 .as_mut()
7590 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7591 .unwrap_or(false)
7592 {
7593 return;
7594 }
7595
7596 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7597 cx.propagate();
7598 return;
7599 }
7600
7601 let Some(row_count) = self.visible_row_count() else {
7602 return;
7603 };
7604
7605 let autoscroll = if action.center_cursor {
7606 Autoscroll::center()
7607 } else {
7608 Autoscroll::fit()
7609 };
7610
7611 let text_layout_details = &self.text_layout_details(cx);
7612 self.change_selections(Some(autoscroll), cx, |s| {
7613 let line_mode = s.line_mode;
7614 s.move_with(|map, selection| {
7615 if !selection.is_empty() && !line_mode {
7616 selection.goal = SelectionGoal::None;
7617 }
7618 let (cursor, goal) = movement::down_by_rows(
7619 map,
7620 selection.end,
7621 row_count,
7622 selection.goal,
7623 false,
7624 text_layout_details,
7625 );
7626 selection.collapse_to(cursor, goal);
7627 });
7628 });
7629 }
7630
7631 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7632 let text_layout_details = &self.text_layout_details(cx);
7633 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7634 s.move_heads_with(|map, head, goal| {
7635 movement::down(map, head, goal, false, text_layout_details)
7636 })
7637 });
7638 }
7639
7640 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7641 if let Some(context_menu) = self.context_menu.write().as_mut() {
7642 context_menu.select_first(self.completion_provider.as_deref(), cx);
7643 }
7644 }
7645
7646 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7647 if let Some(context_menu) = self.context_menu.write().as_mut() {
7648 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7649 }
7650 }
7651
7652 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7653 if let Some(context_menu) = self.context_menu.write().as_mut() {
7654 context_menu.select_next(self.completion_provider.as_deref(), cx);
7655 }
7656 }
7657
7658 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7659 if let Some(context_menu) = self.context_menu.write().as_mut() {
7660 context_menu.select_last(self.completion_provider.as_deref(), cx);
7661 }
7662 }
7663
7664 pub fn move_to_previous_word_start(
7665 &mut self,
7666 _: &MoveToPreviousWordStart,
7667 cx: &mut ViewContext<Self>,
7668 ) {
7669 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7670 s.move_cursors_with(|map, head, _| {
7671 (
7672 movement::previous_word_start(map, head),
7673 SelectionGoal::None,
7674 )
7675 });
7676 })
7677 }
7678
7679 pub fn move_to_previous_subword_start(
7680 &mut self,
7681 _: &MoveToPreviousSubwordStart,
7682 cx: &mut ViewContext<Self>,
7683 ) {
7684 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7685 s.move_cursors_with(|map, head, _| {
7686 (
7687 movement::previous_subword_start(map, head),
7688 SelectionGoal::None,
7689 )
7690 });
7691 })
7692 }
7693
7694 pub fn select_to_previous_word_start(
7695 &mut self,
7696 _: &SelectToPreviousWordStart,
7697 cx: &mut ViewContext<Self>,
7698 ) {
7699 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7700 s.move_heads_with(|map, head, _| {
7701 (
7702 movement::previous_word_start(map, head),
7703 SelectionGoal::None,
7704 )
7705 });
7706 })
7707 }
7708
7709 pub fn select_to_previous_subword_start(
7710 &mut self,
7711 _: &SelectToPreviousSubwordStart,
7712 cx: &mut ViewContext<Self>,
7713 ) {
7714 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7715 s.move_heads_with(|map, head, _| {
7716 (
7717 movement::previous_subword_start(map, head),
7718 SelectionGoal::None,
7719 )
7720 });
7721 })
7722 }
7723
7724 pub fn delete_to_previous_word_start(
7725 &mut self,
7726 action: &DeleteToPreviousWordStart,
7727 cx: &mut ViewContext<Self>,
7728 ) {
7729 self.transact(cx, |this, cx| {
7730 this.select_autoclose_pair(cx);
7731 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7732 let line_mode = s.line_mode;
7733 s.move_with(|map, selection| {
7734 if selection.is_empty() && !line_mode {
7735 let cursor = if action.ignore_newlines {
7736 movement::previous_word_start(map, selection.head())
7737 } else {
7738 movement::previous_word_start_or_newline(map, selection.head())
7739 };
7740 selection.set_head(cursor, SelectionGoal::None);
7741 }
7742 });
7743 });
7744 this.insert("", cx);
7745 });
7746 }
7747
7748 pub fn delete_to_previous_subword_start(
7749 &mut self,
7750 _: &DeleteToPreviousSubwordStart,
7751 cx: &mut ViewContext<Self>,
7752 ) {
7753 self.transact(cx, |this, cx| {
7754 this.select_autoclose_pair(cx);
7755 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7756 let line_mode = s.line_mode;
7757 s.move_with(|map, selection| {
7758 if selection.is_empty() && !line_mode {
7759 let cursor = movement::previous_subword_start(map, selection.head());
7760 selection.set_head(cursor, SelectionGoal::None);
7761 }
7762 });
7763 });
7764 this.insert("", cx);
7765 });
7766 }
7767
7768 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7769 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7770 s.move_cursors_with(|map, head, _| {
7771 (movement::next_word_end(map, head), SelectionGoal::None)
7772 });
7773 })
7774 }
7775
7776 pub fn move_to_next_subword_end(
7777 &mut self,
7778 _: &MoveToNextSubwordEnd,
7779 cx: &mut ViewContext<Self>,
7780 ) {
7781 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7782 s.move_cursors_with(|map, head, _| {
7783 (movement::next_subword_end(map, head), SelectionGoal::None)
7784 });
7785 })
7786 }
7787
7788 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7789 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7790 s.move_heads_with(|map, head, _| {
7791 (movement::next_word_end(map, head), SelectionGoal::None)
7792 });
7793 })
7794 }
7795
7796 pub fn select_to_next_subword_end(
7797 &mut self,
7798 _: &SelectToNextSubwordEnd,
7799 cx: &mut ViewContext<Self>,
7800 ) {
7801 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7802 s.move_heads_with(|map, head, _| {
7803 (movement::next_subword_end(map, head), SelectionGoal::None)
7804 });
7805 })
7806 }
7807
7808 pub fn delete_to_next_word_end(
7809 &mut self,
7810 action: &DeleteToNextWordEnd,
7811 cx: &mut ViewContext<Self>,
7812 ) {
7813 self.transact(cx, |this, cx| {
7814 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7815 let line_mode = s.line_mode;
7816 s.move_with(|map, selection| {
7817 if selection.is_empty() && !line_mode {
7818 let cursor = if action.ignore_newlines {
7819 movement::next_word_end(map, selection.head())
7820 } else {
7821 movement::next_word_end_or_newline(map, selection.head())
7822 };
7823 selection.set_head(cursor, SelectionGoal::None);
7824 }
7825 });
7826 });
7827 this.insert("", cx);
7828 });
7829 }
7830
7831 pub fn delete_to_next_subword_end(
7832 &mut self,
7833 _: &DeleteToNextSubwordEnd,
7834 cx: &mut ViewContext<Self>,
7835 ) {
7836 self.transact(cx, |this, cx| {
7837 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7838 s.move_with(|map, selection| {
7839 if selection.is_empty() {
7840 let cursor = movement::next_subword_end(map, selection.head());
7841 selection.set_head(cursor, SelectionGoal::None);
7842 }
7843 });
7844 });
7845 this.insert("", cx);
7846 });
7847 }
7848
7849 pub fn move_to_beginning_of_line(
7850 &mut self,
7851 action: &MoveToBeginningOfLine,
7852 cx: &mut ViewContext<Self>,
7853 ) {
7854 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7855 s.move_cursors_with(|map, head, _| {
7856 (
7857 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7858 SelectionGoal::None,
7859 )
7860 });
7861 })
7862 }
7863
7864 pub fn select_to_beginning_of_line(
7865 &mut self,
7866 action: &SelectToBeginningOfLine,
7867 cx: &mut ViewContext<Self>,
7868 ) {
7869 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7870 s.move_heads_with(|map, head, _| {
7871 (
7872 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7873 SelectionGoal::None,
7874 )
7875 });
7876 });
7877 }
7878
7879 pub fn delete_to_beginning_of_line(
7880 &mut self,
7881 _: &DeleteToBeginningOfLine,
7882 cx: &mut ViewContext<Self>,
7883 ) {
7884 self.transact(cx, |this, cx| {
7885 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7886 s.move_with(|_, selection| {
7887 selection.reversed = true;
7888 });
7889 });
7890
7891 this.select_to_beginning_of_line(
7892 &SelectToBeginningOfLine {
7893 stop_at_soft_wraps: false,
7894 },
7895 cx,
7896 );
7897 this.backspace(&Backspace, cx);
7898 });
7899 }
7900
7901 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7902 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7903 s.move_cursors_with(|map, head, _| {
7904 (
7905 movement::line_end(map, head, action.stop_at_soft_wraps),
7906 SelectionGoal::None,
7907 )
7908 });
7909 })
7910 }
7911
7912 pub fn select_to_end_of_line(
7913 &mut self,
7914 action: &SelectToEndOfLine,
7915 cx: &mut ViewContext<Self>,
7916 ) {
7917 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7918 s.move_heads_with(|map, head, _| {
7919 (
7920 movement::line_end(map, head, action.stop_at_soft_wraps),
7921 SelectionGoal::None,
7922 )
7923 });
7924 })
7925 }
7926
7927 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7928 self.transact(cx, |this, cx| {
7929 this.select_to_end_of_line(
7930 &SelectToEndOfLine {
7931 stop_at_soft_wraps: false,
7932 },
7933 cx,
7934 );
7935 this.delete(&Delete, cx);
7936 });
7937 }
7938
7939 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7940 self.transact(cx, |this, cx| {
7941 this.select_to_end_of_line(
7942 &SelectToEndOfLine {
7943 stop_at_soft_wraps: false,
7944 },
7945 cx,
7946 );
7947 this.cut(&Cut, cx);
7948 });
7949 }
7950
7951 pub fn move_to_start_of_paragraph(
7952 &mut self,
7953 _: &MoveToStartOfParagraph,
7954 cx: &mut ViewContext<Self>,
7955 ) {
7956 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7957 cx.propagate();
7958 return;
7959 }
7960
7961 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7962 s.move_with(|map, selection| {
7963 selection.collapse_to(
7964 movement::start_of_paragraph(map, selection.head(), 1),
7965 SelectionGoal::None,
7966 )
7967 });
7968 })
7969 }
7970
7971 pub fn move_to_end_of_paragraph(
7972 &mut self,
7973 _: &MoveToEndOfParagraph,
7974 cx: &mut ViewContext<Self>,
7975 ) {
7976 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7977 cx.propagate();
7978 return;
7979 }
7980
7981 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7982 s.move_with(|map, selection| {
7983 selection.collapse_to(
7984 movement::end_of_paragraph(map, selection.head(), 1),
7985 SelectionGoal::None,
7986 )
7987 });
7988 })
7989 }
7990
7991 pub fn select_to_start_of_paragraph(
7992 &mut self,
7993 _: &SelectToStartOfParagraph,
7994 cx: &mut ViewContext<Self>,
7995 ) {
7996 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7997 cx.propagate();
7998 return;
7999 }
8000
8001 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8002 s.move_heads_with(|map, head, _| {
8003 (
8004 movement::start_of_paragraph(map, head, 1),
8005 SelectionGoal::None,
8006 )
8007 });
8008 })
8009 }
8010
8011 pub fn select_to_end_of_paragraph(
8012 &mut self,
8013 _: &SelectToEndOfParagraph,
8014 cx: &mut ViewContext<Self>,
8015 ) {
8016 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8017 cx.propagate();
8018 return;
8019 }
8020
8021 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8022 s.move_heads_with(|map, head, _| {
8023 (
8024 movement::end_of_paragraph(map, head, 1),
8025 SelectionGoal::None,
8026 )
8027 });
8028 })
8029 }
8030
8031 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8032 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8033 cx.propagate();
8034 return;
8035 }
8036
8037 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8038 s.select_ranges(vec![0..0]);
8039 });
8040 }
8041
8042 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8043 let mut selection = self.selections.last::<Point>(cx);
8044 selection.set_head(Point::zero(), SelectionGoal::None);
8045
8046 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8047 s.select(vec![selection]);
8048 });
8049 }
8050
8051 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8052 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8053 cx.propagate();
8054 return;
8055 }
8056
8057 let cursor = self.buffer.read(cx).read(cx).len();
8058 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8059 s.select_ranges(vec![cursor..cursor])
8060 });
8061 }
8062
8063 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8064 self.nav_history = nav_history;
8065 }
8066
8067 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8068 self.nav_history.as_ref()
8069 }
8070
8071 fn push_to_nav_history(
8072 &mut self,
8073 cursor_anchor: Anchor,
8074 new_position: Option<Point>,
8075 cx: &mut ViewContext<Self>,
8076 ) {
8077 if let Some(nav_history) = self.nav_history.as_mut() {
8078 let buffer = self.buffer.read(cx).read(cx);
8079 let cursor_position = cursor_anchor.to_point(&buffer);
8080 let scroll_state = self.scroll_manager.anchor();
8081 let scroll_top_row = scroll_state.top_row(&buffer);
8082 drop(buffer);
8083
8084 if let Some(new_position) = new_position {
8085 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8086 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8087 return;
8088 }
8089 }
8090
8091 nav_history.push(
8092 Some(NavigationData {
8093 cursor_anchor,
8094 cursor_position,
8095 scroll_anchor: scroll_state,
8096 scroll_top_row,
8097 }),
8098 cx,
8099 );
8100 }
8101 }
8102
8103 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8104 let buffer = self.buffer.read(cx).snapshot(cx);
8105 let mut selection = self.selections.first::<usize>(cx);
8106 selection.set_head(buffer.len(), SelectionGoal::None);
8107 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8108 s.select(vec![selection]);
8109 });
8110 }
8111
8112 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8113 let end = self.buffer.read(cx).read(cx).len();
8114 self.change_selections(None, cx, |s| {
8115 s.select_ranges(vec![0..end]);
8116 });
8117 }
8118
8119 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8120 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8121 let mut selections = self.selections.all::<Point>(cx);
8122 let max_point = display_map.buffer_snapshot.max_point();
8123 for selection in &mut selections {
8124 let rows = selection.spanned_rows(true, &display_map);
8125 selection.start = Point::new(rows.start.0, 0);
8126 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8127 selection.reversed = false;
8128 }
8129 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8130 s.select(selections);
8131 });
8132 }
8133
8134 pub fn split_selection_into_lines(
8135 &mut self,
8136 _: &SplitSelectionIntoLines,
8137 cx: &mut ViewContext<Self>,
8138 ) {
8139 let mut to_unfold = Vec::new();
8140 let mut new_selection_ranges = Vec::new();
8141 {
8142 let selections = self.selections.all::<Point>(cx);
8143 let buffer = self.buffer.read(cx).read(cx);
8144 for selection in selections {
8145 for row in selection.start.row..selection.end.row {
8146 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8147 new_selection_ranges.push(cursor..cursor);
8148 }
8149 new_selection_ranges.push(selection.end..selection.end);
8150 to_unfold.push(selection.start..selection.end);
8151 }
8152 }
8153 self.unfold_ranges(to_unfold, true, true, cx);
8154 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8155 s.select_ranges(new_selection_ranges);
8156 });
8157 }
8158
8159 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8160 self.add_selection(true, cx);
8161 }
8162
8163 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8164 self.add_selection(false, cx);
8165 }
8166
8167 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8168 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8169 let mut selections = self.selections.all::<Point>(cx);
8170 let text_layout_details = self.text_layout_details(cx);
8171 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8172 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8173 let range = oldest_selection.display_range(&display_map).sorted();
8174
8175 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8176 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8177 let positions = start_x.min(end_x)..start_x.max(end_x);
8178
8179 selections.clear();
8180 let mut stack = Vec::new();
8181 for row in range.start.row().0..=range.end.row().0 {
8182 if let Some(selection) = self.selections.build_columnar_selection(
8183 &display_map,
8184 DisplayRow(row),
8185 &positions,
8186 oldest_selection.reversed,
8187 &text_layout_details,
8188 ) {
8189 stack.push(selection.id);
8190 selections.push(selection);
8191 }
8192 }
8193
8194 if above {
8195 stack.reverse();
8196 }
8197
8198 AddSelectionsState { above, stack }
8199 });
8200
8201 let last_added_selection = *state.stack.last().unwrap();
8202 let mut new_selections = Vec::new();
8203 if above == state.above {
8204 let end_row = if above {
8205 DisplayRow(0)
8206 } else {
8207 display_map.max_point().row()
8208 };
8209
8210 'outer: for selection in selections {
8211 if selection.id == last_added_selection {
8212 let range = selection.display_range(&display_map).sorted();
8213 debug_assert_eq!(range.start.row(), range.end.row());
8214 let mut row = range.start.row();
8215 let positions =
8216 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8217 px(start)..px(end)
8218 } else {
8219 let start_x =
8220 display_map.x_for_display_point(range.start, &text_layout_details);
8221 let end_x =
8222 display_map.x_for_display_point(range.end, &text_layout_details);
8223 start_x.min(end_x)..start_x.max(end_x)
8224 };
8225
8226 while row != end_row {
8227 if above {
8228 row.0 -= 1;
8229 } else {
8230 row.0 += 1;
8231 }
8232
8233 if let Some(new_selection) = self.selections.build_columnar_selection(
8234 &display_map,
8235 row,
8236 &positions,
8237 selection.reversed,
8238 &text_layout_details,
8239 ) {
8240 state.stack.push(new_selection.id);
8241 if above {
8242 new_selections.push(new_selection);
8243 new_selections.push(selection);
8244 } else {
8245 new_selections.push(selection);
8246 new_selections.push(new_selection);
8247 }
8248
8249 continue 'outer;
8250 }
8251 }
8252 }
8253
8254 new_selections.push(selection);
8255 }
8256 } else {
8257 new_selections = selections;
8258 new_selections.retain(|s| s.id != last_added_selection);
8259 state.stack.pop();
8260 }
8261
8262 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8263 s.select(new_selections);
8264 });
8265 if state.stack.len() > 1 {
8266 self.add_selections_state = Some(state);
8267 }
8268 }
8269
8270 pub fn select_next_match_internal(
8271 &mut self,
8272 display_map: &DisplaySnapshot,
8273 replace_newest: bool,
8274 autoscroll: Option<Autoscroll>,
8275 cx: &mut ViewContext<Self>,
8276 ) -> Result<()> {
8277 fn select_next_match_ranges(
8278 this: &mut Editor,
8279 range: Range<usize>,
8280 replace_newest: bool,
8281 auto_scroll: Option<Autoscroll>,
8282 cx: &mut ViewContext<Editor>,
8283 ) {
8284 this.unfold_ranges([range.clone()], false, true, cx);
8285 this.change_selections(auto_scroll, cx, |s| {
8286 if replace_newest {
8287 s.delete(s.newest_anchor().id);
8288 }
8289 s.insert_range(range.clone());
8290 });
8291 }
8292
8293 let buffer = &display_map.buffer_snapshot;
8294 let mut selections = self.selections.all::<usize>(cx);
8295 if let Some(mut select_next_state) = self.select_next_state.take() {
8296 let query = &select_next_state.query;
8297 if !select_next_state.done {
8298 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8299 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8300 let mut next_selected_range = None;
8301
8302 let bytes_after_last_selection =
8303 buffer.bytes_in_range(last_selection.end..buffer.len());
8304 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8305 let query_matches = query
8306 .stream_find_iter(bytes_after_last_selection)
8307 .map(|result| (last_selection.end, result))
8308 .chain(
8309 query
8310 .stream_find_iter(bytes_before_first_selection)
8311 .map(|result| (0, result)),
8312 );
8313
8314 for (start_offset, query_match) in query_matches {
8315 let query_match = query_match.unwrap(); // can only fail due to I/O
8316 let offset_range =
8317 start_offset + query_match.start()..start_offset + query_match.end();
8318 let display_range = offset_range.start.to_display_point(display_map)
8319 ..offset_range.end.to_display_point(display_map);
8320
8321 if !select_next_state.wordwise
8322 || (!movement::is_inside_word(display_map, display_range.start)
8323 && !movement::is_inside_word(display_map, display_range.end))
8324 {
8325 // TODO: This is n^2, because we might check all the selections
8326 if !selections
8327 .iter()
8328 .any(|selection| selection.range().overlaps(&offset_range))
8329 {
8330 next_selected_range = Some(offset_range);
8331 break;
8332 }
8333 }
8334 }
8335
8336 if let Some(next_selected_range) = next_selected_range {
8337 select_next_match_ranges(
8338 self,
8339 next_selected_range,
8340 replace_newest,
8341 autoscroll,
8342 cx,
8343 );
8344 } else {
8345 select_next_state.done = true;
8346 }
8347 }
8348
8349 self.select_next_state = Some(select_next_state);
8350 } else {
8351 let mut only_carets = true;
8352 let mut same_text_selected = true;
8353 let mut selected_text = None;
8354
8355 let mut selections_iter = selections.iter().peekable();
8356 while let Some(selection) = selections_iter.next() {
8357 if selection.start != selection.end {
8358 only_carets = false;
8359 }
8360
8361 if same_text_selected {
8362 if selected_text.is_none() {
8363 selected_text =
8364 Some(buffer.text_for_range(selection.range()).collect::<String>());
8365 }
8366
8367 if let Some(next_selection) = selections_iter.peek() {
8368 if next_selection.range().len() == selection.range().len() {
8369 let next_selected_text = buffer
8370 .text_for_range(next_selection.range())
8371 .collect::<String>();
8372 if Some(next_selected_text) != selected_text {
8373 same_text_selected = false;
8374 selected_text = None;
8375 }
8376 } else {
8377 same_text_selected = false;
8378 selected_text = None;
8379 }
8380 }
8381 }
8382 }
8383
8384 if only_carets {
8385 for selection in &mut selections {
8386 let word_range = movement::surrounding_word(
8387 display_map,
8388 selection.start.to_display_point(display_map),
8389 );
8390 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8391 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8392 selection.goal = SelectionGoal::None;
8393 selection.reversed = false;
8394 select_next_match_ranges(
8395 self,
8396 selection.start..selection.end,
8397 replace_newest,
8398 autoscroll,
8399 cx,
8400 );
8401 }
8402
8403 if selections.len() == 1 {
8404 let selection = selections
8405 .last()
8406 .expect("ensured that there's only one selection");
8407 let query = buffer
8408 .text_for_range(selection.start..selection.end)
8409 .collect::<String>();
8410 let is_empty = query.is_empty();
8411 let select_state = SelectNextState {
8412 query: AhoCorasick::new(&[query])?,
8413 wordwise: true,
8414 done: is_empty,
8415 };
8416 self.select_next_state = Some(select_state);
8417 } else {
8418 self.select_next_state = None;
8419 }
8420 } else if let Some(selected_text) = selected_text {
8421 self.select_next_state = Some(SelectNextState {
8422 query: AhoCorasick::new(&[selected_text])?,
8423 wordwise: false,
8424 done: false,
8425 });
8426 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8427 }
8428 }
8429 Ok(())
8430 }
8431
8432 pub fn select_all_matches(
8433 &mut self,
8434 _action: &SelectAllMatches,
8435 cx: &mut ViewContext<Self>,
8436 ) -> Result<()> {
8437 self.push_to_selection_history();
8438 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8439
8440 self.select_next_match_internal(&display_map, false, None, cx)?;
8441 let Some(select_next_state) = self.select_next_state.as_mut() else {
8442 return Ok(());
8443 };
8444 if select_next_state.done {
8445 return Ok(());
8446 }
8447
8448 let mut new_selections = self.selections.all::<usize>(cx);
8449
8450 let buffer = &display_map.buffer_snapshot;
8451 let query_matches = select_next_state
8452 .query
8453 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8454
8455 for query_match in query_matches {
8456 let query_match = query_match.unwrap(); // can only fail due to I/O
8457 let offset_range = query_match.start()..query_match.end();
8458 let display_range = offset_range.start.to_display_point(&display_map)
8459 ..offset_range.end.to_display_point(&display_map);
8460
8461 if !select_next_state.wordwise
8462 || (!movement::is_inside_word(&display_map, display_range.start)
8463 && !movement::is_inside_word(&display_map, display_range.end))
8464 {
8465 self.selections.change_with(cx, |selections| {
8466 new_selections.push(Selection {
8467 id: selections.new_selection_id(),
8468 start: offset_range.start,
8469 end: offset_range.end,
8470 reversed: false,
8471 goal: SelectionGoal::None,
8472 });
8473 });
8474 }
8475 }
8476
8477 new_selections.sort_by_key(|selection| selection.start);
8478 let mut ix = 0;
8479 while ix + 1 < new_selections.len() {
8480 let current_selection = &new_selections[ix];
8481 let next_selection = &new_selections[ix + 1];
8482 if current_selection.range().overlaps(&next_selection.range()) {
8483 if current_selection.id < next_selection.id {
8484 new_selections.remove(ix + 1);
8485 } else {
8486 new_selections.remove(ix);
8487 }
8488 } else {
8489 ix += 1;
8490 }
8491 }
8492
8493 select_next_state.done = true;
8494 self.unfold_ranges(
8495 new_selections.iter().map(|selection| selection.range()),
8496 false,
8497 false,
8498 cx,
8499 );
8500 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8501 selections.select(new_selections)
8502 });
8503
8504 Ok(())
8505 }
8506
8507 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8508 self.push_to_selection_history();
8509 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8510 self.select_next_match_internal(
8511 &display_map,
8512 action.replace_newest,
8513 Some(Autoscroll::newest()),
8514 cx,
8515 )?;
8516 Ok(())
8517 }
8518
8519 pub fn select_previous(
8520 &mut self,
8521 action: &SelectPrevious,
8522 cx: &mut ViewContext<Self>,
8523 ) -> Result<()> {
8524 self.push_to_selection_history();
8525 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8526 let buffer = &display_map.buffer_snapshot;
8527 let mut selections = self.selections.all::<usize>(cx);
8528 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8529 let query = &select_prev_state.query;
8530 if !select_prev_state.done {
8531 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8532 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8533 let mut next_selected_range = None;
8534 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8535 let bytes_before_last_selection =
8536 buffer.reversed_bytes_in_range(0..last_selection.start);
8537 let bytes_after_first_selection =
8538 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8539 let query_matches = query
8540 .stream_find_iter(bytes_before_last_selection)
8541 .map(|result| (last_selection.start, result))
8542 .chain(
8543 query
8544 .stream_find_iter(bytes_after_first_selection)
8545 .map(|result| (buffer.len(), result)),
8546 );
8547 for (end_offset, query_match) in query_matches {
8548 let query_match = query_match.unwrap(); // can only fail due to I/O
8549 let offset_range =
8550 end_offset - query_match.end()..end_offset - query_match.start();
8551 let display_range = offset_range.start.to_display_point(&display_map)
8552 ..offset_range.end.to_display_point(&display_map);
8553
8554 if !select_prev_state.wordwise
8555 || (!movement::is_inside_word(&display_map, display_range.start)
8556 && !movement::is_inside_word(&display_map, display_range.end))
8557 {
8558 next_selected_range = Some(offset_range);
8559 break;
8560 }
8561 }
8562
8563 if let Some(next_selected_range) = next_selected_range {
8564 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8565 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8566 if action.replace_newest {
8567 s.delete(s.newest_anchor().id);
8568 }
8569 s.insert_range(next_selected_range);
8570 });
8571 } else {
8572 select_prev_state.done = true;
8573 }
8574 }
8575
8576 self.select_prev_state = Some(select_prev_state);
8577 } else {
8578 let mut only_carets = true;
8579 let mut same_text_selected = true;
8580 let mut selected_text = None;
8581
8582 let mut selections_iter = selections.iter().peekable();
8583 while let Some(selection) = selections_iter.next() {
8584 if selection.start != selection.end {
8585 only_carets = false;
8586 }
8587
8588 if same_text_selected {
8589 if selected_text.is_none() {
8590 selected_text =
8591 Some(buffer.text_for_range(selection.range()).collect::<String>());
8592 }
8593
8594 if let Some(next_selection) = selections_iter.peek() {
8595 if next_selection.range().len() == selection.range().len() {
8596 let next_selected_text = buffer
8597 .text_for_range(next_selection.range())
8598 .collect::<String>();
8599 if Some(next_selected_text) != selected_text {
8600 same_text_selected = false;
8601 selected_text = None;
8602 }
8603 } else {
8604 same_text_selected = false;
8605 selected_text = None;
8606 }
8607 }
8608 }
8609 }
8610
8611 if only_carets {
8612 for selection in &mut selections {
8613 let word_range = movement::surrounding_word(
8614 &display_map,
8615 selection.start.to_display_point(&display_map),
8616 );
8617 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8618 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8619 selection.goal = SelectionGoal::None;
8620 selection.reversed = false;
8621 }
8622 if selections.len() == 1 {
8623 let selection = selections
8624 .last()
8625 .expect("ensured that there's only one selection");
8626 let query = buffer
8627 .text_for_range(selection.start..selection.end)
8628 .collect::<String>();
8629 let is_empty = query.is_empty();
8630 let select_state = SelectNextState {
8631 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8632 wordwise: true,
8633 done: is_empty,
8634 };
8635 self.select_prev_state = Some(select_state);
8636 } else {
8637 self.select_prev_state = None;
8638 }
8639
8640 self.unfold_ranges(
8641 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8642 false,
8643 true,
8644 cx,
8645 );
8646 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8647 s.select(selections);
8648 });
8649 } else if let Some(selected_text) = selected_text {
8650 self.select_prev_state = Some(SelectNextState {
8651 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8652 wordwise: false,
8653 done: false,
8654 });
8655 self.select_previous(action, cx)?;
8656 }
8657 }
8658 Ok(())
8659 }
8660
8661 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8662 let text_layout_details = &self.text_layout_details(cx);
8663 self.transact(cx, |this, cx| {
8664 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8665 let mut edits = Vec::new();
8666 let mut selection_edit_ranges = Vec::new();
8667 let mut last_toggled_row = None;
8668 let snapshot = this.buffer.read(cx).read(cx);
8669 let empty_str: Arc<str> = Arc::default();
8670 let mut suffixes_inserted = Vec::new();
8671
8672 fn comment_prefix_range(
8673 snapshot: &MultiBufferSnapshot,
8674 row: MultiBufferRow,
8675 comment_prefix: &str,
8676 comment_prefix_whitespace: &str,
8677 ) -> Range<Point> {
8678 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8679
8680 let mut line_bytes = snapshot
8681 .bytes_in_range(start..snapshot.max_point())
8682 .flatten()
8683 .copied();
8684
8685 // If this line currently begins with the line comment prefix, then record
8686 // the range containing the prefix.
8687 if line_bytes
8688 .by_ref()
8689 .take(comment_prefix.len())
8690 .eq(comment_prefix.bytes())
8691 {
8692 // Include any whitespace that matches the comment prefix.
8693 let matching_whitespace_len = line_bytes
8694 .zip(comment_prefix_whitespace.bytes())
8695 .take_while(|(a, b)| a == b)
8696 .count() as u32;
8697 let end = Point::new(
8698 start.row,
8699 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8700 );
8701 start..end
8702 } else {
8703 start..start
8704 }
8705 }
8706
8707 fn comment_suffix_range(
8708 snapshot: &MultiBufferSnapshot,
8709 row: MultiBufferRow,
8710 comment_suffix: &str,
8711 comment_suffix_has_leading_space: bool,
8712 ) -> Range<Point> {
8713 let end = Point::new(row.0, snapshot.line_len(row));
8714 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8715
8716 let mut line_end_bytes = snapshot
8717 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8718 .flatten()
8719 .copied();
8720
8721 let leading_space_len = if suffix_start_column > 0
8722 && line_end_bytes.next() == Some(b' ')
8723 && comment_suffix_has_leading_space
8724 {
8725 1
8726 } else {
8727 0
8728 };
8729
8730 // If this line currently begins with the line comment prefix, then record
8731 // the range containing the prefix.
8732 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8733 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8734 start..end
8735 } else {
8736 end..end
8737 }
8738 }
8739
8740 // TODO: Handle selections that cross excerpts
8741 for selection in &mut selections {
8742 let start_column = snapshot
8743 .indent_size_for_line(MultiBufferRow(selection.start.row))
8744 .len;
8745 let language = if let Some(language) =
8746 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8747 {
8748 language
8749 } else {
8750 continue;
8751 };
8752
8753 selection_edit_ranges.clear();
8754
8755 // If multiple selections contain a given row, avoid processing that
8756 // row more than once.
8757 let mut start_row = MultiBufferRow(selection.start.row);
8758 if last_toggled_row == Some(start_row) {
8759 start_row = start_row.next_row();
8760 }
8761 let end_row =
8762 if selection.end.row > selection.start.row && selection.end.column == 0 {
8763 MultiBufferRow(selection.end.row - 1)
8764 } else {
8765 MultiBufferRow(selection.end.row)
8766 };
8767 last_toggled_row = Some(end_row);
8768
8769 if start_row > end_row {
8770 continue;
8771 }
8772
8773 // If the language has line comments, toggle those.
8774 let full_comment_prefixes = language.line_comment_prefixes();
8775 if !full_comment_prefixes.is_empty() {
8776 let first_prefix = full_comment_prefixes
8777 .first()
8778 .expect("prefixes is non-empty");
8779 let prefix_trimmed_lengths = full_comment_prefixes
8780 .iter()
8781 .map(|p| p.trim_end_matches(' ').len())
8782 .collect::<SmallVec<[usize; 4]>>();
8783
8784 let mut all_selection_lines_are_comments = true;
8785
8786 for row in start_row.0..=end_row.0 {
8787 let row = MultiBufferRow(row);
8788 if start_row < end_row && snapshot.is_line_blank(row) {
8789 continue;
8790 }
8791
8792 let prefix_range = full_comment_prefixes
8793 .iter()
8794 .zip(prefix_trimmed_lengths.iter().copied())
8795 .map(|(prefix, trimmed_prefix_len)| {
8796 comment_prefix_range(
8797 snapshot.deref(),
8798 row,
8799 &prefix[..trimmed_prefix_len],
8800 &prefix[trimmed_prefix_len..],
8801 )
8802 })
8803 .max_by_key(|range| range.end.column - range.start.column)
8804 .expect("prefixes is non-empty");
8805
8806 if prefix_range.is_empty() {
8807 all_selection_lines_are_comments = false;
8808 }
8809
8810 selection_edit_ranges.push(prefix_range);
8811 }
8812
8813 if all_selection_lines_are_comments {
8814 edits.extend(
8815 selection_edit_ranges
8816 .iter()
8817 .cloned()
8818 .map(|range| (range, empty_str.clone())),
8819 );
8820 } else {
8821 let min_column = selection_edit_ranges
8822 .iter()
8823 .map(|range| range.start.column)
8824 .min()
8825 .unwrap_or(0);
8826 edits.extend(selection_edit_ranges.iter().map(|range| {
8827 let position = Point::new(range.start.row, min_column);
8828 (position..position, first_prefix.clone())
8829 }));
8830 }
8831 } else if let Some((full_comment_prefix, comment_suffix)) =
8832 language.block_comment_delimiters()
8833 {
8834 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8835 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8836 let prefix_range = comment_prefix_range(
8837 snapshot.deref(),
8838 start_row,
8839 comment_prefix,
8840 comment_prefix_whitespace,
8841 );
8842 let suffix_range = comment_suffix_range(
8843 snapshot.deref(),
8844 end_row,
8845 comment_suffix.trim_start_matches(' '),
8846 comment_suffix.starts_with(' '),
8847 );
8848
8849 if prefix_range.is_empty() || suffix_range.is_empty() {
8850 edits.push((
8851 prefix_range.start..prefix_range.start,
8852 full_comment_prefix.clone(),
8853 ));
8854 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8855 suffixes_inserted.push((end_row, comment_suffix.len()));
8856 } else {
8857 edits.push((prefix_range, empty_str.clone()));
8858 edits.push((suffix_range, empty_str.clone()));
8859 }
8860 } else {
8861 continue;
8862 }
8863 }
8864
8865 drop(snapshot);
8866 this.buffer.update(cx, |buffer, cx| {
8867 buffer.edit(edits, None, cx);
8868 });
8869
8870 // Adjust selections so that they end before any comment suffixes that
8871 // were inserted.
8872 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8873 let mut selections = this.selections.all::<Point>(cx);
8874 let snapshot = this.buffer.read(cx).read(cx);
8875 for selection in &mut selections {
8876 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8877 match row.cmp(&MultiBufferRow(selection.end.row)) {
8878 Ordering::Less => {
8879 suffixes_inserted.next();
8880 continue;
8881 }
8882 Ordering::Greater => break,
8883 Ordering::Equal => {
8884 if selection.end.column == snapshot.line_len(row) {
8885 if selection.is_empty() {
8886 selection.start.column -= suffix_len as u32;
8887 }
8888 selection.end.column -= suffix_len as u32;
8889 }
8890 break;
8891 }
8892 }
8893 }
8894 }
8895
8896 drop(snapshot);
8897 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8898
8899 let selections = this.selections.all::<Point>(cx);
8900 let selections_on_single_row = selections.windows(2).all(|selections| {
8901 selections[0].start.row == selections[1].start.row
8902 && selections[0].end.row == selections[1].end.row
8903 && selections[0].start.row == selections[0].end.row
8904 });
8905 let selections_selecting = selections
8906 .iter()
8907 .any(|selection| selection.start != selection.end);
8908 let advance_downwards = action.advance_downwards
8909 && selections_on_single_row
8910 && !selections_selecting
8911 && !matches!(this.mode, EditorMode::SingleLine { .. });
8912
8913 if advance_downwards {
8914 let snapshot = this.buffer.read(cx).snapshot(cx);
8915
8916 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8917 s.move_cursors_with(|display_snapshot, display_point, _| {
8918 let mut point = display_point.to_point(display_snapshot);
8919 point.row += 1;
8920 point = snapshot.clip_point(point, Bias::Left);
8921 let display_point = point.to_display_point(display_snapshot);
8922 let goal = SelectionGoal::HorizontalPosition(
8923 display_snapshot
8924 .x_for_display_point(display_point, text_layout_details)
8925 .into(),
8926 );
8927 (display_point, goal)
8928 })
8929 });
8930 }
8931 });
8932 }
8933
8934 pub fn select_enclosing_symbol(
8935 &mut self,
8936 _: &SelectEnclosingSymbol,
8937 cx: &mut ViewContext<Self>,
8938 ) {
8939 let buffer = self.buffer.read(cx).snapshot(cx);
8940 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8941
8942 fn update_selection(
8943 selection: &Selection<usize>,
8944 buffer_snap: &MultiBufferSnapshot,
8945 ) -> Option<Selection<usize>> {
8946 let cursor = selection.head();
8947 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8948 for symbol in symbols.iter().rev() {
8949 let start = symbol.range.start.to_offset(buffer_snap);
8950 let end = symbol.range.end.to_offset(buffer_snap);
8951 let new_range = start..end;
8952 if start < selection.start || end > selection.end {
8953 return Some(Selection {
8954 id: selection.id,
8955 start: new_range.start,
8956 end: new_range.end,
8957 goal: SelectionGoal::None,
8958 reversed: selection.reversed,
8959 });
8960 }
8961 }
8962 None
8963 }
8964
8965 let mut selected_larger_symbol = false;
8966 let new_selections = old_selections
8967 .iter()
8968 .map(|selection| match update_selection(selection, &buffer) {
8969 Some(new_selection) => {
8970 if new_selection.range() != selection.range() {
8971 selected_larger_symbol = true;
8972 }
8973 new_selection
8974 }
8975 None => selection.clone(),
8976 })
8977 .collect::<Vec<_>>();
8978
8979 if selected_larger_symbol {
8980 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8981 s.select(new_selections);
8982 });
8983 }
8984 }
8985
8986 pub fn select_larger_syntax_node(
8987 &mut self,
8988 _: &SelectLargerSyntaxNode,
8989 cx: &mut ViewContext<Self>,
8990 ) {
8991 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8992 let buffer = self.buffer.read(cx).snapshot(cx);
8993 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8994
8995 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8996 let mut selected_larger_node = false;
8997 let new_selections = old_selections
8998 .iter()
8999 .map(|selection| {
9000 let old_range = selection.start..selection.end;
9001 let mut new_range = old_range.clone();
9002 while let Some(containing_range) =
9003 buffer.range_for_syntax_ancestor(new_range.clone())
9004 {
9005 new_range = containing_range;
9006 if !display_map.intersects_fold(new_range.start)
9007 && !display_map.intersects_fold(new_range.end)
9008 {
9009 break;
9010 }
9011 }
9012
9013 selected_larger_node |= new_range != old_range;
9014 Selection {
9015 id: selection.id,
9016 start: new_range.start,
9017 end: new_range.end,
9018 goal: SelectionGoal::None,
9019 reversed: selection.reversed,
9020 }
9021 })
9022 .collect::<Vec<_>>();
9023
9024 if selected_larger_node {
9025 stack.push(old_selections);
9026 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9027 s.select(new_selections);
9028 });
9029 }
9030 self.select_larger_syntax_node_stack = stack;
9031 }
9032
9033 pub fn select_smaller_syntax_node(
9034 &mut self,
9035 _: &SelectSmallerSyntaxNode,
9036 cx: &mut ViewContext<Self>,
9037 ) {
9038 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9039 if let Some(selections) = stack.pop() {
9040 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9041 s.select(selections.to_vec());
9042 });
9043 }
9044 self.select_larger_syntax_node_stack = stack;
9045 }
9046
9047 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9048 if !EditorSettings::get_global(cx).gutter.runnables {
9049 self.clear_tasks();
9050 return Task::ready(());
9051 }
9052 let project = self.project.clone();
9053 cx.spawn(|this, mut cx| async move {
9054 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9055 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9056 }) else {
9057 return;
9058 };
9059
9060 let Some(project) = project else {
9061 return;
9062 };
9063
9064 let hide_runnables = project
9065 .update(&mut cx, |project, cx| {
9066 // Do not display any test indicators in non-dev server remote projects.
9067 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9068 })
9069 .unwrap_or(true);
9070 if hide_runnables {
9071 return;
9072 }
9073 let new_rows =
9074 cx.background_executor()
9075 .spawn({
9076 let snapshot = display_snapshot.clone();
9077 async move {
9078 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9079 }
9080 })
9081 .await;
9082 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9083
9084 this.update(&mut cx, |this, _| {
9085 this.clear_tasks();
9086 for (key, value) in rows {
9087 this.insert_tasks(key, value);
9088 }
9089 })
9090 .ok();
9091 })
9092 }
9093 fn fetch_runnable_ranges(
9094 snapshot: &DisplaySnapshot,
9095 range: Range<Anchor>,
9096 ) -> Vec<language::RunnableRange> {
9097 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9098 }
9099
9100 fn runnable_rows(
9101 project: Model<Project>,
9102 snapshot: DisplaySnapshot,
9103 runnable_ranges: Vec<RunnableRange>,
9104 mut cx: AsyncWindowContext,
9105 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9106 runnable_ranges
9107 .into_iter()
9108 .filter_map(|mut runnable| {
9109 let tasks = cx
9110 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9111 .ok()?;
9112 if tasks.is_empty() {
9113 return None;
9114 }
9115
9116 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9117
9118 let row = snapshot
9119 .buffer_snapshot
9120 .buffer_line_for_row(MultiBufferRow(point.row))?
9121 .1
9122 .start
9123 .row;
9124
9125 let context_range =
9126 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9127 Some((
9128 (runnable.buffer_id, row),
9129 RunnableTasks {
9130 templates: tasks,
9131 offset: MultiBufferOffset(runnable.run_range.start),
9132 context_range,
9133 column: point.column,
9134 extra_variables: runnable.extra_captures,
9135 },
9136 ))
9137 })
9138 .collect()
9139 }
9140
9141 fn templates_with_tags(
9142 project: &Model<Project>,
9143 runnable: &mut Runnable,
9144 cx: &WindowContext<'_>,
9145 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9146 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9147 let (worktree_id, file) = project
9148 .buffer_for_id(runnable.buffer, cx)
9149 .and_then(|buffer| buffer.read(cx).file())
9150 .map(|file| (file.worktree_id(cx), file.clone()))
9151 .unzip();
9152
9153 (
9154 project.task_store().read(cx).task_inventory().cloned(),
9155 worktree_id,
9156 file,
9157 )
9158 });
9159
9160 let tags = mem::take(&mut runnable.tags);
9161 let mut tags: Vec<_> = tags
9162 .into_iter()
9163 .flat_map(|tag| {
9164 let tag = tag.0.clone();
9165 inventory
9166 .as_ref()
9167 .into_iter()
9168 .flat_map(|inventory| {
9169 inventory.read(cx).list_tasks(
9170 file.clone(),
9171 Some(runnable.language.clone()),
9172 worktree_id,
9173 cx,
9174 )
9175 })
9176 .filter(move |(_, template)| {
9177 template.tags.iter().any(|source_tag| source_tag == &tag)
9178 })
9179 })
9180 .sorted_by_key(|(kind, _)| kind.to_owned())
9181 .collect();
9182 if let Some((leading_tag_source, _)) = tags.first() {
9183 // Strongest source wins; if we have worktree tag binding, prefer that to
9184 // global and language bindings;
9185 // if we have a global binding, prefer that to language binding.
9186 let first_mismatch = tags
9187 .iter()
9188 .position(|(tag_source, _)| tag_source != leading_tag_source);
9189 if let Some(index) = first_mismatch {
9190 tags.truncate(index);
9191 }
9192 }
9193
9194 tags
9195 }
9196
9197 pub fn move_to_enclosing_bracket(
9198 &mut self,
9199 _: &MoveToEnclosingBracket,
9200 cx: &mut ViewContext<Self>,
9201 ) {
9202 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9203 s.move_offsets_with(|snapshot, selection| {
9204 let Some(enclosing_bracket_ranges) =
9205 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9206 else {
9207 return;
9208 };
9209
9210 let mut best_length = usize::MAX;
9211 let mut best_inside = false;
9212 let mut best_in_bracket_range = false;
9213 let mut best_destination = None;
9214 for (open, close) in enclosing_bracket_ranges {
9215 let close = close.to_inclusive();
9216 let length = close.end() - open.start;
9217 let inside = selection.start >= open.end && selection.end <= *close.start();
9218 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9219 || close.contains(&selection.head());
9220
9221 // If best is next to a bracket and current isn't, skip
9222 if !in_bracket_range && best_in_bracket_range {
9223 continue;
9224 }
9225
9226 // Prefer smaller lengths unless best is inside and current isn't
9227 if length > best_length && (best_inside || !inside) {
9228 continue;
9229 }
9230
9231 best_length = length;
9232 best_inside = inside;
9233 best_in_bracket_range = in_bracket_range;
9234 best_destination = Some(
9235 if close.contains(&selection.start) && close.contains(&selection.end) {
9236 if inside {
9237 open.end
9238 } else {
9239 open.start
9240 }
9241 } else if inside {
9242 *close.start()
9243 } else {
9244 *close.end()
9245 },
9246 );
9247 }
9248
9249 if let Some(destination) = best_destination {
9250 selection.collapse_to(destination, SelectionGoal::None);
9251 }
9252 })
9253 });
9254 }
9255
9256 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9257 self.end_selection(cx);
9258 self.selection_history.mode = SelectionHistoryMode::Undoing;
9259 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9260 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9261 self.select_next_state = entry.select_next_state;
9262 self.select_prev_state = entry.select_prev_state;
9263 self.add_selections_state = entry.add_selections_state;
9264 self.request_autoscroll(Autoscroll::newest(), cx);
9265 }
9266 self.selection_history.mode = SelectionHistoryMode::Normal;
9267 }
9268
9269 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9270 self.end_selection(cx);
9271 self.selection_history.mode = SelectionHistoryMode::Redoing;
9272 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9273 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9274 self.select_next_state = entry.select_next_state;
9275 self.select_prev_state = entry.select_prev_state;
9276 self.add_selections_state = entry.add_selections_state;
9277 self.request_autoscroll(Autoscroll::newest(), cx);
9278 }
9279 self.selection_history.mode = SelectionHistoryMode::Normal;
9280 }
9281
9282 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9283 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9284 }
9285
9286 pub fn expand_excerpts_down(
9287 &mut self,
9288 action: &ExpandExcerptsDown,
9289 cx: &mut ViewContext<Self>,
9290 ) {
9291 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9292 }
9293
9294 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9295 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9296 }
9297
9298 pub fn expand_excerpts_for_direction(
9299 &mut self,
9300 lines: u32,
9301 direction: ExpandExcerptDirection,
9302 cx: &mut ViewContext<Self>,
9303 ) {
9304 let selections = self.selections.disjoint_anchors();
9305
9306 let lines = if lines == 0 {
9307 EditorSettings::get_global(cx).expand_excerpt_lines
9308 } else {
9309 lines
9310 };
9311
9312 self.buffer.update(cx, |buffer, cx| {
9313 buffer.expand_excerpts(
9314 selections
9315 .iter()
9316 .map(|selection| selection.head().excerpt_id)
9317 .dedup(),
9318 lines,
9319 direction,
9320 cx,
9321 )
9322 })
9323 }
9324
9325 pub fn expand_excerpt(
9326 &mut self,
9327 excerpt: ExcerptId,
9328 direction: ExpandExcerptDirection,
9329 cx: &mut ViewContext<Self>,
9330 ) {
9331 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9332 self.buffer.update(cx, |buffer, cx| {
9333 buffer.expand_excerpts([excerpt], lines, direction, cx)
9334 })
9335 }
9336
9337 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9338 self.go_to_diagnostic_impl(Direction::Next, cx)
9339 }
9340
9341 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9342 self.go_to_diagnostic_impl(Direction::Prev, cx)
9343 }
9344
9345 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9346 let buffer = self.buffer.read(cx).snapshot(cx);
9347 let selection = self.selections.newest::<usize>(cx);
9348
9349 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9350 if direction == Direction::Next {
9351 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9352 let (group_id, jump_to) = popover.activation_info();
9353 if self.activate_diagnostics(group_id, cx) {
9354 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9355 let mut new_selection = s.newest_anchor().clone();
9356 new_selection.collapse_to(jump_to, SelectionGoal::None);
9357 s.select_anchors(vec![new_selection.clone()]);
9358 });
9359 }
9360 return;
9361 }
9362 }
9363
9364 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9365 active_diagnostics
9366 .primary_range
9367 .to_offset(&buffer)
9368 .to_inclusive()
9369 });
9370 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9371 if active_primary_range.contains(&selection.head()) {
9372 *active_primary_range.start()
9373 } else {
9374 selection.head()
9375 }
9376 } else {
9377 selection.head()
9378 };
9379 let snapshot = self.snapshot(cx);
9380 loop {
9381 let diagnostics = if direction == Direction::Prev {
9382 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9383 } else {
9384 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9385 }
9386 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9387 let group = diagnostics
9388 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9389 // be sorted in a stable way
9390 // skip until we are at current active diagnostic, if it exists
9391 .skip_while(|entry| {
9392 (match direction {
9393 Direction::Prev => entry.range.start >= search_start,
9394 Direction::Next => entry.range.start <= search_start,
9395 }) && self
9396 .active_diagnostics
9397 .as_ref()
9398 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9399 })
9400 .find_map(|entry| {
9401 if entry.diagnostic.is_primary
9402 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9403 && !entry.range.is_empty()
9404 // if we match with the active diagnostic, skip it
9405 && Some(entry.diagnostic.group_id)
9406 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9407 {
9408 Some((entry.range, entry.diagnostic.group_id))
9409 } else {
9410 None
9411 }
9412 });
9413
9414 if let Some((primary_range, group_id)) = group {
9415 if self.activate_diagnostics(group_id, cx) {
9416 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9417 s.select(vec![Selection {
9418 id: selection.id,
9419 start: primary_range.start,
9420 end: primary_range.start,
9421 reversed: false,
9422 goal: SelectionGoal::None,
9423 }]);
9424 });
9425 }
9426 break;
9427 } else {
9428 // Cycle around to the start of the buffer, potentially moving back to the start of
9429 // the currently active diagnostic.
9430 active_primary_range.take();
9431 if direction == Direction::Prev {
9432 if search_start == buffer.len() {
9433 break;
9434 } else {
9435 search_start = buffer.len();
9436 }
9437 } else if search_start == 0 {
9438 break;
9439 } else {
9440 search_start = 0;
9441 }
9442 }
9443 }
9444 }
9445
9446 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9447 let snapshot = self
9448 .display_map
9449 .update(cx, |display_map, cx| display_map.snapshot(cx));
9450 let selection = self.selections.newest::<Point>(cx);
9451 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9452 }
9453
9454 fn go_to_hunk_after_position(
9455 &mut self,
9456 snapshot: &DisplaySnapshot,
9457 position: Point,
9458 cx: &mut ViewContext<'_, Editor>,
9459 ) -> Option<MultiBufferDiffHunk> {
9460 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9461 snapshot,
9462 position,
9463 false,
9464 snapshot
9465 .buffer_snapshot
9466 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9467 cx,
9468 ) {
9469 return Some(hunk);
9470 }
9471
9472 let wrapped_point = Point::zero();
9473 self.go_to_next_hunk_in_direction(
9474 snapshot,
9475 wrapped_point,
9476 true,
9477 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9478 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9479 ),
9480 cx,
9481 )
9482 }
9483
9484 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9485 let snapshot = self
9486 .display_map
9487 .update(cx, |display_map, cx| display_map.snapshot(cx));
9488 let selection = self.selections.newest::<Point>(cx);
9489
9490 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9491 }
9492
9493 fn go_to_hunk_before_position(
9494 &mut self,
9495 snapshot: &DisplaySnapshot,
9496 position: Point,
9497 cx: &mut ViewContext<'_, Editor>,
9498 ) -> Option<MultiBufferDiffHunk> {
9499 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9500 snapshot,
9501 position,
9502 false,
9503 snapshot
9504 .buffer_snapshot
9505 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9506 cx,
9507 ) {
9508 return Some(hunk);
9509 }
9510
9511 let wrapped_point = snapshot.buffer_snapshot.max_point();
9512 self.go_to_next_hunk_in_direction(
9513 snapshot,
9514 wrapped_point,
9515 true,
9516 snapshot
9517 .buffer_snapshot
9518 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9519 cx,
9520 )
9521 }
9522
9523 fn go_to_next_hunk_in_direction(
9524 &mut self,
9525 snapshot: &DisplaySnapshot,
9526 initial_point: Point,
9527 is_wrapped: bool,
9528 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9529 cx: &mut ViewContext<Editor>,
9530 ) -> Option<MultiBufferDiffHunk> {
9531 let display_point = initial_point.to_display_point(snapshot);
9532 let mut hunks = hunks
9533 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9534 .filter(|(display_hunk, _)| {
9535 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9536 })
9537 .dedup();
9538
9539 if let Some((display_hunk, hunk)) = hunks.next() {
9540 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9541 let row = display_hunk.start_display_row();
9542 let point = DisplayPoint::new(row, 0);
9543 s.select_display_ranges([point..point]);
9544 });
9545
9546 Some(hunk)
9547 } else {
9548 None
9549 }
9550 }
9551
9552 pub fn go_to_definition(
9553 &mut self,
9554 _: &GoToDefinition,
9555 cx: &mut ViewContext<Self>,
9556 ) -> Task<Result<Navigated>> {
9557 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9558 cx.spawn(|editor, mut cx| async move {
9559 if definition.await? == Navigated::Yes {
9560 return Ok(Navigated::Yes);
9561 }
9562 match editor.update(&mut cx, |editor, cx| {
9563 editor.find_all_references(&FindAllReferences, cx)
9564 })? {
9565 Some(references) => references.await,
9566 None => Ok(Navigated::No),
9567 }
9568 })
9569 }
9570
9571 pub fn go_to_declaration(
9572 &mut self,
9573 _: &GoToDeclaration,
9574 cx: &mut ViewContext<Self>,
9575 ) -> Task<Result<Navigated>> {
9576 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9577 }
9578
9579 pub fn go_to_declaration_split(
9580 &mut self,
9581 _: &GoToDeclaration,
9582 cx: &mut ViewContext<Self>,
9583 ) -> Task<Result<Navigated>> {
9584 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9585 }
9586
9587 pub fn go_to_implementation(
9588 &mut self,
9589 _: &GoToImplementation,
9590 cx: &mut ViewContext<Self>,
9591 ) -> Task<Result<Navigated>> {
9592 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9593 }
9594
9595 pub fn go_to_implementation_split(
9596 &mut self,
9597 _: &GoToImplementationSplit,
9598 cx: &mut ViewContext<Self>,
9599 ) -> Task<Result<Navigated>> {
9600 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9601 }
9602
9603 pub fn go_to_type_definition(
9604 &mut self,
9605 _: &GoToTypeDefinition,
9606 cx: &mut ViewContext<Self>,
9607 ) -> Task<Result<Navigated>> {
9608 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9609 }
9610
9611 pub fn go_to_definition_split(
9612 &mut self,
9613 _: &GoToDefinitionSplit,
9614 cx: &mut ViewContext<Self>,
9615 ) -> Task<Result<Navigated>> {
9616 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9617 }
9618
9619 pub fn go_to_type_definition_split(
9620 &mut self,
9621 _: &GoToTypeDefinitionSplit,
9622 cx: &mut ViewContext<Self>,
9623 ) -> Task<Result<Navigated>> {
9624 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9625 }
9626
9627 fn go_to_definition_of_kind(
9628 &mut self,
9629 kind: GotoDefinitionKind,
9630 split: bool,
9631 cx: &mut ViewContext<Self>,
9632 ) -> Task<Result<Navigated>> {
9633 let Some(provider) = self.semantics_provider.clone() else {
9634 return Task::ready(Ok(Navigated::No));
9635 };
9636 let buffer = self.buffer.read(cx);
9637 let head = self.selections.newest::<usize>(cx).head();
9638 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9639 text_anchor
9640 } else {
9641 return Task::ready(Ok(Navigated::No));
9642 };
9643
9644 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9645 return Task::ready(Ok(Navigated::No));
9646 };
9647
9648 cx.spawn(|editor, mut cx| async move {
9649 let definitions = definitions.await?;
9650 let navigated = editor
9651 .update(&mut cx, |editor, cx| {
9652 editor.navigate_to_hover_links(
9653 Some(kind),
9654 definitions
9655 .into_iter()
9656 .filter(|location| {
9657 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9658 })
9659 .map(HoverLink::Text)
9660 .collect::<Vec<_>>(),
9661 split,
9662 cx,
9663 )
9664 })?
9665 .await?;
9666 anyhow::Ok(navigated)
9667 })
9668 }
9669
9670 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9671 let position = self.selections.newest_anchor().head();
9672 let Some((buffer, buffer_position)) =
9673 self.buffer.read(cx).text_anchor_for_position(position, cx)
9674 else {
9675 return;
9676 };
9677
9678 cx.spawn(|editor, mut cx| async move {
9679 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9680 editor.update(&mut cx, |_, cx| {
9681 cx.open_url(&url);
9682 })
9683 } else {
9684 Ok(())
9685 }
9686 })
9687 .detach();
9688 }
9689
9690 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9691 let Some(workspace) = self.workspace() else {
9692 return;
9693 };
9694
9695 let position = self.selections.newest_anchor().head();
9696
9697 let Some((buffer, buffer_position)) =
9698 self.buffer.read(cx).text_anchor_for_position(position, cx)
9699 else {
9700 return;
9701 };
9702
9703 let project = self.project.clone();
9704
9705 cx.spawn(|_, mut cx| async move {
9706 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9707
9708 if let Some((_, path)) = result {
9709 workspace
9710 .update(&mut cx, |workspace, cx| {
9711 workspace.open_resolved_path(path, cx)
9712 })?
9713 .await?;
9714 }
9715 anyhow::Ok(())
9716 })
9717 .detach();
9718 }
9719
9720 pub(crate) fn navigate_to_hover_links(
9721 &mut self,
9722 kind: Option<GotoDefinitionKind>,
9723 mut definitions: Vec<HoverLink>,
9724 split: bool,
9725 cx: &mut ViewContext<Editor>,
9726 ) -> Task<Result<Navigated>> {
9727 // If there is one definition, just open it directly
9728 if definitions.len() == 1 {
9729 let definition = definitions.pop().unwrap();
9730
9731 enum TargetTaskResult {
9732 Location(Option<Location>),
9733 AlreadyNavigated,
9734 }
9735
9736 let target_task = match definition {
9737 HoverLink::Text(link) => {
9738 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9739 }
9740 HoverLink::InlayHint(lsp_location, server_id) => {
9741 let computation = self.compute_target_location(lsp_location, server_id, cx);
9742 cx.background_executor().spawn(async move {
9743 let location = computation.await?;
9744 Ok(TargetTaskResult::Location(location))
9745 })
9746 }
9747 HoverLink::Url(url) => {
9748 cx.open_url(&url);
9749 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9750 }
9751 HoverLink::File(path) => {
9752 if let Some(workspace) = self.workspace() {
9753 cx.spawn(|_, mut cx| async move {
9754 workspace
9755 .update(&mut cx, |workspace, cx| {
9756 workspace.open_resolved_path(path, cx)
9757 })?
9758 .await
9759 .map(|_| TargetTaskResult::AlreadyNavigated)
9760 })
9761 } else {
9762 Task::ready(Ok(TargetTaskResult::Location(None)))
9763 }
9764 }
9765 };
9766 cx.spawn(|editor, mut cx| async move {
9767 let target = match target_task.await.context("target resolution task")? {
9768 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9769 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9770 TargetTaskResult::Location(Some(target)) => target,
9771 };
9772
9773 editor.update(&mut cx, |editor, cx| {
9774 let Some(workspace) = editor.workspace() else {
9775 return Navigated::No;
9776 };
9777 let pane = workspace.read(cx).active_pane().clone();
9778
9779 let range = target.range.to_offset(target.buffer.read(cx));
9780 let range = editor.range_for_match(&range);
9781
9782 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9783 let buffer = target.buffer.read(cx);
9784 let range = check_multiline_range(buffer, range);
9785 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9786 s.select_ranges([range]);
9787 });
9788 } else {
9789 cx.window_context().defer(move |cx| {
9790 let target_editor: View<Self> =
9791 workspace.update(cx, |workspace, cx| {
9792 let pane = if split {
9793 workspace.adjacent_pane(cx)
9794 } else {
9795 workspace.active_pane().clone()
9796 };
9797
9798 workspace.open_project_item(
9799 pane,
9800 target.buffer.clone(),
9801 true,
9802 true,
9803 cx,
9804 )
9805 });
9806 target_editor.update(cx, |target_editor, cx| {
9807 // When selecting a definition in a different buffer, disable the nav history
9808 // to avoid creating a history entry at the previous cursor location.
9809 pane.update(cx, |pane, _| pane.disable_history());
9810 let buffer = target.buffer.read(cx);
9811 let range = check_multiline_range(buffer, range);
9812 target_editor.change_selections(
9813 Some(Autoscroll::focused()),
9814 cx,
9815 |s| {
9816 s.select_ranges([range]);
9817 },
9818 );
9819 pane.update(cx, |pane, _| pane.enable_history());
9820 });
9821 });
9822 }
9823 Navigated::Yes
9824 })
9825 })
9826 } else if !definitions.is_empty() {
9827 cx.spawn(|editor, mut cx| async move {
9828 let (title, location_tasks, workspace) = editor
9829 .update(&mut cx, |editor, cx| {
9830 let tab_kind = match kind {
9831 Some(GotoDefinitionKind::Implementation) => "Implementations",
9832 _ => "Definitions",
9833 };
9834 let title = definitions
9835 .iter()
9836 .find_map(|definition| match definition {
9837 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9838 let buffer = origin.buffer.read(cx);
9839 format!(
9840 "{} for {}",
9841 tab_kind,
9842 buffer
9843 .text_for_range(origin.range.clone())
9844 .collect::<String>()
9845 )
9846 }),
9847 HoverLink::InlayHint(_, _) => None,
9848 HoverLink::Url(_) => None,
9849 HoverLink::File(_) => None,
9850 })
9851 .unwrap_or(tab_kind.to_string());
9852 let location_tasks = definitions
9853 .into_iter()
9854 .map(|definition| match definition {
9855 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9856 HoverLink::InlayHint(lsp_location, server_id) => {
9857 editor.compute_target_location(lsp_location, server_id, cx)
9858 }
9859 HoverLink::Url(_) => Task::ready(Ok(None)),
9860 HoverLink::File(_) => Task::ready(Ok(None)),
9861 })
9862 .collect::<Vec<_>>();
9863 (title, location_tasks, editor.workspace().clone())
9864 })
9865 .context("location tasks preparation")?;
9866
9867 let locations = future::join_all(location_tasks)
9868 .await
9869 .into_iter()
9870 .filter_map(|location| location.transpose())
9871 .collect::<Result<_>>()
9872 .context("location tasks")?;
9873
9874 let Some(workspace) = workspace else {
9875 return Ok(Navigated::No);
9876 };
9877 let opened = workspace
9878 .update(&mut cx, |workspace, cx| {
9879 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9880 })
9881 .ok();
9882
9883 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9884 })
9885 } else {
9886 Task::ready(Ok(Navigated::No))
9887 }
9888 }
9889
9890 fn compute_target_location(
9891 &self,
9892 lsp_location: lsp::Location,
9893 server_id: LanguageServerId,
9894 cx: &mut ViewContext<Self>,
9895 ) -> Task<anyhow::Result<Option<Location>>> {
9896 let Some(project) = self.project.clone() else {
9897 return Task::Ready(Some(Ok(None)));
9898 };
9899
9900 cx.spawn(move |editor, mut cx| async move {
9901 let location_task = editor.update(&mut cx, |_, cx| {
9902 project.update(cx, |project, cx| {
9903 let language_server_name = project
9904 .language_server_statuses(cx)
9905 .find(|(id, _)| server_id == *id)
9906 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9907 language_server_name.map(|language_server_name| {
9908 project.open_local_buffer_via_lsp(
9909 lsp_location.uri.clone(),
9910 server_id,
9911 language_server_name,
9912 cx,
9913 )
9914 })
9915 })
9916 })?;
9917 let location = match location_task {
9918 Some(task) => Some({
9919 let target_buffer_handle = task.await.context("open local buffer")?;
9920 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9921 let target_start = target_buffer
9922 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9923 let target_end = target_buffer
9924 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9925 target_buffer.anchor_after(target_start)
9926 ..target_buffer.anchor_before(target_end)
9927 })?;
9928 Location {
9929 buffer: target_buffer_handle,
9930 range,
9931 }
9932 }),
9933 None => None,
9934 };
9935 Ok(location)
9936 })
9937 }
9938
9939 pub fn find_all_references(
9940 &mut self,
9941 _: &FindAllReferences,
9942 cx: &mut ViewContext<Self>,
9943 ) -> Option<Task<Result<Navigated>>> {
9944 let multi_buffer = self.buffer.read(cx);
9945 let selection = self.selections.newest::<usize>(cx);
9946 let head = selection.head();
9947
9948 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9949 let head_anchor = multi_buffer_snapshot.anchor_at(
9950 head,
9951 if head < selection.tail() {
9952 Bias::Right
9953 } else {
9954 Bias::Left
9955 },
9956 );
9957
9958 match self
9959 .find_all_references_task_sources
9960 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9961 {
9962 Ok(_) => {
9963 log::info!(
9964 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9965 );
9966 return None;
9967 }
9968 Err(i) => {
9969 self.find_all_references_task_sources.insert(i, head_anchor);
9970 }
9971 }
9972
9973 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9974 let workspace = self.workspace()?;
9975 let project = workspace.read(cx).project().clone();
9976 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9977 Some(cx.spawn(|editor, mut cx| async move {
9978 let _cleanup = defer({
9979 let mut cx = cx.clone();
9980 move || {
9981 let _ = editor.update(&mut cx, |editor, _| {
9982 if let Ok(i) =
9983 editor
9984 .find_all_references_task_sources
9985 .binary_search_by(|anchor| {
9986 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9987 })
9988 {
9989 editor.find_all_references_task_sources.remove(i);
9990 }
9991 });
9992 }
9993 });
9994
9995 let locations = references.await?;
9996 if locations.is_empty() {
9997 return anyhow::Ok(Navigated::No);
9998 }
9999
10000 workspace.update(&mut cx, |workspace, cx| {
10001 let title = locations
10002 .first()
10003 .as_ref()
10004 .map(|location| {
10005 let buffer = location.buffer.read(cx);
10006 format!(
10007 "References to `{}`",
10008 buffer
10009 .text_for_range(location.range.clone())
10010 .collect::<String>()
10011 )
10012 })
10013 .unwrap();
10014 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10015 Navigated::Yes
10016 })
10017 }))
10018 }
10019
10020 /// Opens a multibuffer with the given project locations in it
10021 pub fn open_locations_in_multibuffer(
10022 workspace: &mut Workspace,
10023 mut locations: Vec<Location>,
10024 title: String,
10025 split: bool,
10026 cx: &mut ViewContext<Workspace>,
10027 ) {
10028 // If there are multiple definitions, open them in a multibuffer
10029 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10030 let mut locations = locations.into_iter().peekable();
10031 let mut ranges_to_highlight = Vec::new();
10032 let capability = workspace.project().read(cx).capability();
10033
10034 let excerpt_buffer = cx.new_model(|cx| {
10035 let mut multibuffer = MultiBuffer::new(capability);
10036 while let Some(location) = locations.next() {
10037 let buffer = location.buffer.read(cx);
10038 let mut ranges_for_buffer = Vec::new();
10039 let range = location.range.to_offset(buffer);
10040 ranges_for_buffer.push(range.clone());
10041
10042 while let Some(next_location) = locations.peek() {
10043 if next_location.buffer == location.buffer {
10044 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10045 locations.next();
10046 } else {
10047 break;
10048 }
10049 }
10050
10051 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10052 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10053 location.buffer.clone(),
10054 ranges_for_buffer,
10055 DEFAULT_MULTIBUFFER_CONTEXT,
10056 cx,
10057 ))
10058 }
10059
10060 multibuffer.with_title(title)
10061 });
10062
10063 let editor = cx.new_view(|cx| {
10064 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10065 });
10066 editor.update(cx, |editor, cx| {
10067 if let Some(first_range) = ranges_to_highlight.first() {
10068 editor.change_selections(None, cx, |selections| {
10069 selections.clear_disjoint();
10070 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10071 });
10072 }
10073 editor.highlight_background::<Self>(
10074 &ranges_to_highlight,
10075 |theme| theme.editor_highlighted_line_background,
10076 cx,
10077 );
10078 });
10079
10080 let item = Box::new(editor);
10081 let item_id = item.item_id();
10082
10083 if split {
10084 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10085 } else {
10086 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10087 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10088 pane.close_current_preview_item(cx)
10089 } else {
10090 None
10091 }
10092 });
10093 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10094 }
10095 workspace.active_pane().update(cx, |pane, cx| {
10096 pane.set_preview_item_id(Some(item_id), cx);
10097 });
10098 }
10099
10100 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10101 use language::ToOffset as _;
10102
10103 let provider = self.semantics_provider.clone()?;
10104 let selection = self.selections.newest_anchor().clone();
10105 let (cursor_buffer, cursor_buffer_position) = self
10106 .buffer
10107 .read(cx)
10108 .text_anchor_for_position(selection.head(), cx)?;
10109 let (tail_buffer, cursor_buffer_position_end) = self
10110 .buffer
10111 .read(cx)
10112 .text_anchor_for_position(selection.tail(), cx)?;
10113 if tail_buffer != cursor_buffer {
10114 return None;
10115 }
10116
10117 let snapshot = cursor_buffer.read(cx).snapshot();
10118 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10119 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10120 let prepare_rename = provider
10121 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10122 .unwrap_or_else(|| Task::ready(Ok(None)));
10123 drop(snapshot);
10124
10125 Some(cx.spawn(|this, mut cx| async move {
10126 let rename_range = if let Some(range) = prepare_rename.await? {
10127 Some(range)
10128 } else {
10129 this.update(&mut cx, |this, cx| {
10130 let buffer = this.buffer.read(cx).snapshot(cx);
10131 let mut buffer_highlights = this
10132 .document_highlights_for_position(selection.head(), &buffer)
10133 .filter(|highlight| {
10134 highlight.start.excerpt_id == selection.head().excerpt_id
10135 && highlight.end.excerpt_id == selection.head().excerpt_id
10136 });
10137 buffer_highlights
10138 .next()
10139 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10140 })?
10141 };
10142 if let Some(rename_range) = rename_range {
10143 this.update(&mut cx, |this, cx| {
10144 let snapshot = cursor_buffer.read(cx).snapshot();
10145 let rename_buffer_range = rename_range.to_offset(&snapshot);
10146 let cursor_offset_in_rename_range =
10147 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10148 let cursor_offset_in_rename_range_end =
10149 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10150
10151 this.take_rename(false, cx);
10152 let buffer = this.buffer.read(cx).read(cx);
10153 let cursor_offset = selection.head().to_offset(&buffer);
10154 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10155 let rename_end = rename_start + rename_buffer_range.len();
10156 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10157 let mut old_highlight_id = None;
10158 let old_name: Arc<str> = buffer
10159 .chunks(rename_start..rename_end, true)
10160 .map(|chunk| {
10161 if old_highlight_id.is_none() {
10162 old_highlight_id = chunk.syntax_highlight_id;
10163 }
10164 chunk.text
10165 })
10166 .collect::<String>()
10167 .into();
10168
10169 drop(buffer);
10170
10171 // Position the selection in the rename editor so that it matches the current selection.
10172 this.show_local_selections = false;
10173 let rename_editor = cx.new_view(|cx| {
10174 let mut editor = Editor::single_line(cx);
10175 editor.buffer.update(cx, |buffer, cx| {
10176 buffer.edit([(0..0, old_name.clone())], None, cx)
10177 });
10178 let rename_selection_range = match cursor_offset_in_rename_range
10179 .cmp(&cursor_offset_in_rename_range_end)
10180 {
10181 Ordering::Equal => {
10182 editor.select_all(&SelectAll, cx);
10183 return editor;
10184 }
10185 Ordering::Less => {
10186 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10187 }
10188 Ordering::Greater => {
10189 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10190 }
10191 };
10192 if rename_selection_range.end > old_name.len() {
10193 editor.select_all(&SelectAll, cx);
10194 } else {
10195 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10196 s.select_ranges([rename_selection_range]);
10197 });
10198 }
10199 editor
10200 });
10201 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10202 if e == &EditorEvent::Focused {
10203 cx.emit(EditorEvent::FocusedIn)
10204 }
10205 })
10206 .detach();
10207
10208 let write_highlights =
10209 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10210 let read_highlights =
10211 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10212 let ranges = write_highlights
10213 .iter()
10214 .flat_map(|(_, ranges)| ranges.iter())
10215 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10216 .cloned()
10217 .collect();
10218
10219 this.highlight_text::<Rename>(
10220 ranges,
10221 HighlightStyle {
10222 fade_out: Some(0.6),
10223 ..Default::default()
10224 },
10225 cx,
10226 );
10227 let rename_focus_handle = rename_editor.focus_handle(cx);
10228 cx.focus(&rename_focus_handle);
10229 let block_id = this.insert_blocks(
10230 [BlockProperties {
10231 style: BlockStyle::Flex,
10232 position: range.start,
10233 height: 1,
10234 render: Box::new({
10235 let rename_editor = rename_editor.clone();
10236 move |cx: &mut BlockContext| {
10237 let mut text_style = cx.editor_style.text.clone();
10238 if let Some(highlight_style) = old_highlight_id
10239 .and_then(|h| h.style(&cx.editor_style.syntax))
10240 {
10241 text_style = text_style.highlight(highlight_style);
10242 }
10243 div()
10244 .pl(cx.anchor_x)
10245 .child(EditorElement::new(
10246 &rename_editor,
10247 EditorStyle {
10248 background: cx.theme().system().transparent,
10249 local_player: cx.editor_style.local_player,
10250 text: text_style,
10251 scrollbar_width: cx.editor_style.scrollbar_width,
10252 syntax: cx.editor_style.syntax.clone(),
10253 status: cx.editor_style.status.clone(),
10254 inlay_hints_style: HighlightStyle {
10255 font_weight: Some(FontWeight::BOLD),
10256 ..make_inlay_hints_style(cx)
10257 },
10258 suggestions_style: HighlightStyle {
10259 color: Some(cx.theme().status().predictive),
10260 ..HighlightStyle::default()
10261 },
10262 ..EditorStyle::default()
10263 },
10264 ))
10265 .into_any_element()
10266 }
10267 }),
10268 disposition: BlockDisposition::Below,
10269 priority: 0,
10270 }],
10271 Some(Autoscroll::fit()),
10272 cx,
10273 )[0];
10274 this.pending_rename = Some(RenameState {
10275 range,
10276 old_name,
10277 editor: rename_editor,
10278 block_id,
10279 });
10280 })?;
10281 }
10282
10283 Ok(())
10284 }))
10285 }
10286
10287 pub fn confirm_rename(
10288 &mut self,
10289 _: &ConfirmRename,
10290 cx: &mut ViewContext<Self>,
10291 ) -> Option<Task<Result<()>>> {
10292 let rename = self.take_rename(false, cx)?;
10293 let workspace = self.workspace()?.downgrade();
10294 let (buffer, start) = self
10295 .buffer
10296 .read(cx)
10297 .text_anchor_for_position(rename.range.start, cx)?;
10298 let (end_buffer, _) = self
10299 .buffer
10300 .read(cx)
10301 .text_anchor_for_position(rename.range.end, cx)?;
10302 if buffer != end_buffer {
10303 return None;
10304 }
10305
10306 let old_name = rename.old_name;
10307 let new_name = rename.editor.read(cx).text(cx);
10308
10309 let rename = self.semantics_provider.as_ref()?.perform_rename(
10310 &buffer,
10311 start,
10312 new_name.clone(),
10313 cx,
10314 )?;
10315
10316 Some(cx.spawn(|editor, mut cx| async move {
10317 let project_transaction = rename.await?;
10318 Self::open_project_transaction(
10319 &editor,
10320 workspace,
10321 project_transaction,
10322 format!("Rename: {} → {}", old_name, new_name),
10323 cx.clone(),
10324 )
10325 .await?;
10326
10327 editor.update(&mut cx, |editor, cx| {
10328 editor.refresh_document_highlights(cx);
10329 })?;
10330 Ok(())
10331 }))
10332 }
10333
10334 fn take_rename(
10335 &mut self,
10336 moving_cursor: bool,
10337 cx: &mut ViewContext<Self>,
10338 ) -> Option<RenameState> {
10339 let rename = self.pending_rename.take()?;
10340 if rename.editor.focus_handle(cx).is_focused(cx) {
10341 cx.focus(&self.focus_handle);
10342 }
10343
10344 self.remove_blocks(
10345 [rename.block_id].into_iter().collect(),
10346 Some(Autoscroll::fit()),
10347 cx,
10348 );
10349 self.clear_highlights::<Rename>(cx);
10350 self.show_local_selections = true;
10351
10352 if moving_cursor {
10353 let rename_editor = rename.editor.read(cx);
10354 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10355
10356 // Update the selection to match the position of the selection inside
10357 // the rename editor.
10358 let snapshot = self.buffer.read(cx).read(cx);
10359 let rename_range = rename.range.to_offset(&snapshot);
10360 let cursor_in_editor = snapshot
10361 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10362 .min(rename_range.end);
10363 drop(snapshot);
10364
10365 self.change_selections(None, cx, |s| {
10366 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10367 });
10368 } else {
10369 self.refresh_document_highlights(cx);
10370 }
10371
10372 Some(rename)
10373 }
10374
10375 pub fn pending_rename(&self) -> Option<&RenameState> {
10376 self.pending_rename.as_ref()
10377 }
10378
10379 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10380 let project = match &self.project {
10381 Some(project) => project.clone(),
10382 None => return None,
10383 };
10384
10385 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10386 }
10387
10388 fn format_selections(
10389 &mut self,
10390 _: &FormatSelections,
10391 cx: &mut ViewContext<Self>,
10392 ) -> Option<Task<Result<()>>> {
10393 let project = match &self.project {
10394 Some(project) => project.clone(),
10395 None => return None,
10396 };
10397
10398 let selections = self
10399 .selections
10400 .all_adjusted(cx)
10401 .into_iter()
10402 .filter(|s| !s.is_empty())
10403 .collect_vec();
10404
10405 Some(self.perform_format(
10406 project,
10407 FormatTrigger::Manual,
10408 FormatTarget::Ranges(selections),
10409 cx,
10410 ))
10411 }
10412
10413 fn perform_format(
10414 &mut self,
10415 project: Model<Project>,
10416 trigger: FormatTrigger,
10417 target: FormatTarget,
10418 cx: &mut ViewContext<Self>,
10419 ) -> Task<Result<()>> {
10420 let buffer = self.buffer().clone();
10421 let mut buffers = buffer.read(cx).all_buffers();
10422 if trigger == FormatTrigger::Save {
10423 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10424 }
10425
10426 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10427 let format = project.update(cx, |project, cx| {
10428 project.format(buffers, true, trigger, target, cx)
10429 });
10430
10431 cx.spawn(|_, mut cx| async move {
10432 let transaction = futures::select_biased! {
10433 () = timeout => {
10434 log::warn!("timed out waiting for formatting");
10435 None
10436 }
10437 transaction = format.log_err().fuse() => transaction,
10438 };
10439
10440 buffer
10441 .update(&mut cx, |buffer, cx| {
10442 if let Some(transaction) = transaction {
10443 if !buffer.is_singleton() {
10444 buffer.push_transaction(&transaction.0, cx);
10445 }
10446 }
10447
10448 cx.notify();
10449 })
10450 .ok();
10451
10452 Ok(())
10453 })
10454 }
10455
10456 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10457 if let Some(project) = self.project.clone() {
10458 self.buffer.update(cx, |multi_buffer, cx| {
10459 project.update(cx, |project, cx| {
10460 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10461 });
10462 })
10463 }
10464 }
10465
10466 fn cancel_language_server_work(
10467 &mut self,
10468 _: &CancelLanguageServerWork,
10469 cx: &mut ViewContext<Self>,
10470 ) {
10471 if let Some(project) = self.project.clone() {
10472 self.buffer.update(cx, |multi_buffer, cx| {
10473 project.update(cx, |project, cx| {
10474 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10475 });
10476 })
10477 }
10478 }
10479
10480 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10481 cx.show_character_palette();
10482 }
10483
10484 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10485 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10486 let buffer = self.buffer.read(cx).snapshot(cx);
10487 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10488 let is_valid = buffer
10489 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10490 .any(|entry| {
10491 entry.diagnostic.is_primary
10492 && !entry.range.is_empty()
10493 && entry.range.start == primary_range_start
10494 && entry.diagnostic.message == active_diagnostics.primary_message
10495 });
10496
10497 if is_valid != active_diagnostics.is_valid {
10498 active_diagnostics.is_valid = is_valid;
10499 let mut new_styles = HashMap::default();
10500 for (block_id, diagnostic) in &active_diagnostics.blocks {
10501 new_styles.insert(
10502 *block_id,
10503 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10504 );
10505 }
10506 self.display_map.update(cx, |display_map, _cx| {
10507 display_map.replace_blocks(new_styles)
10508 });
10509 }
10510 }
10511 }
10512
10513 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10514 self.dismiss_diagnostics(cx);
10515 let snapshot = self.snapshot(cx);
10516 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10517 let buffer = self.buffer.read(cx).snapshot(cx);
10518
10519 let mut primary_range = None;
10520 let mut primary_message = None;
10521 let mut group_end = Point::zero();
10522 let diagnostic_group = buffer
10523 .diagnostic_group::<MultiBufferPoint>(group_id)
10524 .filter_map(|entry| {
10525 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10526 && (entry.range.start.row == entry.range.end.row
10527 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10528 {
10529 return None;
10530 }
10531 if entry.range.end > group_end {
10532 group_end = entry.range.end;
10533 }
10534 if entry.diagnostic.is_primary {
10535 primary_range = Some(entry.range.clone());
10536 primary_message = Some(entry.diagnostic.message.clone());
10537 }
10538 Some(entry)
10539 })
10540 .collect::<Vec<_>>();
10541 let primary_range = primary_range?;
10542 let primary_message = primary_message?;
10543 let primary_range =
10544 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10545
10546 let blocks = display_map
10547 .insert_blocks(
10548 diagnostic_group.iter().map(|entry| {
10549 let diagnostic = entry.diagnostic.clone();
10550 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10551 BlockProperties {
10552 style: BlockStyle::Fixed,
10553 position: buffer.anchor_after(entry.range.start),
10554 height: message_height,
10555 render: diagnostic_block_renderer(diagnostic, None, true, true),
10556 disposition: BlockDisposition::Below,
10557 priority: 0,
10558 }
10559 }),
10560 cx,
10561 )
10562 .into_iter()
10563 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10564 .collect();
10565
10566 Some(ActiveDiagnosticGroup {
10567 primary_range,
10568 primary_message,
10569 group_id,
10570 blocks,
10571 is_valid: true,
10572 })
10573 });
10574 self.active_diagnostics.is_some()
10575 }
10576
10577 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10578 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10579 self.display_map.update(cx, |display_map, cx| {
10580 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10581 });
10582 cx.notify();
10583 }
10584 }
10585
10586 pub fn set_selections_from_remote(
10587 &mut self,
10588 selections: Vec<Selection<Anchor>>,
10589 pending_selection: Option<Selection<Anchor>>,
10590 cx: &mut ViewContext<Self>,
10591 ) {
10592 let old_cursor_position = self.selections.newest_anchor().head();
10593 self.selections.change_with(cx, |s| {
10594 s.select_anchors(selections);
10595 if let Some(pending_selection) = pending_selection {
10596 s.set_pending(pending_selection, SelectMode::Character);
10597 } else {
10598 s.clear_pending();
10599 }
10600 });
10601 self.selections_did_change(false, &old_cursor_position, true, cx);
10602 }
10603
10604 fn push_to_selection_history(&mut self) {
10605 self.selection_history.push(SelectionHistoryEntry {
10606 selections: self.selections.disjoint_anchors(),
10607 select_next_state: self.select_next_state.clone(),
10608 select_prev_state: self.select_prev_state.clone(),
10609 add_selections_state: self.add_selections_state.clone(),
10610 });
10611 }
10612
10613 pub fn transact(
10614 &mut self,
10615 cx: &mut ViewContext<Self>,
10616 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10617 ) -> Option<TransactionId> {
10618 self.start_transaction_at(Instant::now(), cx);
10619 update(self, cx);
10620 self.end_transaction_at(Instant::now(), cx)
10621 }
10622
10623 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10624 self.end_selection(cx);
10625 if let Some(tx_id) = self
10626 .buffer
10627 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10628 {
10629 self.selection_history
10630 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10631 cx.emit(EditorEvent::TransactionBegun {
10632 transaction_id: tx_id,
10633 })
10634 }
10635 }
10636
10637 fn end_transaction_at(
10638 &mut self,
10639 now: Instant,
10640 cx: &mut ViewContext<Self>,
10641 ) -> Option<TransactionId> {
10642 if let Some(transaction_id) = self
10643 .buffer
10644 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10645 {
10646 if let Some((_, end_selections)) =
10647 self.selection_history.transaction_mut(transaction_id)
10648 {
10649 *end_selections = Some(self.selections.disjoint_anchors());
10650 } else {
10651 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10652 }
10653
10654 cx.emit(EditorEvent::Edited { transaction_id });
10655 Some(transaction_id)
10656 } else {
10657 None
10658 }
10659 }
10660
10661 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10662 let selection = self.selections.newest::<Point>(cx);
10663
10664 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10665 let range = if selection.is_empty() {
10666 let point = selection.head().to_display_point(&display_map);
10667 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10668 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10669 .to_point(&display_map);
10670 start..end
10671 } else {
10672 selection.range()
10673 };
10674 if display_map.folds_in_range(range).next().is_some() {
10675 self.unfold_lines(&Default::default(), cx)
10676 } else {
10677 self.fold(&Default::default(), cx)
10678 }
10679 }
10680
10681 pub fn toggle_fold_recursive(
10682 &mut self,
10683 _: &actions::ToggleFoldRecursive,
10684 cx: &mut ViewContext<Self>,
10685 ) {
10686 let selection = self.selections.newest::<Point>(cx);
10687
10688 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10689 let range = if selection.is_empty() {
10690 let point = selection.head().to_display_point(&display_map);
10691 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10692 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10693 .to_point(&display_map);
10694 start..end
10695 } else {
10696 selection.range()
10697 };
10698 if display_map.folds_in_range(range).next().is_some() {
10699 self.unfold_recursive(&Default::default(), cx)
10700 } else {
10701 self.fold_recursive(&Default::default(), cx)
10702 }
10703 }
10704
10705 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10706 let mut fold_ranges = Vec::new();
10707 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10708 let selections = self.selections.all_adjusted(cx);
10709
10710 for selection in selections {
10711 let range = selection.range().sorted();
10712 let buffer_start_row = range.start.row;
10713
10714 if range.start.row != range.end.row {
10715 let mut found = false;
10716 let mut row = range.start.row;
10717 while row <= range.end.row {
10718 if let Some((foldable_range, fold_text)) =
10719 { display_map.foldable_range(MultiBufferRow(row)) }
10720 {
10721 found = true;
10722 row = foldable_range.end.row + 1;
10723 fold_ranges.push((foldable_range, fold_text));
10724 } else {
10725 row += 1
10726 }
10727 }
10728 if found {
10729 continue;
10730 }
10731 }
10732
10733 for row in (0..=range.start.row).rev() {
10734 if let Some((foldable_range, fold_text)) =
10735 display_map.foldable_range(MultiBufferRow(row))
10736 {
10737 if foldable_range.end.row >= buffer_start_row {
10738 fold_ranges.push((foldable_range, fold_text));
10739 if row <= range.start.row {
10740 break;
10741 }
10742 }
10743 }
10744 }
10745 }
10746
10747 self.fold_ranges(fold_ranges, true, cx);
10748 }
10749
10750 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10751 let mut fold_ranges = Vec::new();
10752 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10753
10754 for row in 0..display_map.max_buffer_row().0 {
10755 if let Some((foldable_range, fold_text)) =
10756 display_map.foldable_range(MultiBufferRow(row))
10757 {
10758 fold_ranges.push((foldable_range, fold_text));
10759 }
10760 }
10761
10762 self.fold_ranges(fold_ranges, true, cx);
10763 }
10764
10765 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10766 let mut fold_ranges = Vec::new();
10767 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10768 let selections = self.selections.all_adjusted(cx);
10769
10770 for selection in selections {
10771 let range = selection.range().sorted();
10772 let buffer_start_row = range.start.row;
10773
10774 if range.start.row != range.end.row {
10775 let mut found = false;
10776 for row in range.start.row..=range.end.row {
10777 if let Some((foldable_range, fold_text)) =
10778 { display_map.foldable_range(MultiBufferRow(row)) }
10779 {
10780 found = true;
10781 fold_ranges.push((foldable_range, fold_text));
10782 }
10783 }
10784 if found {
10785 continue;
10786 }
10787 }
10788
10789 for row in (0..=range.start.row).rev() {
10790 if let Some((foldable_range, fold_text)) =
10791 display_map.foldable_range(MultiBufferRow(row))
10792 {
10793 if foldable_range.end.row >= buffer_start_row {
10794 fold_ranges.push((foldable_range, fold_text));
10795 } else {
10796 break;
10797 }
10798 }
10799 }
10800 }
10801
10802 self.fold_ranges(fold_ranges, true, cx);
10803 }
10804
10805 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10806 let buffer_row = fold_at.buffer_row;
10807 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10808
10809 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10810 let autoscroll = self
10811 .selections
10812 .all::<Point>(cx)
10813 .iter()
10814 .any(|selection| fold_range.overlaps(&selection.range()));
10815
10816 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10817 }
10818 }
10819
10820 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10821 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10822 let buffer = &display_map.buffer_snapshot;
10823 let selections = self.selections.all::<Point>(cx);
10824 let ranges = selections
10825 .iter()
10826 .map(|s| {
10827 let range = s.display_range(&display_map).sorted();
10828 let mut start = range.start.to_point(&display_map);
10829 let mut end = range.end.to_point(&display_map);
10830 start.column = 0;
10831 end.column = buffer.line_len(MultiBufferRow(end.row));
10832 start..end
10833 })
10834 .collect::<Vec<_>>();
10835
10836 self.unfold_ranges(ranges, true, true, cx);
10837 }
10838
10839 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10840 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10841 let selections = self.selections.all::<Point>(cx);
10842 let ranges = selections
10843 .iter()
10844 .map(|s| {
10845 let mut range = s.display_range(&display_map).sorted();
10846 *range.start.column_mut() = 0;
10847 *range.end.column_mut() = display_map.line_len(range.end.row());
10848 let start = range.start.to_point(&display_map);
10849 let end = range.end.to_point(&display_map);
10850 start..end
10851 })
10852 .collect::<Vec<_>>();
10853
10854 self.unfold_ranges(ranges, true, true, cx);
10855 }
10856
10857 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10858 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10859
10860 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10861 ..Point::new(
10862 unfold_at.buffer_row.0,
10863 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10864 );
10865
10866 let autoscroll = self
10867 .selections
10868 .all::<Point>(cx)
10869 .iter()
10870 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10871
10872 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10873 }
10874
10875 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10876 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10877 self.unfold_ranges(
10878 [Point::zero()..display_map.max_point().to_point(&display_map)],
10879 true,
10880 true,
10881 cx,
10882 );
10883 }
10884
10885 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10886 let selections = self.selections.all::<Point>(cx);
10887 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10888 let line_mode = self.selections.line_mode;
10889 let ranges = selections.into_iter().map(|s| {
10890 if line_mode {
10891 let start = Point::new(s.start.row, 0);
10892 let end = Point::new(
10893 s.end.row,
10894 display_map
10895 .buffer_snapshot
10896 .line_len(MultiBufferRow(s.end.row)),
10897 );
10898 (start..end, display_map.fold_placeholder.clone())
10899 } else {
10900 (s.start..s.end, display_map.fold_placeholder.clone())
10901 }
10902 });
10903 self.fold_ranges(ranges, true, cx);
10904 }
10905
10906 pub fn fold_ranges<T: ToOffset + Clone>(
10907 &mut self,
10908 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10909 auto_scroll: bool,
10910 cx: &mut ViewContext<Self>,
10911 ) {
10912 let mut fold_ranges = Vec::new();
10913 let mut buffers_affected = HashMap::default();
10914 let multi_buffer = self.buffer().read(cx);
10915 for (fold_range, fold_text) in ranges {
10916 if let Some((_, buffer, _)) =
10917 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10918 {
10919 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10920 };
10921 fold_ranges.push((fold_range, fold_text));
10922 }
10923
10924 let mut ranges = fold_ranges.into_iter().peekable();
10925 if ranges.peek().is_some() {
10926 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10927
10928 if auto_scroll {
10929 self.request_autoscroll(Autoscroll::fit(), cx);
10930 }
10931
10932 for buffer in buffers_affected.into_values() {
10933 self.sync_expanded_diff_hunks(buffer, cx);
10934 }
10935
10936 cx.notify();
10937
10938 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10939 // Clear diagnostics block when folding a range that contains it.
10940 let snapshot = self.snapshot(cx);
10941 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10942 drop(snapshot);
10943 self.active_diagnostics = Some(active_diagnostics);
10944 self.dismiss_diagnostics(cx);
10945 } else {
10946 self.active_diagnostics = Some(active_diagnostics);
10947 }
10948 }
10949
10950 self.scrollbar_marker_state.dirty = true;
10951 }
10952 }
10953
10954 pub fn unfold_ranges<T: ToOffset + Clone>(
10955 &mut self,
10956 ranges: impl IntoIterator<Item = Range<T>>,
10957 inclusive: bool,
10958 auto_scroll: bool,
10959 cx: &mut ViewContext<Self>,
10960 ) {
10961 let mut unfold_ranges = Vec::new();
10962 let mut buffers_affected = HashMap::default();
10963 let multi_buffer = self.buffer().read(cx);
10964 for range in ranges {
10965 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10966 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10967 };
10968 unfold_ranges.push(range);
10969 }
10970
10971 let mut ranges = unfold_ranges.into_iter().peekable();
10972 if ranges.peek().is_some() {
10973 self.display_map
10974 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10975 if auto_scroll {
10976 self.request_autoscroll(Autoscroll::fit(), cx);
10977 }
10978
10979 for buffer in buffers_affected.into_values() {
10980 self.sync_expanded_diff_hunks(buffer, cx);
10981 }
10982
10983 cx.notify();
10984 self.scrollbar_marker_state.dirty = true;
10985 self.active_indent_guides_state.dirty = true;
10986 }
10987 }
10988
10989 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10990 self.display_map.read(cx).fold_placeholder.clone()
10991 }
10992
10993 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10994 if hovered != self.gutter_hovered {
10995 self.gutter_hovered = hovered;
10996 cx.notify();
10997 }
10998 }
10999
11000 pub fn insert_blocks(
11001 &mut self,
11002 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11003 autoscroll: Option<Autoscroll>,
11004 cx: &mut ViewContext<Self>,
11005 ) -> Vec<CustomBlockId> {
11006 let blocks = self
11007 .display_map
11008 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11009 if let Some(autoscroll) = autoscroll {
11010 self.request_autoscroll(autoscroll, cx);
11011 }
11012 cx.notify();
11013 blocks
11014 }
11015
11016 pub fn resize_blocks(
11017 &mut self,
11018 heights: HashMap<CustomBlockId, u32>,
11019 autoscroll: Option<Autoscroll>,
11020 cx: &mut ViewContext<Self>,
11021 ) {
11022 self.display_map
11023 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11024 if let Some(autoscroll) = autoscroll {
11025 self.request_autoscroll(autoscroll, cx);
11026 }
11027 cx.notify();
11028 }
11029
11030 pub fn replace_blocks(
11031 &mut self,
11032 renderers: HashMap<CustomBlockId, RenderBlock>,
11033 autoscroll: Option<Autoscroll>,
11034 cx: &mut ViewContext<Self>,
11035 ) {
11036 self.display_map
11037 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11038 if let Some(autoscroll) = autoscroll {
11039 self.request_autoscroll(autoscroll, cx);
11040 }
11041 cx.notify();
11042 }
11043
11044 pub fn remove_blocks(
11045 &mut self,
11046 block_ids: HashSet<CustomBlockId>,
11047 autoscroll: Option<Autoscroll>,
11048 cx: &mut ViewContext<Self>,
11049 ) {
11050 self.display_map.update(cx, |display_map, cx| {
11051 display_map.remove_blocks(block_ids, cx)
11052 });
11053 if let Some(autoscroll) = autoscroll {
11054 self.request_autoscroll(autoscroll, cx);
11055 }
11056 cx.notify();
11057 }
11058
11059 pub fn row_for_block(
11060 &self,
11061 block_id: CustomBlockId,
11062 cx: &mut ViewContext<Self>,
11063 ) -> Option<DisplayRow> {
11064 self.display_map
11065 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11066 }
11067
11068 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11069 self.focused_block = Some(focused_block);
11070 }
11071
11072 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11073 self.focused_block.take()
11074 }
11075
11076 pub fn insert_creases(
11077 &mut self,
11078 creases: impl IntoIterator<Item = Crease>,
11079 cx: &mut ViewContext<Self>,
11080 ) -> Vec<CreaseId> {
11081 self.display_map
11082 .update(cx, |map, cx| map.insert_creases(creases, cx))
11083 }
11084
11085 pub fn remove_creases(
11086 &mut self,
11087 ids: impl IntoIterator<Item = CreaseId>,
11088 cx: &mut ViewContext<Self>,
11089 ) {
11090 self.display_map
11091 .update(cx, |map, cx| map.remove_creases(ids, cx));
11092 }
11093
11094 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11095 self.display_map
11096 .update(cx, |map, cx| map.snapshot(cx))
11097 .longest_row()
11098 }
11099
11100 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11101 self.display_map
11102 .update(cx, |map, cx| map.snapshot(cx))
11103 .max_point()
11104 }
11105
11106 pub fn text(&self, cx: &AppContext) -> String {
11107 self.buffer.read(cx).read(cx).text()
11108 }
11109
11110 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11111 let text = self.text(cx);
11112 let text = text.trim();
11113
11114 if text.is_empty() {
11115 return None;
11116 }
11117
11118 Some(text.to_string())
11119 }
11120
11121 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11122 self.transact(cx, |this, cx| {
11123 this.buffer
11124 .read(cx)
11125 .as_singleton()
11126 .expect("you can only call set_text on editors for singleton buffers")
11127 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11128 });
11129 }
11130
11131 pub fn display_text(&self, cx: &mut AppContext) -> String {
11132 self.display_map
11133 .update(cx, |map, cx| map.snapshot(cx))
11134 .text()
11135 }
11136
11137 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11138 let mut wrap_guides = smallvec::smallvec![];
11139
11140 if self.show_wrap_guides == Some(false) {
11141 return wrap_guides;
11142 }
11143
11144 let settings = self.buffer.read(cx).settings_at(0, cx);
11145 if settings.show_wrap_guides {
11146 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11147 wrap_guides.push((soft_wrap as usize, true));
11148 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11149 wrap_guides.push((soft_wrap as usize, true));
11150 }
11151 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11152 }
11153
11154 wrap_guides
11155 }
11156
11157 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11158 let settings = self.buffer.read(cx).settings_at(0, cx);
11159 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11160 match mode {
11161 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11162 SoftWrap::None
11163 }
11164 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11165 language_settings::SoftWrap::PreferredLineLength => {
11166 SoftWrap::Column(settings.preferred_line_length)
11167 }
11168 language_settings::SoftWrap::Bounded => {
11169 SoftWrap::Bounded(settings.preferred_line_length)
11170 }
11171 }
11172 }
11173
11174 pub fn set_soft_wrap_mode(
11175 &mut self,
11176 mode: language_settings::SoftWrap,
11177 cx: &mut ViewContext<Self>,
11178 ) {
11179 self.soft_wrap_mode_override = Some(mode);
11180 cx.notify();
11181 }
11182
11183 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11184 let rem_size = cx.rem_size();
11185 self.display_map.update(cx, |map, cx| {
11186 map.set_font(
11187 style.text.font(),
11188 style.text.font_size.to_pixels(rem_size),
11189 cx,
11190 )
11191 });
11192 self.style = Some(style);
11193 }
11194
11195 pub fn style(&self) -> Option<&EditorStyle> {
11196 self.style.as_ref()
11197 }
11198
11199 // Called by the element. This method is not designed to be called outside of the editor
11200 // element's layout code because it does not notify when rewrapping is computed synchronously.
11201 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11202 self.display_map
11203 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11204 }
11205
11206 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11207 if self.soft_wrap_mode_override.is_some() {
11208 self.soft_wrap_mode_override.take();
11209 } else {
11210 let soft_wrap = match self.soft_wrap_mode(cx) {
11211 SoftWrap::GitDiff => return,
11212 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11213 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11214 language_settings::SoftWrap::None
11215 }
11216 };
11217 self.soft_wrap_mode_override = Some(soft_wrap);
11218 }
11219 cx.notify();
11220 }
11221
11222 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11223 let Some(workspace) = self.workspace() else {
11224 return;
11225 };
11226 let fs = workspace.read(cx).app_state().fs.clone();
11227 let current_show = TabBarSettings::get_global(cx).show;
11228 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11229 setting.show = Some(!current_show);
11230 });
11231 }
11232
11233 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11234 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11235 self.buffer
11236 .read(cx)
11237 .settings_at(0, cx)
11238 .indent_guides
11239 .enabled
11240 });
11241 self.show_indent_guides = Some(!currently_enabled);
11242 cx.notify();
11243 }
11244
11245 fn should_show_indent_guides(&self) -> Option<bool> {
11246 self.show_indent_guides
11247 }
11248
11249 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11250 let mut editor_settings = EditorSettings::get_global(cx).clone();
11251 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11252 EditorSettings::override_global(editor_settings, cx);
11253 }
11254
11255 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11256 self.use_relative_line_numbers
11257 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11258 }
11259
11260 pub fn toggle_relative_line_numbers(
11261 &mut self,
11262 _: &ToggleRelativeLineNumbers,
11263 cx: &mut ViewContext<Self>,
11264 ) {
11265 let is_relative = self.should_use_relative_line_numbers(cx);
11266 self.set_relative_line_number(Some(!is_relative), cx)
11267 }
11268
11269 pub fn set_relative_line_number(
11270 &mut self,
11271 is_relative: Option<bool>,
11272 cx: &mut ViewContext<Self>,
11273 ) {
11274 self.use_relative_line_numbers = is_relative;
11275 cx.notify();
11276 }
11277
11278 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11279 self.show_gutter = show_gutter;
11280 cx.notify();
11281 }
11282
11283 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11284 self.show_line_numbers = Some(show_line_numbers);
11285 cx.notify();
11286 }
11287
11288 pub fn set_show_git_diff_gutter(
11289 &mut self,
11290 show_git_diff_gutter: bool,
11291 cx: &mut ViewContext<Self>,
11292 ) {
11293 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11294 cx.notify();
11295 }
11296
11297 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11298 self.show_code_actions = Some(show_code_actions);
11299 cx.notify();
11300 }
11301
11302 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11303 self.show_runnables = Some(show_runnables);
11304 cx.notify();
11305 }
11306
11307 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11308 if self.display_map.read(cx).masked != masked {
11309 self.display_map.update(cx, |map, _| map.masked = masked);
11310 }
11311 cx.notify()
11312 }
11313
11314 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11315 self.show_wrap_guides = Some(show_wrap_guides);
11316 cx.notify();
11317 }
11318
11319 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11320 self.show_indent_guides = Some(show_indent_guides);
11321 cx.notify();
11322 }
11323
11324 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11325 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11326 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11327 if let Some(dir) = file.abs_path(cx).parent() {
11328 return Some(dir.to_owned());
11329 }
11330 }
11331
11332 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11333 return Some(project_path.path.to_path_buf());
11334 }
11335 }
11336
11337 None
11338 }
11339
11340 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11341 self.active_excerpt(cx)?
11342 .1
11343 .read(cx)
11344 .file()
11345 .and_then(|f| f.as_local())
11346 }
11347
11348 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11349 if let Some(target) = self.target_file(cx) {
11350 cx.reveal_path(&target.abs_path(cx));
11351 }
11352 }
11353
11354 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11355 if let Some(file) = self.target_file(cx) {
11356 if let Some(path) = file.abs_path(cx).to_str() {
11357 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11358 }
11359 }
11360 }
11361
11362 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11363 if let Some(file) = self.target_file(cx) {
11364 if let Some(path) = file.path().to_str() {
11365 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11366 }
11367 }
11368 }
11369
11370 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11371 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11372
11373 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11374 self.start_git_blame(true, cx);
11375 }
11376
11377 cx.notify();
11378 }
11379
11380 pub fn toggle_git_blame_inline(
11381 &mut self,
11382 _: &ToggleGitBlameInline,
11383 cx: &mut ViewContext<Self>,
11384 ) {
11385 self.toggle_git_blame_inline_internal(true, cx);
11386 cx.notify();
11387 }
11388
11389 pub fn git_blame_inline_enabled(&self) -> bool {
11390 self.git_blame_inline_enabled
11391 }
11392
11393 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11394 self.show_selection_menu = self
11395 .show_selection_menu
11396 .map(|show_selections_menu| !show_selections_menu)
11397 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11398
11399 cx.notify();
11400 }
11401
11402 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11403 self.show_selection_menu
11404 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11405 }
11406
11407 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11408 if let Some(project) = self.project.as_ref() {
11409 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11410 return;
11411 };
11412
11413 if buffer.read(cx).file().is_none() {
11414 return;
11415 }
11416
11417 let focused = self.focus_handle(cx).contains_focused(cx);
11418
11419 let project = project.clone();
11420 let blame =
11421 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11422 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11423 self.blame = Some(blame);
11424 }
11425 }
11426
11427 fn toggle_git_blame_inline_internal(
11428 &mut self,
11429 user_triggered: bool,
11430 cx: &mut ViewContext<Self>,
11431 ) {
11432 if self.git_blame_inline_enabled {
11433 self.git_blame_inline_enabled = false;
11434 self.show_git_blame_inline = false;
11435 self.show_git_blame_inline_delay_task.take();
11436 } else {
11437 self.git_blame_inline_enabled = true;
11438 self.start_git_blame_inline(user_triggered, cx);
11439 }
11440
11441 cx.notify();
11442 }
11443
11444 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11445 self.start_git_blame(user_triggered, cx);
11446
11447 if ProjectSettings::get_global(cx)
11448 .git
11449 .inline_blame_delay()
11450 .is_some()
11451 {
11452 self.start_inline_blame_timer(cx);
11453 } else {
11454 self.show_git_blame_inline = true
11455 }
11456 }
11457
11458 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11459 self.blame.as_ref()
11460 }
11461
11462 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11463 self.show_git_blame_gutter && self.has_blame_entries(cx)
11464 }
11465
11466 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11467 self.show_git_blame_inline
11468 && self.focus_handle.is_focused(cx)
11469 && !self.newest_selection_head_on_empty_line(cx)
11470 && self.has_blame_entries(cx)
11471 }
11472
11473 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11474 self.blame()
11475 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11476 }
11477
11478 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11479 let cursor_anchor = self.selections.newest_anchor().head();
11480
11481 let snapshot = self.buffer.read(cx).snapshot(cx);
11482 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11483
11484 snapshot.line_len(buffer_row) == 0
11485 }
11486
11487 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11488 let buffer_and_selection = maybe!({
11489 let selection = self.selections.newest::<Point>(cx);
11490 let selection_range = selection.range();
11491
11492 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11493 (buffer, selection_range.start.row..selection_range.end.row)
11494 } else {
11495 let buffer_ranges = self
11496 .buffer()
11497 .read(cx)
11498 .range_to_buffer_ranges(selection_range, cx);
11499
11500 let (buffer, range, _) = if selection.reversed {
11501 buffer_ranges.first()
11502 } else {
11503 buffer_ranges.last()
11504 }?;
11505
11506 let snapshot = buffer.read(cx).snapshot();
11507 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11508 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11509 (buffer.clone(), selection)
11510 };
11511
11512 Some((buffer, selection))
11513 });
11514
11515 let Some((buffer, selection)) = buffer_and_selection else {
11516 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11517 };
11518
11519 let Some(project) = self.project.as_ref() else {
11520 return Task::ready(Err(anyhow!("editor does not have project")));
11521 };
11522
11523 project.update(cx, |project, cx| {
11524 project.get_permalink_to_line(&buffer, selection, cx)
11525 })
11526 }
11527
11528 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11529 let permalink_task = self.get_permalink_to_line(cx);
11530 let workspace = self.workspace();
11531
11532 cx.spawn(|_, mut cx| async move {
11533 match permalink_task.await {
11534 Ok(permalink) => {
11535 cx.update(|cx| {
11536 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11537 })
11538 .ok();
11539 }
11540 Err(err) => {
11541 let message = format!("Failed to copy permalink: {err}");
11542
11543 Err::<(), anyhow::Error>(err).log_err();
11544
11545 if let Some(workspace) = workspace {
11546 workspace
11547 .update(&mut cx, |workspace, cx| {
11548 struct CopyPermalinkToLine;
11549
11550 workspace.show_toast(
11551 Toast::new(
11552 NotificationId::unique::<CopyPermalinkToLine>(),
11553 message,
11554 ),
11555 cx,
11556 )
11557 })
11558 .ok();
11559 }
11560 }
11561 }
11562 })
11563 .detach();
11564 }
11565
11566 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11567 if let Some(file) = self.target_file(cx) {
11568 if let Some(path) = file.path().to_str() {
11569 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11570 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11571 }
11572 }
11573 }
11574
11575 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11576 let permalink_task = self.get_permalink_to_line(cx);
11577 let workspace = self.workspace();
11578
11579 cx.spawn(|_, mut cx| async move {
11580 match permalink_task.await {
11581 Ok(permalink) => {
11582 cx.update(|cx| {
11583 cx.open_url(permalink.as_ref());
11584 })
11585 .ok();
11586 }
11587 Err(err) => {
11588 let message = format!("Failed to open permalink: {err}");
11589
11590 Err::<(), anyhow::Error>(err).log_err();
11591
11592 if let Some(workspace) = workspace {
11593 workspace
11594 .update(&mut cx, |workspace, cx| {
11595 struct OpenPermalinkToLine;
11596
11597 workspace.show_toast(
11598 Toast::new(
11599 NotificationId::unique::<OpenPermalinkToLine>(),
11600 message,
11601 ),
11602 cx,
11603 )
11604 })
11605 .ok();
11606 }
11607 }
11608 }
11609 })
11610 .detach();
11611 }
11612
11613 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11614 /// last highlight added will be used.
11615 ///
11616 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11617 pub fn highlight_rows<T: 'static>(
11618 &mut self,
11619 range: Range<Anchor>,
11620 color: Hsla,
11621 should_autoscroll: bool,
11622 cx: &mut ViewContext<Self>,
11623 ) {
11624 let snapshot = self.buffer().read(cx).snapshot(cx);
11625 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11626 let ix = row_highlights.binary_search_by(|highlight| {
11627 Ordering::Equal
11628 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11629 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11630 });
11631
11632 if let Err(mut ix) = ix {
11633 let index = post_inc(&mut self.highlight_order);
11634
11635 // If this range intersects with the preceding highlight, then merge it with
11636 // the preceding highlight. Otherwise insert a new highlight.
11637 let mut merged = false;
11638 if ix > 0 {
11639 let prev_highlight = &mut row_highlights[ix - 1];
11640 if prev_highlight
11641 .range
11642 .end
11643 .cmp(&range.start, &snapshot)
11644 .is_ge()
11645 {
11646 ix -= 1;
11647 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11648 prev_highlight.range.end = range.end;
11649 }
11650 merged = true;
11651 prev_highlight.index = index;
11652 prev_highlight.color = color;
11653 prev_highlight.should_autoscroll = should_autoscroll;
11654 }
11655 }
11656
11657 if !merged {
11658 row_highlights.insert(
11659 ix,
11660 RowHighlight {
11661 range: range.clone(),
11662 index,
11663 color,
11664 should_autoscroll,
11665 },
11666 );
11667 }
11668
11669 // If any of the following highlights intersect with this one, merge them.
11670 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11671 let highlight = &row_highlights[ix];
11672 if next_highlight
11673 .range
11674 .start
11675 .cmp(&highlight.range.end, &snapshot)
11676 .is_le()
11677 {
11678 if next_highlight
11679 .range
11680 .end
11681 .cmp(&highlight.range.end, &snapshot)
11682 .is_gt()
11683 {
11684 row_highlights[ix].range.end = next_highlight.range.end;
11685 }
11686 row_highlights.remove(ix + 1);
11687 } else {
11688 break;
11689 }
11690 }
11691 }
11692 }
11693
11694 /// Remove any highlighted row ranges of the given type that intersect the
11695 /// given ranges.
11696 pub fn remove_highlighted_rows<T: 'static>(
11697 &mut self,
11698 ranges_to_remove: Vec<Range<Anchor>>,
11699 cx: &mut ViewContext<Self>,
11700 ) {
11701 let snapshot = self.buffer().read(cx).snapshot(cx);
11702 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11703 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11704 row_highlights.retain(|highlight| {
11705 while let Some(range_to_remove) = ranges_to_remove.peek() {
11706 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11707 Ordering::Less | Ordering::Equal => {
11708 ranges_to_remove.next();
11709 }
11710 Ordering::Greater => {
11711 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11712 Ordering::Less | Ordering::Equal => {
11713 return false;
11714 }
11715 Ordering::Greater => break,
11716 }
11717 }
11718 }
11719 }
11720
11721 true
11722 })
11723 }
11724
11725 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11726 pub fn clear_row_highlights<T: 'static>(&mut self) {
11727 self.highlighted_rows.remove(&TypeId::of::<T>());
11728 }
11729
11730 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11731 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11732 self.highlighted_rows
11733 .get(&TypeId::of::<T>())
11734 .map_or(&[] as &[_], |vec| vec.as_slice())
11735 .iter()
11736 .map(|highlight| (highlight.range.clone(), highlight.color))
11737 }
11738
11739 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11740 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11741 /// Allows to ignore certain kinds of highlights.
11742 pub fn highlighted_display_rows(
11743 &mut self,
11744 cx: &mut WindowContext,
11745 ) -> BTreeMap<DisplayRow, Hsla> {
11746 let snapshot = self.snapshot(cx);
11747 let mut used_highlight_orders = HashMap::default();
11748 self.highlighted_rows
11749 .iter()
11750 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11751 .fold(
11752 BTreeMap::<DisplayRow, Hsla>::new(),
11753 |mut unique_rows, highlight| {
11754 let start = highlight.range.start.to_display_point(&snapshot);
11755 let end = highlight.range.end.to_display_point(&snapshot);
11756 let start_row = start.row().0;
11757 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11758 && end.column() == 0
11759 {
11760 end.row().0.saturating_sub(1)
11761 } else {
11762 end.row().0
11763 };
11764 for row in start_row..=end_row {
11765 let used_index =
11766 used_highlight_orders.entry(row).or_insert(highlight.index);
11767 if highlight.index >= *used_index {
11768 *used_index = highlight.index;
11769 unique_rows.insert(DisplayRow(row), highlight.color);
11770 }
11771 }
11772 unique_rows
11773 },
11774 )
11775 }
11776
11777 pub fn highlighted_display_row_for_autoscroll(
11778 &self,
11779 snapshot: &DisplaySnapshot,
11780 ) -> Option<DisplayRow> {
11781 self.highlighted_rows
11782 .values()
11783 .flat_map(|highlighted_rows| highlighted_rows.iter())
11784 .filter_map(|highlight| {
11785 if highlight.should_autoscroll {
11786 Some(highlight.range.start.to_display_point(snapshot).row())
11787 } else {
11788 None
11789 }
11790 })
11791 .min()
11792 }
11793
11794 pub fn set_search_within_ranges(
11795 &mut self,
11796 ranges: &[Range<Anchor>],
11797 cx: &mut ViewContext<Self>,
11798 ) {
11799 self.highlight_background::<SearchWithinRange>(
11800 ranges,
11801 |colors| colors.editor_document_highlight_read_background,
11802 cx,
11803 )
11804 }
11805
11806 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11807 self.breadcrumb_header = Some(new_header);
11808 }
11809
11810 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11811 self.clear_background_highlights::<SearchWithinRange>(cx);
11812 }
11813
11814 pub fn highlight_background<T: 'static>(
11815 &mut self,
11816 ranges: &[Range<Anchor>],
11817 color_fetcher: fn(&ThemeColors) -> Hsla,
11818 cx: &mut ViewContext<Self>,
11819 ) {
11820 self.background_highlights
11821 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11822 self.scrollbar_marker_state.dirty = true;
11823 cx.notify();
11824 }
11825
11826 pub fn clear_background_highlights<T: 'static>(
11827 &mut self,
11828 cx: &mut ViewContext<Self>,
11829 ) -> Option<BackgroundHighlight> {
11830 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11831 if !text_highlights.1.is_empty() {
11832 self.scrollbar_marker_state.dirty = true;
11833 cx.notify();
11834 }
11835 Some(text_highlights)
11836 }
11837
11838 pub fn highlight_gutter<T: 'static>(
11839 &mut self,
11840 ranges: &[Range<Anchor>],
11841 color_fetcher: fn(&AppContext) -> Hsla,
11842 cx: &mut ViewContext<Self>,
11843 ) {
11844 self.gutter_highlights
11845 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11846 cx.notify();
11847 }
11848
11849 pub fn clear_gutter_highlights<T: 'static>(
11850 &mut self,
11851 cx: &mut ViewContext<Self>,
11852 ) -> Option<GutterHighlight> {
11853 cx.notify();
11854 self.gutter_highlights.remove(&TypeId::of::<T>())
11855 }
11856
11857 #[cfg(feature = "test-support")]
11858 pub fn all_text_background_highlights(
11859 &mut self,
11860 cx: &mut ViewContext<Self>,
11861 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11862 let snapshot = self.snapshot(cx);
11863 let buffer = &snapshot.buffer_snapshot;
11864 let start = buffer.anchor_before(0);
11865 let end = buffer.anchor_after(buffer.len());
11866 let theme = cx.theme().colors();
11867 self.background_highlights_in_range(start..end, &snapshot, theme)
11868 }
11869
11870 #[cfg(feature = "test-support")]
11871 pub fn search_background_highlights(
11872 &mut self,
11873 cx: &mut ViewContext<Self>,
11874 ) -> Vec<Range<Point>> {
11875 let snapshot = self.buffer().read(cx).snapshot(cx);
11876
11877 let highlights = self
11878 .background_highlights
11879 .get(&TypeId::of::<items::BufferSearchHighlights>());
11880
11881 if let Some((_color, ranges)) = highlights {
11882 ranges
11883 .iter()
11884 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11885 .collect_vec()
11886 } else {
11887 vec![]
11888 }
11889 }
11890
11891 fn document_highlights_for_position<'a>(
11892 &'a self,
11893 position: Anchor,
11894 buffer: &'a MultiBufferSnapshot,
11895 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11896 let read_highlights = self
11897 .background_highlights
11898 .get(&TypeId::of::<DocumentHighlightRead>())
11899 .map(|h| &h.1);
11900 let write_highlights = self
11901 .background_highlights
11902 .get(&TypeId::of::<DocumentHighlightWrite>())
11903 .map(|h| &h.1);
11904 let left_position = position.bias_left(buffer);
11905 let right_position = position.bias_right(buffer);
11906 read_highlights
11907 .into_iter()
11908 .chain(write_highlights)
11909 .flat_map(move |ranges| {
11910 let start_ix = match ranges.binary_search_by(|probe| {
11911 let cmp = probe.end.cmp(&left_position, buffer);
11912 if cmp.is_ge() {
11913 Ordering::Greater
11914 } else {
11915 Ordering::Less
11916 }
11917 }) {
11918 Ok(i) | Err(i) => i,
11919 };
11920
11921 ranges[start_ix..]
11922 .iter()
11923 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11924 })
11925 }
11926
11927 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11928 self.background_highlights
11929 .get(&TypeId::of::<T>())
11930 .map_or(false, |(_, highlights)| !highlights.is_empty())
11931 }
11932
11933 pub fn background_highlights_in_range(
11934 &self,
11935 search_range: Range<Anchor>,
11936 display_snapshot: &DisplaySnapshot,
11937 theme: &ThemeColors,
11938 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11939 let mut results = Vec::new();
11940 for (color_fetcher, ranges) in self.background_highlights.values() {
11941 let color = color_fetcher(theme);
11942 let start_ix = match ranges.binary_search_by(|probe| {
11943 let cmp = probe
11944 .end
11945 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11946 if cmp.is_gt() {
11947 Ordering::Greater
11948 } else {
11949 Ordering::Less
11950 }
11951 }) {
11952 Ok(i) | Err(i) => i,
11953 };
11954 for range in &ranges[start_ix..] {
11955 if range
11956 .start
11957 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11958 .is_ge()
11959 {
11960 break;
11961 }
11962
11963 let start = range.start.to_display_point(display_snapshot);
11964 let end = range.end.to_display_point(display_snapshot);
11965 results.push((start..end, color))
11966 }
11967 }
11968 results
11969 }
11970
11971 pub fn background_highlight_row_ranges<T: 'static>(
11972 &self,
11973 search_range: Range<Anchor>,
11974 display_snapshot: &DisplaySnapshot,
11975 count: usize,
11976 ) -> Vec<RangeInclusive<DisplayPoint>> {
11977 let mut results = Vec::new();
11978 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11979 return vec![];
11980 };
11981
11982 let start_ix = match ranges.binary_search_by(|probe| {
11983 let cmp = probe
11984 .end
11985 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11986 if cmp.is_gt() {
11987 Ordering::Greater
11988 } else {
11989 Ordering::Less
11990 }
11991 }) {
11992 Ok(i) | Err(i) => i,
11993 };
11994 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11995 if let (Some(start_display), Some(end_display)) = (start, end) {
11996 results.push(
11997 start_display.to_display_point(display_snapshot)
11998 ..=end_display.to_display_point(display_snapshot),
11999 );
12000 }
12001 };
12002 let mut start_row: Option<Point> = None;
12003 let mut end_row: Option<Point> = None;
12004 if ranges.len() > count {
12005 return Vec::new();
12006 }
12007 for range in &ranges[start_ix..] {
12008 if range
12009 .start
12010 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12011 .is_ge()
12012 {
12013 break;
12014 }
12015 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12016 if let Some(current_row) = &end_row {
12017 if end.row == current_row.row {
12018 continue;
12019 }
12020 }
12021 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12022 if start_row.is_none() {
12023 assert_eq!(end_row, None);
12024 start_row = Some(start);
12025 end_row = Some(end);
12026 continue;
12027 }
12028 if let Some(current_end) = end_row.as_mut() {
12029 if start.row > current_end.row + 1 {
12030 push_region(start_row, end_row);
12031 start_row = Some(start);
12032 end_row = Some(end);
12033 } else {
12034 // Merge two hunks.
12035 *current_end = end;
12036 }
12037 } else {
12038 unreachable!();
12039 }
12040 }
12041 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12042 push_region(start_row, end_row);
12043 results
12044 }
12045
12046 pub fn gutter_highlights_in_range(
12047 &self,
12048 search_range: Range<Anchor>,
12049 display_snapshot: &DisplaySnapshot,
12050 cx: &AppContext,
12051 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12052 let mut results = Vec::new();
12053 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12054 let color = color_fetcher(cx);
12055 let start_ix = match ranges.binary_search_by(|probe| {
12056 let cmp = probe
12057 .end
12058 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12059 if cmp.is_gt() {
12060 Ordering::Greater
12061 } else {
12062 Ordering::Less
12063 }
12064 }) {
12065 Ok(i) | Err(i) => i,
12066 };
12067 for range in &ranges[start_ix..] {
12068 if range
12069 .start
12070 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12071 .is_ge()
12072 {
12073 break;
12074 }
12075
12076 let start = range.start.to_display_point(display_snapshot);
12077 let end = range.end.to_display_point(display_snapshot);
12078 results.push((start..end, color))
12079 }
12080 }
12081 results
12082 }
12083
12084 /// Get the text ranges corresponding to the redaction query
12085 pub fn redacted_ranges(
12086 &self,
12087 search_range: Range<Anchor>,
12088 display_snapshot: &DisplaySnapshot,
12089 cx: &WindowContext,
12090 ) -> Vec<Range<DisplayPoint>> {
12091 display_snapshot
12092 .buffer_snapshot
12093 .redacted_ranges(search_range, |file| {
12094 if let Some(file) = file {
12095 file.is_private()
12096 && EditorSettings::get(
12097 Some(SettingsLocation {
12098 worktree_id: file.worktree_id(cx),
12099 path: file.path().as_ref(),
12100 }),
12101 cx,
12102 )
12103 .redact_private_values
12104 } else {
12105 false
12106 }
12107 })
12108 .map(|range| {
12109 range.start.to_display_point(display_snapshot)
12110 ..range.end.to_display_point(display_snapshot)
12111 })
12112 .collect()
12113 }
12114
12115 pub fn highlight_text<T: 'static>(
12116 &mut self,
12117 ranges: Vec<Range<Anchor>>,
12118 style: HighlightStyle,
12119 cx: &mut ViewContext<Self>,
12120 ) {
12121 self.display_map.update(cx, |map, _| {
12122 map.highlight_text(TypeId::of::<T>(), ranges, style)
12123 });
12124 cx.notify();
12125 }
12126
12127 pub(crate) fn highlight_inlays<T: 'static>(
12128 &mut self,
12129 highlights: Vec<InlayHighlight>,
12130 style: HighlightStyle,
12131 cx: &mut ViewContext<Self>,
12132 ) {
12133 self.display_map.update(cx, |map, _| {
12134 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12135 });
12136 cx.notify();
12137 }
12138
12139 pub fn text_highlights<'a, T: 'static>(
12140 &'a self,
12141 cx: &'a AppContext,
12142 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12143 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12144 }
12145
12146 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12147 let cleared = self
12148 .display_map
12149 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12150 if cleared {
12151 cx.notify();
12152 }
12153 }
12154
12155 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12156 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12157 && self.focus_handle.is_focused(cx)
12158 }
12159
12160 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12161 self.show_cursor_when_unfocused = is_enabled;
12162 cx.notify();
12163 }
12164
12165 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12166 cx.notify();
12167 }
12168
12169 fn on_buffer_event(
12170 &mut self,
12171 multibuffer: Model<MultiBuffer>,
12172 event: &multi_buffer::Event,
12173 cx: &mut ViewContext<Self>,
12174 ) {
12175 match event {
12176 multi_buffer::Event::Edited {
12177 singleton_buffer_edited,
12178 } => {
12179 self.scrollbar_marker_state.dirty = true;
12180 self.active_indent_guides_state.dirty = true;
12181 self.refresh_active_diagnostics(cx);
12182 self.refresh_code_actions(cx);
12183 if self.has_active_inline_completion(cx) {
12184 self.update_visible_inline_completion(cx);
12185 }
12186 cx.emit(EditorEvent::BufferEdited);
12187 cx.emit(SearchEvent::MatchesInvalidated);
12188 if *singleton_buffer_edited {
12189 if let Some(project) = &self.project {
12190 let project = project.read(cx);
12191 #[allow(clippy::mutable_key_type)]
12192 let languages_affected = multibuffer
12193 .read(cx)
12194 .all_buffers()
12195 .into_iter()
12196 .filter_map(|buffer| {
12197 let buffer = buffer.read(cx);
12198 let language = buffer.language()?;
12199 if project.is_local()
12200 && project.language_servers_for_buffer(buffer, cx).count() == 0
12201 {
12202 None
12203 } else {
12204 Some(language)
12205 }
12206 })
12207 .cloned()
12208 .collect::<HashSet<_>>();
12209 if !languages_affected.is_empty() {
12210 self.refresh_inlay_hints(
12211 InlayHintRefreshReason::BufferEdited(languages_affected),
12212 cx,
12213 );
12214 }
12215 }
12216 }
12217
12218 let Some(project) = &self.project else { return };
12219 let (telemetry, is_via_ssh) = {
12220 let project = project.read(cx);
12221 let telemetry = project.client().telemetry().clone();
12222 let is_via_ssh = project.is_via_ssh();
12223 (telemetry, is_via_ssh)
12224 };
12225 refresh_linked_ranges(self, cx);
12226 telemetry.log_edit_event("editor", is_via_ssh);
12227 }
12228 multi_buffer::Event::ExcerptsAdded {
12229 buffer,
12230 predecessor,
12231 excerpts,
12232 } => {
12233 self.tasks_update_task = Some(self.refresh_runnables(cx));
12234 cx.emit(EditorEvent::ExcerptsAdded {
12235 buffer: buffer.clone(),
12236 predecessor: *predecessor,
12237 excerpts: excerpts.clone(),
12238 });
12239 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12240 }
12241 multi_buffer::Event::ExcerptsRemoved { ids } => {
12242 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12243 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12244 }
12245 multi_buffer::Event::ExcerptsEdited { ids } => {
12246 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12247 }
12248 multi_buffer::Event::ExcerptsExpanded { ids } => {
12249 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12250 }
12251 multi_buffer::Event::Reparsed(buffer_id) => {
12252 self.tasks_update_task = Some(self.refresh_runnables(cx));
12253
12254 cx.emit(EditorEvent::Reparsed(*buffer_id));
12255 }
12256 multi_buffer::Event::LanguageChanged(buffer_id) => {
12257 linked_editing_ranges::refresh_linked_ranges(self, cx);
12258 cx.emit(EditorEvent::Reparsed(*buffer_id));
12259 cx.notify();
12260 }
12261 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12262 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12263 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12264 cx.emit(EditorEvent::TitleChanged)
12265 }
12266 multi_buffer::Event::DiffBaseChanged => {
12267 self.scrollbar_marker_state.dirty = true;
12268 cx.emit(EditorEvent::DiffBaseChanged);
12269 cx.notify();
12270 }
12271 multi_buffer::Event::DiffUpdated { buffer } => {
12272 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12273 cx.notify();
12274 }
12275 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12276 multi_buffer::Event::DiagnosticsUpdated => {
12277 self.refresh_active_diagnostics(cx);
12278 self.scrollbar_marker_state.dirty = true;
12279 cx.notify();
12280 }
12281 _ => {}
12282 };
12283 }
12284
12285 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12286 cx.notify();
12287 }
12288
12289 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12290 self.tasks_update_task = Some(self.refresh_runnables(cx));
12291 self.refresh_inline_completion(true, false, cx);
12292 self.refresh_inlay_hints(
12293 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12294 self.selections.newest_anchor().head(),
12295 &self.buffer.read(cx).snapshot(cx),
12296 cx,
12297 )),
12298 cx,
12299 );
12300
12301 let old_cursor_shape = self.cursor_shape;
12302
12303 {
12304 let editor_settings = EditorSettings::get_global(cx);
12305 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12306 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12307 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12308 }
12309
12310 if old_cursor_shape != self.cursor_shape {
12311 cx.emit(EditorEvent::CursorShapeChanged);
12312 }
12313
12314 let project_settings = ProjectSettings::get_global(cx);
12315 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12316
12317 if self.mode == EditorMode::Full {
12318 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12319 if self.git_blame_inline_enabled != inline_blame_enabled {
12320 self.toggle_git_blame_inline_internal(false, cx);
12321 }
12322 }
12323
12324 cx.notify();
12325 }
12326
12327 pub fn set_searchable(&mut self, searchable: bool) {
12328 self.searchable = searchable;
12329 }
12330
12331 pub fn searchable(&self) -> bool {
12332 self.searchable
12333 }
12334
12335 fn open_proposed_changes_editor(
12336 &mut self,
12337 _: &OpenProposedChangesEditor,
12338 cx: &mut ViewContext<Self>,
12339 ) {
12340 let Some(workspace) = self.workspace() else {
12341 cx.propagate();
12342 return;
12343 };
12344
12345 let buffer = self.buffer.read(cx);
12346 let mut new_selections_by_buffer = HashMap::default();
12347 for selection in self.selections.all::<usize>(cx) {
12348 for (buffer, range, _) in
12349 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12350 {
12351 let mut range = range.to_point(buffer.read(cx));
12352 range.start.column = 0;
12353 range.end.column = buffer.read(cx).line_len(range.end.row);
12354 new_selections_by_buffer
12355 .entry(buffer)
12356 .or_insert(Vec::new())
12357 .push(range)
12358 }
12359 }
12360
12361 let proposed_changes_buffers = new_selections_by_buffer
12362 .into_iter()
12363 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12364 .collect::<Vec<_>>();
12365 let proposed_changes_editor = cx.new_view(|cx| {
12366 ProposedChangesEditor::new(
12367 "Proposed changes",
12368 proposed_changes_buffers,
12369 self.project.clone(),
12370 cx,
12371 )
12372 });
12373
12374 cx.window_context().defer(move |cx| {
12375 workspace.update(cx, |workspace, cx| {
12376 workspace.active_pane().update(cx, |pane, cx| {
12377 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12378 });
12379 });
12380 });
12381 }
12382
12383 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12384 self.open_excerpts_common(true, cx)
12385 }
12386
12387 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12388 self.open_excerpts_common(false, cx)
12389 }
12390
12391 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12392 let buffer = self.buffer.read(cx);
12393 if buffer.is_singleton() {
12394 cx.propagate();
12395 return;
12396 }
12397
12398 let Some(workspace) = self.workspace() else {
12399 cx.propagate();
12400 return;
12401 };
12402
12403 let mut new_selections_by_buffer = HashMap::default();
12404 for selection in self.selections.all::<usize>(cx) {
12405 for (mut buffer_handle, mut range, _) in
12406 buffer.range_to_buffer_ranges(selection.range(), cx)
12407 {
12408 // When editing branch buffers, jump to the corresponding location
12409 // in their base buffer.
12410 let buffer = buffer_handle.read(cx);
12411 if let Some(base_buffer) = buffer.diff_base_buffer() {
12412 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12413 buffer_handle = base_buffer;
12414 }
12415
12416 if selection.reversed {
12417 mem::swap(&mut range.start, &mut range.end);
12418 }
12419 new_selections_by_buffer
12420 .entry(buffer_handle)
12421 .or_insert(Vec::new())
12422 .push(range)
12423 }
12424 }
12425
12426 // We defer the pane interaction because we ourselves are a workspace item
12427 // and activating a new item causes the pane to call a method on us reentrantly,
12428 // which panics if we're on the stack.
12429 cx.window_context().defer(move |cx| {
12430 workspace.update(cx, |workspace, cx| {
12431 let pane = if split {
12432 workspace.adjacent_pane(cx)
12433 } else {
12434 workspace.active_pane().clone()
12435 };
12436
12437 for (buffer, ranges) in new_selections_by_buffer {
12438 let editor =
12439 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12440 editor.update(cx, |editor, cx| {
12441 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12442 s.select_ranges(ranges);
12443 });
12444 });
12445 }
12446 })
12447 });
12448 }
12449
12450 fn jump(
12451 &mut self,
12452 path: ProjectPath,
12453 position: Point,
12454 anchor: language::Anchor,
12455 offset_from_top: u32,
12456 cx: &mut ViewContext<Self>,
12457 ) {
12458 let workspace = self.workspace();
12459 cx.spawn(|_, mut cx| async move {
12460 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12461 let editor = workspace.update(&mut cx, |workspace, cx| {
12462 // Reset the preview item id before opening the new item
12463 workspace.active_pane().update(cx, |pane, cx| {
12464 pane.set_preview_item_id(None, cx);
12465 });
12466 workspace.open_path_preview(path, None, true, true, cx)
12467 })?;
12468 let editor = editor
12469 .await?
12470 .downcast::<Editor>()
12471 .ok_or_else(|| anyhow!("opened item was not an editor"))?
12472 .downgrade();
12473 editor.update(&mut cx, |editor, cx| {
12474 let buffer = editor
12475 .buffer()
12476 .read(cx)
12477 .as_singleton()
12478 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12479 let buffer = buffer.read(cx);
12480 let cursor = if buffer.can_resolve(&anchor) {
12481 language::ToPoint::to_point(&anchor, buffer)
12482 } else {
12483 buffer.clip_point(position, Bias::Left)
12484 };
12485
12486 let nav_history = editor.nav_history.take();
12487 editor.change_selections(
12488 Some(Autoscroll::top_relative(offset_from_top as usize)),
12489 cx,
12490 |s| {
12491 s.select_ranges([cursor..cursor]);
12492 },
12493 );
12494 editor.nav_history = nav_history;
12495
12496 anyhow::Ok(())
12497 })??;
12498
12499 anyhow::Ok(())
12500 })
12501 .detach_and_log_err(cx);
12502 }
12503
12504 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12505 let snapshot = self.buffer.read(cx).read(cx);
12506 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12507 Some(
12508 ranges
12509 .iter()
12510 .map(move |range| {
12511 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12512 })
12513 .collect(),
12514 )
12515 }
12516
12517 fn selection_replacement_ranges(
12518 &self,
12519 range: Range<OffsetUtf16>,
12520 cx: &AppContext,
12521 ) -> Vec<Range<OffsetUtf16>> {
12522 let selections = self.selections.all::<OffsetUtf16>(cx);
12523 let newest_selection = selections
12524 .iter()
12525 .max_by_key(|selection| selection.id)
12526 .unwrap();
12527 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12528 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12529 let snapshot = self.buffer.read(cx).read(cx);
12530 selections
12531 .into_iter()
12532 .map(|mut selection| {
12533 selection.start.0 =
12534 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12535 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12536 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12537 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12538 })
12539 .collect()
12540 }
12541
12542 fn report_editor_event(
12543 &self,
12544 operation: &'static str,
12545 file_extension: Option<String>,
12546 cx: &AppContext,
12547 ) {
12548 if cfg!(any(test, feature = "test-support")) {
12549 return;
12550 }
12551
12552 let Some(project) = &self.project else { return };
12553
12554 // If None, we are in a file without an extension
12555 let file = self
12556 .buffer
12557 .read(cx)
12558 .as_singleton()
12559 .and_then(|b| b.read(cx).file());
12560 let file_extension = file_extension.or(file
12561 .as_ref()
12562 .and_then(|file| Path::new(file.file_name(cx)).extension())
12563 .and_then(|e| e.to_str())
12564 .map(|a| a.to_string()));
12565
12566 let vim_mode = cx
12567 .global::<SettingsStore>()
12568 .raw_user_settings()
12569 .get("vim_mode")
12570 == Some(&serde_json::Value::Bool(true));
12571
12572 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12573 == language::language_settings::InlineCompletionProvider::Copilot;
12574 let copilot_enabled_for_language = self
12575 .buffer
12576 .read(cx)
12577 .settings_at(0, cx)
12578 .show_inline_completions;
12579
12580 let project = project.read(cx);
12581 let telemetry = project.client().telemetry().clone();
12582 telemetry.report_editor_event(
12583 file_extension,
12584 vim_mode,
12585 operation,
12586 copilot_enabled,
12587 copilot_enabled_for_language,
12588 project.is_via_ssh(),
12589 )
12590 }
12591
12592 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12593 /// with each line being an array of {text, highlight} objects.
12594 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12595 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12596 return;
12597 };
12598
12599 #[derive(Serialize)]
12600 struct Chunk<'a> {
12601 text: String,
12602 highlight: Option<&'a str>,
12603 }
12604
12605 let snapshot = buffer.read(cx).snapshot();
12606 let range = self
12607 .selected_text_range(false, cx)
12608 .and_then(|selection| {
12609 if selection.range.is_empty() {
12610 None
12611 } else {
12612 Some(selection.range)
12613 }
12614 })
12615 .unwrap_or_else(|| 0..snapshot.len());
12616
12617 let chunks = snapshot.chunks(range, true);
12618 let mut lines = Vec::new();
12619 let mut line: VecDeque<Chunk> = VecDeque::new();
12620
12621 let Some(style) = self.style.as_ref() else {
12622 return;
12623 };
12624
12625 for chunk in chunks {
12626 let highlight = chunk
12627 .syntax_highlight_id
12628 .and_then(|id| id.name(&style.syntax));
12629 let mut chunk_lines = chunk.text.split('\n').peekable();
12630 while let Some(text) = chunk_lines.next() {
12631 let mut merged_with_last_token = false;
12632 if let Some(last_token) = line.back_mut() {
12633 if last_token.highlight == highlight {
12634 last_token.text.push_str(text);
12635 merged_with_last_token = true;
12636 }
12637 }
12638
12639 if !merged_with_last_token {
12640 line.push_back(Chunk {
12641 text: text.into(),
12642 highlight,
12643 });
12644 }
12645
12646 if chunk_lines.peek().is_some() {
12647 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12648 line.pop_front();
12649 }
12650 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12651 line.pop_back();
12652 }
12653
12654 lines.push(mem::take(&mut line));
12655 }
12656 }
12657 }
12658
12659 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12660 return;
12661 };
12662 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12663 }
12664
12665 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12666 &self.inlay_hint_cache
12667 }
12668
12669 pub fn replay_insert_event(
12670 &mut self,
12671 text: &str,
12672 relative_utf16_range: Option<Range<isize>>,
12673 cx: &mut ViewContext<Self>,
12674 ) {
12675 if !self.input_enabled {
12676 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12677 return;
12678 }
12679 if let Some(relative_utf16_range) = relative_utf16_range {
12680 let selections = self.selections.all::<OffsetUtf16>(cx);
12681 self.change_selections(None, cx, |s| {
12682 let new_ranges = selections.into_iter().map(|range| {
12683 let start = OffsetUtf16(
12684 range
12685 .head()
12686 .0
12687 .saturating_add_signed(relative_utf16_range.start),
12688 );
12689 let end = OffsetUtf16(
12690 range
12691 .head()
12692 .0
12693 .saturating_add_signed(relative_utf16_range.end),
12694 );
12695 start..end
12696 });
12697 s.select_ranges(new_ranges);
12698 });
12699 }
12700
12701 self.handle_input(text, cx);
12702 }
12703
12704 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12705 let Some(provider) = self.semantics_provider.as_ref() else {
12706 return false;
12707 };
12708
12709 let mut supports = false;
12710 self.buffer().read(cx).for_each_buffer(|buffer| {
12711 supports |= provider.supports_inlay_hints(buffer, cx);
12712 });
12713 supports
12714 }
12715
12716 pub fn focus(&self, cx: &mut WindowContext) {
12717 cx.focus(&self.focus_handle)
12718 }
12719
12720 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12721 self.focus_handle.is_focused(cx)
12722 }
12723
12724 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12725 cx.emit(EditorEvent::Focused);
12726
12727 if let Some(descendant) = self
12728 .last_focused_descendant
12729 .take()
12730 .and_then(|descendant| descendant.upgrade())
12731 {
12732 cx.focus(&descendant);
12733 } else {
12734 if let Some(blame) = self.blame.as_ref() {
12735 blame.update(cx, GitBlame::focus)
12736 }
12737
12738 self.blink_manager.update(cx, BlinkManager::enable);
12739 self.show_cursor_names(cx);
12740 self.buffer.update(cx, |buffer, cx| {
12741 buffer.finalize_last_transaction(cx);
12742 if self.leader_peer_id.is_none() {
12743 buffer.set_active_selections(
12744 &self.selections.disjoint_anchors(),
12745 self.selections.line_mode,
12746 self.cursor_shape,
12747 cx,
12748 );
12749 }
12750 });
12751 }
12752 }
12753
12754 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12755 cx.emit(EditorEvent::FocusedIn)
12756 }
12757
12758 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12759 if event.blurred != self.focus_handle {
12760 self.last_focused_descendant = Some(event.blurred);
12761 }
12762 }
12763
12764 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12765 self.blink_manager.update(cx, BlinkManager::disable);
12766 self.buffer
12767 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12768
12769 if let Some(blame) = self.blame.as_ref() {
12770 blame.update(cx, GitBlame::blur)
12771 }
12772 if !self.hover_state.focused(cx) {
12773 hide_hover(self, cx);
12774 }
12775
12776 self.hide_context_menu(cx);
12777 cx.emit(EditorEvent::Blurred);
12778 cx.notify();
12779 }
12780
12781 pub fn register_action<A: Action>(
12782 &mut self,
12783 listener: impl Fn(&A, &mut WindowContext) + 'static,
12784 ) -> Subscription {
12785 let id = self.next_editor_action_id.post_inc();
12786 let listener = Arc::new(listener);
12787 self.editor_actions.borrow_mut().insert(
12788 id,
12789 Box::new(move |cx| {
12790 let cx = cx.window_context();
12791 let listener = listener.clone();
12792 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12793 let action = action.downcast_ref().unwrap();
12794 if phase == DispatchPhase::Bubble {
12795 listener(action, cx)
12796 }
12797 })
12798 }),
12799 );
12800
12801 let editor_actions = self.editor_actions.clone();
12802 Subscription::new(move || {
12803 editor_actions.borrow_mut().remove(&id);
12804 })
12805 }
12806
12807 pub fn file_header_size(&self) -> u32 {
12808 FILE_HEADER_HEIGHT
12809 }
12810
12811 pub fn revert(
12812 &mut self,
12813 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12814 cx: &mut ViewContext<Self>,
12815 ) {
12816 self.buffer().update(cx, |multi_buffer, cx| {
12817 for (buffer_id, changes) in revert_changes {
12818 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12819 buffer.update(cx, |buffer, cx| {
12820 buffer.edit(
12821 changes.into_iter().map(|(range, text)| {
12822 (range, text.to_string().map(Arc::<str>::from))
12823 }),
12824 None,
12825 cx,
12826 );
12827 });
12828 }
12829 }
12830 });
12831 self.change_selections(None, cx, |selections| selections.refresh());
12832 }
12833
12834 pub fn to_pixel_point(
12835 &mut self,
12836 source: multi_buffer::Anchor,
12837 editor_snapshot: &EditorSnapshot,
12838 cx: &mut ViewContext<Self>,
12839 ) -> Option<gpui::Point<Pixels>> {
12840 let source_point = source.to_display_point(editor_snapshot);
12841 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12842 }
12843
12844 pub fn display_to_pixel_point(
12845 &mut self,
12846 source: DisplayPoint,
12847 editor_snapshot: &EditorSnapshot,
12848 cx: &mut ViewContext<Self>,
12849 ) -> Option<gpui::Point<Pixels>> {
12850 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12851 let text_layout_details = self.text_layout_details(cx);
12852 let scroll_top = text_layout_details
12853 .scroll_anchor
12854 .scroll_position(editor_snapshot)
12855 .y;
12856
12857 if source.row().as_f32() < scroll_top.floor() {
12858 return None;
12859 }
12860 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12861 let source_y = line_height * (source.row().as_f32() - scroll_top);
12862 Some(gpui::Point::new(source_x, source_y))
12863 }
12864
12865 pub fn has_active_completions_menu(&self) -> bool {
12866 self.context_menu.read().as_ref().map_or(false, |menu| {
12867 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12868 })
12869 }
12870
12871 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12872 self.addons
12873 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12874 }
12875
12876 pub fn unregister_addon<T: Addon>(&mut self) {
12877 self.addons.remove(&std::any::TypeId::of::<T>());
12878 }
12879
12880 pub fn addon<T: Addon>(&self) -> Option<&T> {
12881 let type_id = std::any::TypeId::of::<T>();
12882 self.addons
12883 .get(&type_id)
12884 .and_then(|item| item.to_any().downcast_ref::<T>())
12885 }
12886}
12887
12888fn hunks_for_selections(
12889 multi_buffer_snapshot: &MultiBufferSnapshot,
12890 selections: &[Selection<Anchor>],
12891) -> Vec<MultiBufferDiffHunk> {
12892 let buffer_rows_for_selections = selections.iter().map(|selection| {
12893 let head = selection.head();
12894 let tail = selection.tail();
12895 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12896 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12897 if start > end {
12898 end..start
12899 } else {
12900 start..end
12901 }
12902 });
12903
12904 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12905}
12906
12907pub fn hunks_for_rows(
12908 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12909 multi_buffer_snapshot: &MultiBufferSnapshot,
12910) -> Vec<MultiBufferDiffHunk> {
12911 let mut hunks = Vec::new();
12912 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12913 HashMap::default();
12914 for selected_multi_buffer_rows in rows {
12915 let query_rows =
12916 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12917 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12918 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12919 // when the caret is just above or just below the deleted hunk.
12920 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12921 let related_to_selection = if allow_adjacent {
12922 hunk.row_range.overlaps(&query_rows)
12923 || hunk.row_range.start == query_rows.end
12924 || hunk.row_range.end == query_rows.start
12925 } else {
12926 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12927 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12928 hunk.row_range.overlaps(&selected_multi_buffer_rows)
12929 || selected_multi_buffer_rows.end == hunk.row_range.start
12930 };
12931 if related_to_selection {
12932 if !processed_buffer_rows
12933 .entry(hunk.buffer_id)
12934 .or_default()
12935 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12936 {
12937 continue;
12938 }
12939 hunks.push(hunk);
12940 }
12941 }
12942 }
12943
12944 hunks
12945}
12946
12947pub trait CollaborationHub {
12948 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12949 fn user_participant_indices<'a>(
12950 &self,
12951 cx: &'a AppContext,
12952 ) -> &'a HashMap<u64, ParticipantIndex>;
12953 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12954}
12955
12956impl CollaborationHub for Model<Project> {
12957 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12958 self.read(cx).collaborators()
12959 }
12960
12961 fn user_participant_indices<'a>(
12962 &self,
12963 cx: &'a AppContext,
12964 ) -> &'a HashMap<u64, ParticipantIndex> {
12965 self.read(cx).user_store().read(cx).participant_indices()
12966 }
12967
12968 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12969 let this = self.read(cx);
12970 let user_ids = this.collaborators().values().map(|c| c.user_id);
12971 this.user_store().read_with(cx, |user_store, cx| {
12972 user_store.participant_names(user_ids, cx)
12973 })
12974 }
12975}
12976
12977pub trait SemanticsProvider {
12978 fn hover(
12979 &self,
12980 buffer: &Model<Buffer>,
12981 position: text::Anchor,
12982 cx: &mut AppContext,
12983 ) -> Option<Task<Vec<project::Hover>>>;
12984
12985 fn inlay_hints(
12986 &self,
12987 buffer_handle: Model<Buffer>,
12988 range: Range<text::Anchor>,
12989 cx: &mut AppContext,
12990 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
12991
12992 fn resolve_inlay_hint(
12993 &self,
12994 hint: InlayHint,
12995 buffer_handle: Model<Buffer>,
12996 server_id: LanguageServerId,
12997 cx: &mut AppContext,
12998 ) -> Option<Task<anyhow::Result<InlayHint>>>;
12999
13000 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
13001
13002 fn document_highlights(
13003 &self,
13004 buffer: &Model<Buffer>,
13005 position: text::Anchor,
13006 cx: &mut AppContext,
13007 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13008
13009 fn definitions(
13010 &self,
13011 buffer: &Model<Buffer>,
13012 position: text::Anchor,
13013 kind: GotoDefinitionKind,
13014 cx: &mut AppContext,
13015 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13016
13017 fn range_for_rename(
13018 &self,
13019 buffer: &Model<Buffer>,
13020 position: text::Anchor,
13021 cx: &mut AppContext,
13022 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13023
13024 fn perform_rename(
13025 &self,
13026 buffer: &Model<Buffer>,
13027 position: text::Anchor,
13028 new_name: String,
13029 cx: &mut AppContext,
13030 ) -> Option<Task<Result<ProjectTransaction>>>;
13031}
13032
13033pub trait CompletionProvider {
13034 fn completions(
13035 &self,
13036 buffer: &Model<Buffer>,
13037 buffer_position: text::Anchor,
13038 trigger: CompletionContext,
13039 cx: &mut ViewContext<Editor>,
13040 ) -> Task<Result<Vec<Completion>>>;
13041
13042 fn resolve_completions(
13043 &self,
13044 buffer: Model<Buffer>,
13045 completion_indices: Vec<usize>,
13046 completions: Arc<RwLock<Box<[Completion]>>>,
13047 cx: &mut ViewContext<Editor>,
13048 ) -> Task<Result<bool>>;
13049
13050 fn apply_additional_edits_for_completion(
13051 &self,
13052 buffer: Model<Buffer>,
13053 completion: Completion,
13054 push_to_history: bool,
13055 cx: &mut ViewContext<Editor>,
13056 ) -> Task<Result<Option<language::Transaction>>>;
13057
13058 fn is_completion_trigger(
13059 &self,
13060 buffer: &Model<Buffer>,
13061 position: language::Anchor,
13062 text: &str,
13063 trigger_in_words: bool,
13064 cx: &mut ViewContext<Editor>,
13065 ) -> bool;
13066
13067 fn sort_completions(&self) -> bool {
13068 true
13069 }
13070}
13071
13072pub trait CodeActionProvider {
13073 fn code_actions(
13074 &self,
13075 buffer: &Model<Buffer>,
13076 range: Range<text::Anchor>,
13077 cx: &mut WindowContext,
13078 ) -> Task<Result<Vec<CodeAction>>>;
13079
13080 fn apply_code_action(
13081 &self,
13082 buffer_handle: Model<Buffer>,
13083 action: CodeAction,
13084 excerpt_id: ExcerptId,
13085 push_to_history: bool,
13086 cx: &mut WindowContext,
13087 ) -> Task<Result<ProjectTransaction>>;
13088}
13089
13090impl CodeActionProvider for Model<Project> {
13091 fn code_actions(
13092 &self,
13093 buffer: &Model<Buffer>,
13094 range: Range<text::Anchor>,
13095 cx: &mut WindowContext,
13096 ) -> Task<Result<Vec<CodeAction>>> {
13097 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13098 }
13099
13100 fn apply_code_action(
13101 &self,
13102 buffer_handle: Model<Buffer>,
13103 action: CodeAction,
13104 _excerpt_id: ExcerptId,
13105 push_to_history: bool,
13106 cx: &mut WindowContext,
13107 ) -> Task<Result<ProjectTransaction>> {
13108 self.update(cx, |project, cx| {
13109 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13110 })
13111 }
13112}
13113
13114fn snippet_completions(
13115 project: &Project,
13116 buffer: &Model<Buffer>,
13117 buffer_position: text::Anchor,
13118 cx: &mut AppContext,
13119) -> Vec<Completion> {
13120 let language = buffer.read(cx).language_at(buffer_position);
13121 let language_name = language.as_ref().map(|language| language.lsp_id());
13122 let snippet_store = project.snippets().read(cx);
13123 let snippets = snippet_store.snippets_for(language_name, cx);
13124
13125 if snippets.is_empty() {
13126 return vec![];
13127 }
13128 let snapshot = buffer.read(cx).text_snapshot();
13129 let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13130
13131 let scope = language.map(|language| language.default_scope());
13132 let classifier = CharClassifier::new(scope).for_completion(true);
13133 let mut last_word = chars
13134 .take_while(|c| classifier.is_word(*c))
13135 .collect::<String>();
13136 last_word = last_word.chars().rev().collect();
13137 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13138 let to_lsp = |point: &text::Anchor| {
13139 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13140 point_to_lsp(end)
13141 };
13142 let lsp_end = to_lsp(&buffer_position);
13143 snippets
13144 .into_iter()
13145 .filter_map(|snippet| {
13146 let matching_prefix = snippet
13147 .prefix
13148 .iter()
13149 .find(|prefix| prefix.starts_with(&last_word))?;
13150 let start = as_offset - last_word.len();
13151 let start = snapshot.anchor_before(start);
13152 let range = start..buffer_position;
13153 let lsp_start = to_lsp(&start);
13154 let lsp_range = lsp::Range {
13155 start: lsp_start,
13156 end: lsp_end,
13157 };
13158 Some(Completion {
13159 old_range: range,
13160 new_text: snippet.body.clone(),
13161 label: CodeLabel {
13162 text: matching_prefix.clone(),
13163 runs: vec![],
13164 filter_range: 0..matching_prefix.len(),
13165 },
13166 server_id: LanguageServerId(usize::MAX),
13167 documentation: snippet.description.clone().map(Documentation::SingleLine),
13168 lsp_completion: lsp::CompletionItem {
13169 label: snippet.prefix.first().unwrap().clone(),
13170 kind: Some(CompletionItemKind::SNIPPET),
13171 label_details: snippet.description.as_ref().map(|description| {
13172 lsp::CompletionItemLabelDetails {
13173 detail: Some(description.clone()),
13174 description: None,
13175 }
13176 }),
13177 insert_text_format: Some(InsertTextFormat::SNIPPET),
13178 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13179 lsp::InsertReplaceEdit {
13180 new_text: snippet.body.clone(),
13181 insert: lsp_range,
13182 replace: lsp_range,
13183 },
13184 )),
13185 filter_text: Some(snippet.body.clone()),
13186 sort_text: Some(char::MAX.to_string()),
13187 ..Default::default()
13188 },
13189 confirm: None,
13190 })
13191 })
13192 .collect()
13193}
13194
13195impl CompletionProvider for Model<Project> {
13196 fn completions(
13197 &self,
13198 buffer: &Model<Buffer>,
13199 buffer_position: text::Anchor,
13200 options: CompletionContext,
13201 cx: &mut ViewContext<Editor>,
13202 ) -> Task<Result<Vec<Completion>>> {
13203 self.update(cx, |project, cx| {
13204 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13205 let project_completions = project.completions(buffer, buffer_position, options, cx);
13206 cx.background_executor().spawn(async move {
13207 let mut completions = project_completions.await?;
13208 //let snippets = snippets.into_iter().;
13209 completions.extend(snippets);
13210 Ok(completions)
13211 })
13212 })
13213 }
13214
13215 fn resolve_completions(
13216 &self,
13217 buffer: Model<Buffer>,
13218 completion_indices: Vec<usize>,
13219 completions: Arc<RwLock<Box<[Completion]>>>,
13220 cx: &mut ViewContext<Editor>,
13221 ) -> Task<Result<bool>> {
13222 self.update(cx, |project, cx| {
13223 project.resolve_completions(buffer, completion_indices, completions, cx)
13224 })
13225 }
13226
13227 fn apply_additional_edits_for_completion(
13228 &self,
13229 buffer: Model<Buffer>,
13230 completion: Completion,
13231 push_to_history: bool,
13232 cx: &mut ViewContext<Editor>,
13233 ) -> Task<Result<Option<language::Transaction>>> {
13234 self.update(cx, |project, cx| {
13235 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13236 })
13237 }
13238
13239 fn is_completion_trigger(
13240 &self,
13241 buffer: &Model<Buffer>,
13242 position: language::Anchor,
13243 text: &str,
13244 trigger_in_words: bool,
13245 cx: &mut ViewContext<Editor>,
13246 ) -> bool {
13247 if !EditorSettings::get_global(cx).show_completions_on_input {
13248 return false;
13249 }
13250
13251 let mut chars = text.chars();
13252 let char = if let Some(char) = chars.next() {
13253 char
13254 } else {
13255 return false;
13256 };
13257 if chars.next().is_some() {
13258 return false;
13259 }
13260
13261 let buffer = buffer.read(cx);
13262 let classifier = buffer
13263 .snapshot()
13264 .char_classifier_at(position)
13265 .for_completion(true);
13266 if trigger_in_words && classifier.is_word(char) {
13267 return true;
13268 }
13269
13270 buffer
13271 .completion_triggers()
13272 .iter()
13273 .any(|string| string == text)
13274 }
13275}
13276
13277impl SemanticsProvider for Model<Project> {
13278 fn hover(
13279 &self,
13280 buffer: &Model<Buffer>,
13281 position: text::Anchor,
13282 cx: &mut AppContext,
13283 ) -> Option<Task<Vec<project::Hover>>> {
13284 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13285 }
13286
13287 fn document_highlights(
13288 &self,
13289 buffer: &Model<Buffer>,
13290 position: text::Anchor,
13291 cx: &mut AppContext,
13292 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13293 Some(self.update(cx, |project, cx| {
13294 project.document_highlights(buffer, position, cx)
13295 }))
13296 }
13297
13298 fn definitions(
13299 &self,
13300 buffer: &Model<Buffer>,
13301 position: text::Anchor,
13302 kind: GotoDefinitionKind,
13303 cx: &mut AppContext,
13304 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13305 Some(self.update(cx, |project, cx| match kind {
13306 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13307 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13308 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13309 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13310 }))
13311 }
13312
13313 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13314 // TODO: make this work for remote projects
13315 self.read(cx)
13316 .language_servers_for_buffer(buffer.read(cx), cx)
13317 .any(
13318 |(_, server)| match server.capabilities().inlay_hint_provider {
13319 Some(lsp::OneOf::Left(enabled)) => enabled,
13320 Some(lsp::OneOf::Right(_)) => true,
13321 None => false,
13322 },
13323 )
13324 }
13325
13326 fn inlay_hints(
13327 &self,
13328 buffer_handle: Model<Buffer>,
13329 range: Range<text::Anchor>,
13330 cx: &mut AppContext,
13331 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13332 Some(self.update(cx, |project, cx| {
13333 project.inlay_hints(buffer_handle, range, cx)
13334 }))
13335 }
13336
13337 fn resolve_inlay_hint(
13338 &self,
13339 hint: InlayHint,
13340 buffer_handle: Model<Buffer>,
13341 server_id: LanguageServerId,
13342 cx: &mut AppContext,
13343 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13344 Some(self.update(cx, |project, cx| {
13345 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13346 }))
13347 }
13348
13349 fn range_for_rename(
13350 &self,
13351 buffer: &Model<Buffer>,
13352 position: text::Anchor,
13353 cx: &mut AppContext,
13354 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13355 Some(self.update(cx, |project, cx| {
13356 project.prepare_rename(buffer.clone(), position, cx)
13357 }))
13358 }
13359
13360 fn perform_rename(
13361 &self,
13362 buffer: &Model<Buffer>,
13363 position: text::Anchor,
13364 new_name: String,
13365 cx: &mut AppContext,
13366 ) -> Option<Task<Result<ProjectTransaction>>> {
13367 Some(self.update(cx, |project, cx| {
13368 project.perform_rename(buffer.clone(), position, new_name, cx)
13369 }))
13370 }
13371}
13372
13373fn inlay_hint_settings(
13374 location: Anchor,
13375 snapshot: &MultiBufferSnapshot,
13376 cx: &mut ViewContext<'_, Editor>,
13377) -> InlayHintSettings {
13378 let file = snapshot.file_at(location);
13379 let language = snapshot.language_at(location).map(|l| l.name());
13380 language_settings(language, file, cx).inlay_hints
13381}
13382
13383fn consume_contiguous_rows(
13384 contiguous_row_selections: &mut Vec<Selection<Point>>,
13385 selection: &Selection<Point>,
13386 display_map: &DisplaySnapshot,
13387 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13388) -> (MultiBufferRow, MultiBufferRow) {
13389 contiguous_row_selections.push(selection.clone());
13390 let start_row = MultiBufferRow(selection.start.row);
13391 let mut end_row = ending_row(selection, display_map);
13392
13393 while let Some(next_selection) = selections.peek() {
13394 if next_selection.start.row <= end_row.0 {
13395 end_row = ending_row(next_selection, display_map);
13396 contiguous_row_selections.push(selections.next().unwrap().clone());
13397 } else {
13398 break;
13399 }
13400 }
13401 (start_row, end_row)
13402}
13403
13404fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13405 if next_selection.end.column > 0 || next_selection.is_empty() {
13406 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13407 } else {
13408 MultiBufferRow(next_selection.end.row)
13409 }
13410}
13411
13412impl EditorSnapshot {
13413 pub fn remote_selections_in_range<'a>(
13414 &'a self,
13415 range: &'a Range<Anchor>,
13416 collaboration_hub: &dyn CollaborationHub,
13417 cx: &'a AppContext,
13418 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13419 let participant_names = collaboration_hub.user_names(cx);
13420 let participant_indices = collaboration_hub.user_participant_indices(cx);
13421 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13422 let collaborators_by_replica_id = collaborators_by_peer_id
13423 .iter()
13424 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13425 .collect::<HashMap<_, _>>();
13426 self.buffer_snapshot
13427 .selections_in_range(range, false)
13428 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13429 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13430 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13431 let user_name = participant_names.get(&collaborator.user_id).cloned();
13432 Some(RemoteSelection {
13433 replica_id,
13434 selection,
13435 cursor_shape,
13436 line_mode,
13437 participant_index,
13438 peer_id: collaborator.peer_id,
13439 user_name,
13440 })
13441 })
13442 }
13443
13444 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13445 self.display_snapshot.buffer_snapshot.language_at(position)
13446 }
13447
13448 pub fn is_focused(&self) -> bool {
13449 self.is_focused
13450 }
13451
13452 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13453 self.placeholder_text.as_ref()
13454 }
13455
13456 pub fn scroll_position(&self) -> gpui::Point<f32> {
13457 self.scroll_anchor.scroll_position(&self.display_snapshot)
13458 }
13459
13460 fn gutter_dimensions(
13461 &self,
13462 font_id: FontId,
13463 font_size: Pixels,
13464 em_width: Pixels,
13465 em_advance: Pixels,
13466 max_line_number_width: Pixels,
13467 cx: &AppContext,
13468 ) -> GutterDimensions {
13469 if !self.show_gutter {
13470 return GutterDimensions::default();
13471 }
13472 let descent = cx.text_system().descent(font_id, font_size);
13473
13474 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13475 matches!(
13476 ProjectSettings::get_global(cx).git.git_gutter,
13477 Some(GitGutterSetting::TrackedFiles)
13478 )
13479 });
13480 let gutter_settings = EditorSettings::get_global(cx).gutter;
13481 let show_line_numbers = self
13482 .show_line_numbers
13483 .unwrap_or(gutter_settings.line_numbers);
13484 let line_gutter_width = if show_line_numbers {
13485 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13486 let min_width_for_number_on_gutter = em_advance * 4.0;
13487 max_line_number_width.max(min_width_for_number_on_gutter)
13488 } else {
13489 0.0.into()
13490 };
13491
13492 let show_code_actions = self
13493 .show_code_actions
13494 .unwrap_or(gutter_settings.code_actions);
13495
13496 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13497
13498 let git_blame_entries_width =
13499 self.git_blame_gutter_max_author_length
13500 .map(|max_author_length| {
13501 // Length of the author name, but also space for the commit hash,
13502 // the spacing and the timestamp.
13503 let max_char_count = max_author_length
13504 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13505 + 7 // length of commit sha
13506 + 14 // length of max relative timestamp ("60 minutes ago")
13507 + 4; // gaps and margins
13508
13509 em_advance * max_char_count
13510 });
13511
13512 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13513 left_padding += if show_code_actions || show_runnables {
13514 em_width * 3.0
13515 } else if show_git_gutter && show_line_numbers {
13516 em_width * 2.0
13517 } else if show_git_gutter || show_line_numbers {
13518 em_width
13519 } else {
13520 px(0.)
13521 };
13522
13523 let right_padding = if gutter_settings.folds && show_line_numbers {
13524 em_width * 4.0
13525 } else if gutter_settings.folds {
13526 em_width * 3.0
13527 } else if show_line_numbers {
13528 em_width
13529 } else {
13530 px(0.)
13531 };
13532
13533 GutterDimensions {
13534 left_padding,
13535 right_padding,
13536 width: line_gutter_width + left_padding + right_padding,
13537 margin: -descent,
13538 git_blame_entries_width,
13539 }
13540 }
13541
13542 pub fn render_fold_toggle(
13543 &self,
13544 buffer_row: MultiBufferRow,
13545 row_contains_cursor: bool,
13546 editor: View<Editor>,
13547 cx: &mut WindowContext,
13548 ) -> Option<AnyElement> {
13549 let folded = self.is_line_folded(buffer_row);
13550
13551 if let Some(crease) = self
13552 .crease_snapshot
13553 .query_row(buffer_row, &self.buffer_snapshot)
13554 {
13555 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13556 if folded {
13557 editor.update(cx, |editor, cx| {
13558 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13559 });
13560 } else {
13561 editor.update(cx, |editor, cx| {
13562 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13563 });
13564 }
13565 });
13566
13567 Some((crease.render_toggle)(
13568 buffer_row,
13569 folded,
13570 toggle_callback,
13571 cx,
13572 ))
13573 } else if folded
13574 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13575 {
13576 Some(
13577 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13578 .selected(folded)
13579 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13580 if folded {
13581 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13582 } else {
13583 this.fold_at(&FoldAt { buffer_row }, cx);
13584 }
13585 }))
13586 .into_any_element(),
13587 )
13588 } else {
13589 None
13590 }
13591 }
13592
13593 pub fn render_crease_trailer(
13594 &self,
13595 buffer_row: MultiBufferRow,
13596 cx: &mut WindowContext,
13597 ) -> Option<AnyElement> {
13598 let folded = self.is_line_folded(buffer_row);
13599 let crease = self
13600 .crease_snapshot
13601 .query_row(buffer_row, &self.buffer_snapshot)?;
13602 Some((crease.render_trailer)(buffer_row, folded, cx))
13603 }
13604}
13605
13606impl Deref for EditorSnapshot {
13607 type Target = DisplaySnapshot;
13608
13609 fn deref(&self) -> &Self::Target {
13610 &self.display_snapshot
13611 }
13612}
13613
13614#[derive(Clone, Debug, PartialEq, Eq)]
13615pub enum EditorEvent {
13616 InputIgnored {
13617 text: Arc<str>,
13618 },
13619 InputHandled {
13620 utf16_range_to_replace: Option<Range<isize>>,
13621 text: Arc<str>,
13622 },
13623 ExcerptsAdded {
13624 buffer: Model<Buffer>,
13625 predecessor: ExcerptId,
13626 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13627 },
13628 ExcerptsRemoved {
13629 ids: Vec<ExcerptId>,
13630 },
13631 ExcerptsEdited {
13632 ids: Vec<ExcerptId>,
13633 },
13634 ExcerptsExpanded {
13635 ids: Vec<ExcerptId>,
13636 },
13637 BufferEdited,
13638 Edited {
13639 transaction_id: clock::Lamport,
13640 },
13641 Reparsed(BufferId),
13642 Focused,
13643 FocusedIn,
13644 Blurred,
13645 DirtyChanged,
13646 Saved,
13647 TitleChanged,
13648 DiffBaseChanged,
13649 SelectionsChanged {
13650 local: bool,
13651 },
13652 ScrollPositionChanged {
13653 local: bool,
13654 autoscroll: bool,
13655 },
13656 Closed,
13657 TransactionUndone {
13658 transaction_id: clock::Lamport,
13659 },
13660 TransactionBegun {
13661 transaction_id: clock::Lamport,
13662 },
13663 Reloaded,
13664 CursorShapeChanged,
13665}
13666
13667impl EventEmitter<EditorEvent> for Editor {}
13668
13669impl FocusableView for Editor {
13670 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13671 self.focus_handle.clone()
13672 }
13673}
13674
13675impl Render for Editor {
13676 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13677 let settings = ThemeSettings::get_global(cx);
13678
13679 let text_style = match self.mode {
13680 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13681 color: cx.theme().colors().editor_foreground,
13682 font_family: settings.ui_font.family.clone(),
13683 font_features: settings.ui_font.features.clone(),
13684 font_fallbacks: settings.ui_font.fallbacks.clone(),
13685 font_size: rems(0.875).into(),
13686 font_weight: settings.ui_font.weight,
13687 line_height: relative(settings.buffer_line_height.value()),
13688 ..Default::default()
13689 },
13690 EditorMode::Full => TextStyle {
13691 color: cx.theme().colors().editor_foreground,
13692 font_family: settings.buffer_font.family.clone(),
13693 font_features: settings.buffer_font.features.clone(),
13694 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13695 font_size: settings.buffer_font_size(cx).into(),
13696 font_weight: settings.buffer_font.weight,
13697 line_height: relative(settings.buffer_line_height.value()),
13698 ..Default::default()
13699 },
13700 };
13701
13702 let background = match self.mode {
13703 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13704 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13705 EditorMode::Full => cx.theme().colors().editor_background,
13706 };
13707
13708 EditorElement::new(
13709 cx.view(),
13710 EditorStyle {
13711 background,
13712 local_player: cx.theme().players().local(),
13713 text: text_style,
13714 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13715 syntax: cx.theme().syntax().clone(),
13716 status: cx.theme().status().clone(),
13717 inlay_hints_style: make_inlay_hints_style(cx),
13718 suggestions_style: HighlightStyle {
13719 color: Some(cx.theme().status().predictive),
13720 ..HighlightStyle::default()
13721 },
13722 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13723 },
13724 )
13725 }
13726}
13727
13728impl ViewInputHandler for Editor {
13729 fn text_for_range(
13730 &mut self,
13731 range_utf16: Range<usize>,
13732 cx: &mut ViewContext<Self>,
13733 ) -> Option<String> {
13734 Some(
13735 self.buffer
13736 .read(cx)
13737 .read(cx)
13738 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13739 .collect(),
13740 )
13741 }
13742
13743 fn selected_text_range(
13744 &mut self,
13745 ignore_disabled_input: bool,
13746 cx: &mut ViewContext<Self>,
13747 ) -> Option<UTF16Selection> {
13748 // Prevent the IME menu from appearing when holding down an alphabetic key
13749 // while input is disabled.
13750 if !ignore_disabled_input && !self.input_enabled {
13751 return None;
13752 }
13753
13754 let selection = self.selections.newest::<OffsetUtf16>(cx);
13755 let range = selection.range();
13756
13757 Some(UTF16Selection {
13758 range: range.start.0..range.end.0,
13759 reversed: selection.reversed,
13760 })
13761 }
13762
13763 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13764 let snapshot = self.buffer.read(cx).read(cx);
13765 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13766 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13767 }
13768
13769 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13770 self.clear_highlights::<InputComposition>(cx);
13771 self.ime_transaction.take();
13772 }
13773
13774 fn replace_text_in_range(
13775 &mut self,
13776 range_utf16: Option<Range<usize>>,
13777 text: &str,
13778 cx: &mut ViewContext<Self>,
13779 ) {
13780 if !self.input_enabled {
13781 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13782 return;
13783 }
13784
13785 self.transact(cx, |this, cx| {
13786 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13787 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13788 Some(this.selection_replacement_ranges(range_utf16, cx))
13789 } else {
13790 this.marked_text_ranges(cx)
13791 };
13792
13793 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13794 let newest_selection_id = this.selections.newest_anchor().id;
13795 this.selections
13796 .all::<OffsetUtf16>(cx)
13797 .iter()
13798 .zip(ranges_to_replace.iter())
13799 .find_map(|(selection, range)| {
13800 if selection.id == newest_selection_id {
13801 Some(
13802 (range.start.0 as isize - selection.head().0 as isize)
13803 ..(range.end.0 as isize - selection.head().0 as isize),
13804 )
13805 } else {
13806 None
13807 }
13808 })
13809 });
13810
13811 cx.emit(EditorEvent::InputHandled {
13812 utf16_range_to_replace: range_to_replace,
13813 text: text.into(),
13814 });
13815
13816 if let Some(new_selected_ranges) = new_selected_ranges {
13817 this.change_selections(None, cx, |selections| {
13818 selections.select_ranges(new_selected_ranges)
13819 });
13820 this.backspace(&Default::default(), cx);
13821 }
13822
13823 this.handle_input(text, cx);
13824 });
13825
13826 if let Some(transaction) = self.ime_transaction {
13827 self.buffer.update(cx, |buffer, cx| {
13828 buffer.group_until_transaction(transaction, cx);
13829 });
13830 }
13831
13832 self.unmark_text(cx);
13833 }
13834
13835 fn replace_and_mark_text_in_range(
13836 &mut self,
13837 range_utf16: Option<Range<usize>>,
13838 text: &str,
13839 new_selected_range_utf16: Option<Range<usize>>,
13840 cx: &mut ViewContext<Self>,
13841 ) {
13842 if !self.input_enabled {
13843 return;
13844 }
13845
13846 let transaction = self.transact(cx, |this, cx| {
13847 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13848 let snapshot = this.buffer.read(cx).read(cx);
13849 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13850 for marked_range in &mut marked_ranges {
13851 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13852 marked_range.start.0 += relative_range_utf16.start;
13853 marked_range.start =
13854 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13855 marked_range.end =
13856 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13857 }
13858 }
13859 Some(marked_ranges)
13860 } else if let Some(range_utf16) = range_utf16 {
13861 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13862 Some(this.selection_replacement_ranges(range_utf16, cx))
13863 } else {
13864 None
13865 };
13866
13867 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13868 let newest_selection_id = this.selections.newest_anchor().id;
13869 this.selections
13870 .all::<OffsetUtf16>(cx)
13871 .iter()
13872 .zip(ranges_to_replace.iter())
13873 .find_map(|(selection, range)| {
13874 if selection.id == newest_selection_id {
13875 Some(
13876 (range.start.0 as isize - selection.head().0 as isize)
13877 ..(range.end.0 as isize - selection.head().0 as isize),
13878 )
13879 } else {
13880 None
13881 }
13882 })
13883 });
13884
13885 cx.emit(EditorEvent::InputHandled {
13886 utf16_range_to_replace: range_to_replace,
13887 text: text.into(),
13888 });
13889
13890 if let Some(ranges) = ranges_to_replace {
13891 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13892 }
13893
13894 let marked_ranges = {
13895 let snapshot = this.buffer.read(cx).read(cx);
13896 this.selections
13897 .disjoint_anchors()
13898 .iter()
13899 .map(|selection| {
13900 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13901 })
13902 .collect::<Vec<_>>()
13903 };
13904
13905 if text.is_empty() {
13906 this.unmark_text(cx);
13907 } else {
13908 this.highlight_text::<InputComposition>(
13909 marked_ranges.clone(),
13910 HighlightStyle {
13911 underline: Some(UnderlineStyle {
13912 thickness: px(1.),
13913 color: None,
13914 wavy: false,
13915 }),
13916 ..Default::default()
13917 },
13918 cx,
13919 );
13920 }
13921
13922 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13923 let use_autoclose = this.use_autoclose;
13924 let use_auto_surround = this.use_auto_surround;
13925 this.set_use_autoclose(false);
13926 this.set_use_auto_surround(false);
13927 this.handle_input(text, cx);
13928 this.set_use_autoclose(use_autoclose);
13929 this.set_use_auto_surround(use_auto_surround);
13930
13931 if let Some(new_selected_range) = new_selected_range_utf16 {
13932 let snapshot = this.buffer.read(cx).read(cx);
13933 let new_selected_ranges = marked_ranges
13934 .into_iter()
13935 .map(|marked_range| {
13936 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13937 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13938 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13939 snapshot.clip_offset_utf16(new_start, Bias::Left)
13940 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13941 })
13942 .collect::<Vec<_>>();
13943
13944 drop(snapshot);
13945 this.change_selections(None, cx, |selections| {
13946 selections.select_ranges(new_selected_ranges)
13947 });
13948 }
13949 });
13950
13951 self.ime_transaction = self.ime_transaction.or(transaction);
13952 if let Some(transaction) = self.ime_transaction {
13953 self.buffer.update(cx, |buffer, cx| {
13954 buffer.group_until_transaction(transaction, cx);
13955 });
13956 }
13957
13958 if self.text_highlights::<InputComposition>(cx).is_none() {
13959 self.ime_transaction.take();
13960 }
13961 }
13962
13963 fn bounds_for_range(
13964 &mut self,
13965 range_utf16: Range<usize>,
13966 element_bounds: gpui::Bounds<Pixels>,
13967 cx: &mut ViewContext<Self>,
13968 ) -> Option<gpui::Bounds<Pixels>> {
13969 let text_layout_details = self.text_layout_details(cx);
13970 let style = &text_layout_details.editor_style;
13971 let font_id = cx.text_system().resolve_font(&style.text.font());
13972 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13973 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13974
13975 let em_width = cx
13976 .text_system()
13977 .typographic_bounds(font_id, font_size, 'm')
13978 .unwrap()
13979 .size
13980 .width;
13981
13982 let snapshot = self.snapshot(cx);
13983 let scroll_position = snapshot.scroll_position();
13984 let scroll_left = scroll_position.x * em_width;
13985
13986 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13987 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13988 + self.gutter_dimensions.width;
13989 let y = line_height * (start.row().as_f32() - scroll_position.y);
13990
13991 Some(Bounds {
13992 origin: element_bounds.origin + point(x, y),
13993 size: size(em_width, line_height),
13994 })
13995 }
13996}
13997
13998trait SelectionExt {
13999 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14000 fn spanned_rows(
14001 &self,
14002 include_end_if_at_line_start: bool,
14003 map: &DisplaySnapshot,
14004 ) -> Range<MultiBufferRow>;
14005}
14006
14007impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14008 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14009 let start = self
14010 .start
14011 .to_point(&map.buffer_snapshot)
14012 .to_display_point(map);
14013 let end = self
14014 .end
14015 .to_point(&map.buffer_snapshot)
14016 .to_display_point(map);
14017 if self.reversed {
14018 end..start
14019 } else {
14020 start..end
14021 }
14022 }
14023
14024 fn spanned_rows(
14025 &self,
14026 include_end_if_at_line_start: bool,
14027 map: &DisplaySnapshot,
14028 ) -> Range<MultiBufferRow> {
14029 let start = self.start.to_point(&map.buffer_snapshot);
14030 let mut end = self.end.to_point(&map.buffer_snapshot);
14031 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14032 end.row -= 1;
14033 }
14034
14035 let buffer_start = map.prev_line_boundary(start).0;
14036 let buffer_end = map.next_line_boundary(end).0;
14037 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14038 }
14039}
14040
14041impl<T: InvalidationRegion> InvalidationStack<T> {
14042 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14043 where
14044 S: Clone + ToOffset,
14045 {
14046 while let Some(region) = self.last() {
14047 let all_selections_inside_invalidation_ranges =
14048 if selections.len() == region.ranges().len() {
14049 selections
14050 .iter()
14051 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14052 .all(|(selection, invalidation_range)| {
14053 let head = selection.head().to_offset(buffer);
14054 invalidation_range.start <= head && invalidation_range.end >= head
14055 })
14056 } else {
14057 false
14058 };
14059
14060 if all_selections_inside_invalidation_ranges {
14061 break;
14062 } else {
14063 self.pop();
14064 }
14065 }
14066 }
14067}
14068
14069impl<T> Default for InvalidationStack<T> {
14070 fn default() -> Self {
14071 Self(Default::default())
14072 }
14073}
14074
14075impl<T> Deref for InvalidationStack<T> {
14076 type Target = Vec<T>;
14077
14078 fn deref(&self) -> &Self::Target {
14079 &self.0
14080 }
14081}
14082
14083impl<T> DerefMut for InvalidationStack<T> {
14084 fn deref_mut(&mut self) -> &mut Self::Target {
14085 &mut self.0
14086 }
14087}
14088
14089impl InvalidationRegion for SnippetState {
14090 fn ranges(&self) -> &[Range<Anchor>] {
14091 &self.ranges[self.active_index]
14092 }
14093}
14094
14095pub fn diagnostic_block_renderer(
14096 diagnostic: Diagnostic,
14097 max_message_rows: Option<u8>,
14098 allow_closing: bool,
14099 _is_valid: bool,
14100) -> RenderBlock {
14101 let (text_without_backticks, code_ranges) =
14102 highlight_diagnostic_message(&diagnostic, max_message_rows);
14103
14104 Box::new(move |cx: &mut BlockContext| {
14105 let group_id: SharedString = cx.block_id.to_string().into();
14106
14107 let mut text_style = cx.text_style().clone();
14108 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14109 let theme_settings = ThemeSettings::get_global(cx);
14110 text_style.font_family = theme_settings.buffer_font.family.clone();
14111 text_style.font_style = theme_settings.buffer_font.style;
14112 text_style.font_features = theme_settings.buffer_font.features.clone();
14113 text_style.font_weight = theme_settings.buffer_font.weight;
14114
14115 let multi_line_diagnostic = diagnostic.message.contains('\n');
14116
14117 let buttons = |diagnostic: &Diagnostic| {
14118 if multi_line_diagnostic {
14119 v_flex()
14120 } else {
14121 h_flex()
14122 }
14123 .when(allow_closing, |div| {
14124 div.children(diagnostic.is_primary.then(|| {
14125 IconButton::new("close-block", IconName::XCircle)
14126 .icon_color(Color::Muted)
14127 .size(ButtonSize::Compact)
14128 .style(ButtonStyle::Transparent)
14129 .visible_on_hover(group_id.clone())
14130 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14131 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14132 }))
14133 })
14134 .child(
14135 IconButton::new("copy-block", IconName::Copy)
14136 .icon_color(Color::Muted)
14137 .size(ButtonSize::Compact)
14138 .style(ButtonStyle::Transparent)
14139 .visible_on_hover(group_id.clone())
14140 .on_click({
14141 let message = diagnostic.message.clone();
14142 move |_click, cx| {
14143 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14144 }
14145 })
14146 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14147 )
14148 };
14149
14150 let icon_size = buttons(&diagnostic)
14151 .into_any_element()
14152 .layout_as_root(AvailableSpace::min_size(), cx);
14153
14154 h_flex()
14155 .id(cx.block_id)
14156 .group(group_id.clone())
14157 .relative()
14158 .size_full()
14159 .pl(cx.gutter_dimensions.width)
14160 .w(cx.max_width + cx.gutter_dimensions.width)
14161 .child(
14162 div()
14163 .flex()
14164 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14165 .flex_shrink(),
14166 )
14167 .child(buttons(&diagnostic))
14168 .child(div().flex().flex_shrink_0().child(
14169 StyledText::new(text_without_backticks.clone()).with_highlights(
14170 &text_style,
14171 code_ranges.iter().map(|range| {
14172 (
14173 range.clone(),
14174 HighlightStyle {
14175 font_weight: Some(FontWeight::BOLD),
14176 ..Default::default()
14177 },
14178 )
14179 }),
14180 ),
14181 ))
14182 .into_any_element()
14183 })
14184}
14185
14186pub fn highlight_diagnostic_message(
14187 diagnostic: &Diagnostic,
14188 mut max_message_rows: Option<u8>,
14189) -> (SharedString, Vec<Range<usize>>) {
14190 let mut text_without_backticks = String::new();
14191 let mut code_ranges = Vec::new();
14192
14193 if let Some(source) = &diagnostic.source {
14194 text_without_backticks.push_str(source);
14195 code_ranges.push(0..source.len());
14196 text_without_backticks.push_str(": ");
14197 }
14198
14199 let mut prev_offset = 0;
14200 let mut in_code_block = false;
14201 let has_row_limit = max_message_rows.is_some();
14202 let mut newline_indices = diagnostic
14203 .message
14204 .match_indices('\n')
14205 .filter(|_| has_row_limit)
14206 .map(|(ix, _)| ix)
14207 .fuse()
14208 .peekable();
14209
14210 for (quote_ix, _) in diagnostic
14211 .message
14212 .match_indices('`')
14213 .chain([(diagnostic.message.len(), "")])
14214 {
14215 let mut first_newline_ix = None;
14216 let mut last_newline_ix = None;
14217 while let Some(newline_ix) = newline_indices.peek() {
14218 if *newline_ix < quote_ix {
14219 if first_newline_ix.is_none() {
14220 first_newline_ix = Some(*newline_ix);
14221 }
14222 last_newline_ix = Some(*newline_ix);
14223
14224 if let Some(rows_left) = &mut max_message_rows {
14225 if *rows_left == 0 {
14226 break;
14227 } else {
14228 *rows_left -= 1;
14229 }
14230 }
14231 let _ = newline_indices.next();
14232 } else {
14233 break;
14234 }
14235 }
14236 let prev_len = text_without_backticks.len();
14237 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14238 text_without_backticks.push_str(new_text);
14239 if in_code_block {
14240 code_ranges.push(prev_len..text_without_backticks.len());
14241 }
14242 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14243 in_code_block = !in_code_block;
14244 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14245 text_without_backticks.push_str("...");
14246 break;
14247 }
14248 }
14249
14250 (text_without_backticks.into(), code_ranges)
14251}
14252
14253fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14254 match severity {
14255 DiagnosticSeverity::ERROR => colors.error,
14256 DiagnosticSeverity::WARNING => colors.warning,
14257 DiagnosticSeverity::INFORMATION => colors.info,
14258 DiagnosticSeverity::HINT => colors.info,
14259 _ => colors.ignored,
14260 }
14261}
14262
14263pub fn styled_runs_for_code_label<'a>(
14264 label: &'a CodeLabel,
14265 syntax_theme: &'a theme::SyntaxTheme,
14266) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14267 let fade_out = HighlightStyle {
14268 fade_out: Some(0.35),
14269 ..Default::default()
14270 };
14271
14272 let mut prev_end = label.filter_range.end;
14273 label
14274 .runs
14275 .iter()
14276 .enumerate()
14277 .flat_map(move |(ix, (range, highlight_id))| {
14278 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14279 style
14280 } else {
14281 return Default::default();
14282 };
14283 let mut muted_style = style;
14284 muted_style.highlight(fade_out);
14285
14286 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14287 if range.start >= label.filter_range.end {
14288 if range.start > prev_end {
14289 runs.push((prev_end..range.start, fade_out));
14290 }
14291 runs.push((range.clone(), muted_style));
14292 } else if range.end <= label.filter_range.end {
14293 runs.push((range.clone(), style));
14294 } else {
14295 runs.push((range.start..label.filter_range.end, style));
14296 runs.push((label.filter_range.end..range.end, muted_style));
14297 }
14298 prev_end = cmp::max(prev_end, range.end);
14299
14300 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14301 runs.push((prev_end..label.text.len(), fade_out));
14302 }
14303
14304 runs
14305 })
14306}
14307
14308pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14309 let mut prev_index = 0;
14310 let mut prev_codepoint: Option<char> = None;
14311 text.char_indices()
14312 .chain([(text.len(), '\0')])
14313 .filter_map(move |(index, codepoint)| {
14314 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14315 let is_boundary = index == text.len()
14316 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14317 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14318 if is_boundary {
14319 let chunk = &text[prev_index..index];
14320 prev_index = index;
14321 Some(chunk)
14322 } else {
14323 None
14324 }
14325 })
14326}
14327
14328pub trait RangeToAnchorExt: Sized {
14329 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14330
14331 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14332 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14333 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14334 }
14335}
14336
14337impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14338 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14339 let start_offset = self.start.to_offset(snapshot);
14340 let end_offset = self.end.to_offset(snapshot);
14341 if start_offset == end_offset {
14342 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14343 } else {
14344 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14345 }
14346 }
14347}
14348
14349pub trait RowExt {
14350 fn as_f32(&self) -> f32;
14351
14352 fn next_row(&self) -> Self;
14353
14354 fn previous_row(&self) -> Self;
14355
14356 fn minus(&self, other: Self) -> u32;
14357}
14358
14359impl RowExt for DisplayRow {
14360 fn as_f32(&self) -> f32 {
14361 self.0 as f32
14362 }
14363
14364 fn next_row(&self) -> Self {
14365 Self(self.0 + 1)
14366 }
14367
14368 fn previous_row(&self) -> Self {
14369 Self(self.0.saturating_sub(1))
14370 }
14371
14372 fn minus(&self, other: Self) -> u32 {
14373 self.0 - other.0
14374 }
14375}
14376
14377impl RowExt for MultiBufferRow {
14378 fn as_f32(&self) -> f32 {
14379 self.0 as f32
14380 }
14381
14382 fn next_row(&self) -> Self {
14383 Self(self.0 + 1)
14384 }
14385
14386 fn previous_row(&self) -> Self {
14387 Self(self.0.saturating_sub(1))
14388 }
14389
14390 fn minus(&self, other: Self) -> u32 {
14391 self.0 - other.0
14392 }
14393}
14394
14395trait RowRangeExt {
14396 type Row;
14397
14398 fn len(&self) -> usize;
14399
14400 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14401}
14402
14403impl RowRangeExt for Range<MultiBufferRow> {
14404 type Row = MultiBufferRow;
14405
14406 fn len(&self) -> usize {
14407 (self.end.0 - self.start.0) as usize
14408 }
14409
14410 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14411 (self.start.0..self.end.0).map(MultiBufferRow)
14412 }
14413}
14414
14415impl RowRangeExt for Range<DisplayRow> {
14416 type Row = DisplayRow;
14417
14418 fn len(&self) -> usize {
14419 (self.end.0 - self.start.0) as usize
14420 }
14421
14422 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14423 (self.start.0..self.end.0).map(DisplayRow)
14424 }
14425}
14426
14427fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14428 if hunk.diff_base_byte_range.is_empty() {
14429 DiffHunkStatus::Added
14430 } else if hunk.row_range.is_empty() {
14431 DiffHunkStatus::Removed
14432 } else {
14433 DiffHunkStatus::Modified
14434 }
14435}
14436
14437/// If select range has more than one line, we
14438/// just point the cursor to range.start.
14439fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14440 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14441 range
14442 } else {
14443 range.start..range.start
14444 }
14445}