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, 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 = all_language_settings(None, cx)
432 .language(None)
433 .inlay_hints
434 .show_background;
435
436 HighlightStyle {
437 color: Some(cx.theme().status().hint),
438 background_color: show_background.then(|| cx.theme().status().hint_background),
439 ..HighlightStyle::default()
440 }
441}
442
443type CompletionId = usize;
444
445#[derive(Clone, Debug)]
446struct CompletionState {
447 // render_inlay_ids represents the inlay hints that are inserted
448 // for rendering the inline completions. They may be discontinuous
449 // in the event that the completion provider returns some intersection
450 // with the existing content.
451 render_inlay_ids: Vec<InlayId>,
452 // text is the resulting rope that is inserted when the user accepts a completion.
453 text: Rope,
454 // position is the position of the cursor when the completion was triggered.
455 position: multi_buffer::Anchor,
456 // delete_range is the range of text that this completion state covers.
457 // if the completion is accepted, this range should be deleted.
458 delete_range: Option<Range<multi_buffer::Anchor>>,
459}
460
461#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
462struct EditorActionId(usize);
463
464impl EditorActionId {
465 pub fn post_inc(&mut self) -> Self {
466 let answer = self.0;
467
468 *self = Self(answer + 1);
469
470 Self(answer)
471 }
472}
473
474// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
475// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
476
477type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
478type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
479
480#[derive(Default)]
481struct ScrollbarMarkerState {
482 scrollbar_size: Size<Pixels>,
483 dirty: bool,
484 markers: Arc<[PaintQuad]>,
485 pending_refresh: Option<Task<Result<()>>>,
486}
487
488impl ScrollbarMarkerState {
489 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
490 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
491 }
492}
493
494#[derive(Clone, Debug)]
495struct RunnableTasks {
496 templates: Vec<(TaskSourceKind, TaskTemplate)>,
497 offset: MultiBufferOffset,
498 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
499 column: u32,
500 // Values of all named captures, including those starting with '_'
501 extra_variables: HashMap<String, String>,
502 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
503 context_range: Range<BufferOffset>,
504}
505
506#[derive(Clone)]
507struct ResolvedTasks {
508 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
509 position: Anchor,
510}
511#[derive(Copy, Clone, Debug)]
512struct MultiBufferOffset(usize);
513#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
514struct BufferOffset(usize);
515
516// Addons allow storing per-editor state in other crates (e.g. Vim)
517pub trait Addon: 'static {
518 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
519
520 fn to_any(&self) -> &dyn std::any::Any;
521}
522
523/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
524///
525/// See the [module level documentation](self) for more information.
526pub struct Editor {
527 focus_handle: FocusHandle,
528 last_focused_descendant: Option<WeakFocusHandle>,
529 /// The text buffer being edited
530 buffer: Model<MultiBuffer>,
531 /// Map of how text in the buffer should be displayed.
532 /// Handles soft wraps, folds, fake inlay text insertions, etc.
533 pub display_map: Model<DisplayMap>,
534 pub selections: SelectionsCollection,
535 pub scroll_manager: ScrollManager,
536 /// When inline assist editors are linked, they all render cursors because
537 /// typing enters text into each of them, even the ones that aren't focused.
538 pub(crate) show_cursor_when_unfocused: bool,
539 columnar_selection_tail: Option<Anchor>,
540 add_selections_state: Option<AddSelectionsState>,
541 select_next_state: Option<SelectNextState>,
542 select_prev_state: Option<SelectNextState>,
543 selection_history: SelectionHistory,
544 autoclose_regions: Vec<AutocloseRegion>,
545 snippet_stack: InvalidationStack<SnippetState>,
546 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
547 ime_transaction: Option<TransactionId>,
548 active_diagnostics: Option<ActiveDiagnosticGroup>,
549 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
550 project: Option<Model<Project>>,
551 semantics_provider: Option<Rc<dyn SemanticsProvider>>,
552 completion_provider: Option<Box<dyn CompletionProvider>>,
553 collaboration_hub: Option<Box<dyn CollaborationHub>>,
554 blink_manager: Model<BlinkManager>,
555 show_cursor_names: bool,
556 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
557 pub show_local_selections: bool,
558 mode: EditorMode,
559 show_breadcrumbs: bool,
560 show_gutter: bool,
561 show_line_numbers: Option<bool>,
562 use_relative_line_numbers: Option<bool>,
563 show_git_diff_gutter: Option<bool>,
564 show_code_actions: Option<bool>,
565 show_runnables: Option<bool>,
566 show_wrap_guides: Option<bool>,
567 show_indent_guides: Option<bool>,
568 placeholder_text: Option<Arc<str>>,
569 highlight_order: usize,
570 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
571 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
572 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
573 scrollbar_marker_state: ScrollbarMarkerState,
574 active_indent_guides_state: ActiveIndentGuidesState,
575 nav_history: Option<ItemNavHistory>,
576 context_menu: RwLock<Option<ContextMenu>>,
577 mouse_context_menu: Option<MouseContextMenu>,
578 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
579 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
580 signature_help_state: SignatureHelpState,
581 auto_signature_help: Option<bool>,
582 find_all_references_task_sources: Vec<Anchor>,
583 next_completion_id: CompletionId,
584 completion_documentation_pre_resolve_debounce: DebouncedDelay,
585 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
586 code_actions_task: Option<Task<Result<()>>>,
587 document_highlights_task: Option<Task<()>>,
588 linked_editing_range_task: Option<Task<Option<()>>>,
589 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
590 pending_rename: Option<RenameState>,
591 searchable: bool,
592 cursor_shape: CursorShape,
593 current_line_highlight: Option<CurrentLineHighlight>,
594 collapse_matches: bool,
595 autoindent_mode: Option<AutoindentMode>,
596 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
597 input_enabled: bool,
598 use_modal_editing: bool,
599 read_only: bool,
600 leader_peer_id: Option<PeerId>,
601 remote_id: Option<ViewId>,
602 hover_state: HoverState,
603 gutter_hovered: bool,
604 hovered_link_state: Option<HoveredLinkState>,
605 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
606 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
607 active_inline_completion: Option<CompletionState>,
608 // enable_inline_completions is a switch that Vim can use to disable
609 // inline completions based on its mode.
610 enable_inline_completions: bool,
611 show_inline_completions_override: Option<bool>,
612 inlay_hint_cache: InlayHintCache,
613 expanded_hunks: ExpandedHunks,
614 next_inlay_id: usize,
615 _subscriptions: Vec<Subscription>,
616 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
617 gutter_dimensions: GutterDimensions,
618 style: Option<EditorStyle>,
619 next_editor_action_id: EditorActionId,
620 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
621 use_autoclose: bool,
622 use_auto_surround: bool,
623 auto_replace_emoji_shortcode: bool,
624 show_git_blame_gutter: bool,
625 show_git_blame_inline: bool,
626 show_git_blame_inline_delay_task: Option<Task<()>>,
627 git_blame_inline_enabled: bool,
628 serialize_dirty_buffers: bool,
629 show_selection_menu: Option<bool>,
630 blame: Option<Model<GitBlame>>,
631 blame_subscription: Option<Subscription>,
632 custom_context_menu: Option<
633 Box<
634 dyn 'static
635 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
636 >,
637 >,
638 last_bounds: Option<Bounds<Pixels>>,
639 expect_bounds_change: Option<Bounds<Pixels>>,
640 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
641 tasks_update_task: Option<Task<()>>,
642 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
643 breadcrumb_header: Option<String>,
644 focused_block: Option<FocusedBlock>,
645 next_scroll_position: NextScrollCursorCenterTopBottom,
646 addons: HashMap<TypeId, Box<dyn Addon>>,
647 _scroll_cursor_center_top_bottom_task: Task<()>,
648}
649
650#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
651enum NextScrollCursorCenterTopBottom {
652 #[default]
653 Center,
654 Top,
655 Bottom,
656}
657
658impl NextScrollCursorCenterTopBottom {
659 fn next(&self) -> Self {
660 match self {
661 Self::Center => Self::Top,
662 Self::Top => Self::Bottom,
663 Self::Bottom => Self::Center,
664 }
665 }
666}
667
668#[derive(Clone)]
669pub struct EditorSnapshot {
670 pub mode: EditorMode,
671 show_gutter: bool,
672 show_line_numbers: Option<bool>,
673 show_git_diff_gutter: Option<bool>,
674 show_code_actions: Option<bool>,
675 show_runnables: Option<bool>,
676 git_blame_gutter_max_author_length: Option<usize>,
677 pub display_snapshot: DisplaySnapshot,
678 pub placeholder_text: Option<Arc<str>>,
679 is_focused: bool,
680 scroll_anchor: ScrollAnchor,
681 ongoing_scroll: OngoingScroll,
682 current_line_highlight: CurrentLineHighlight,
683 gutter_hovered: bool,
684}
685
686const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
687
688#[derive(Default, Debug, Clone, Copy)]
689pub struct GutterDimensions {
690 pub left_padding: Pixels,
691 pub right_padding: Pixels,
692 pub width: Pixels,
693 pub margin: Pixels,
694 pub git_blame_entries_width: Option<Pixels>,
695}
696
697impl GutterDimensions {
698 /// The full width of the space taken up by the gutter.
699 pub fn full_width(&self) -> Pixels {
700 self.margin + self.width
701 }
702
703 /// The width of the space reserved for the fold indicators,
704 /// use alongside 'justify_end' and `gutter_width` to
705 /// right align content with the line numbers
706 pub fn fold_area_width(&self) -> Pixels {
707 self.margin + self.right_padding
708 }
709}
710
711#[derive(Debug)]
712pub struct RemoteSelection {
713 pub replica_id: ReplicaId,
714 pub selection: Selection<Anchor>,
715 pub cursor_shape: CursorShape,
716 pub peer_id: PeerId,
717 pub line_mode: bool,
718 pub participant_index: Option<ParticipantIndex>,
719 pub user_name: Option<SharedString>,
720}
721
722#[derive(Clone, Debug)]
723struct SelectionHistoryEntry {
724 selections: Arc<[Selection<Anchor>]>,
725 select_next_state: Option<SelectNextState>,
726 select_prev_state: Option<SelectNextState>,
727 add_selections_state: Option<AddSelectionsState>,
728}
729
730enum SelectionHistoryMode {
731 Normal,
732 Undoing,
733 Redoing,
734}
735
736#[derive(Clone, PartialEq, Eq, Hash)]
737struct HoveredCursor {
738 replica_id: u16,
739 selection_id: usize,
740}
741
742impl Default for SelectionHistoryMode {
743 fn default() -> Self {
744 Self::Normal
745 }
746}
747
748#[derive(Default)]
749struct SelectionHistory {
750 #[allow(clippy::type_complexity)]
751 selections_by_transaction:
752 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
753 mode: SelectionHistoryMode,
754 undo_stack: VecDeque<SelectionHistoryEntry>,
755 redo_stack: VecDeque<SelectionHistoryEntry>,
756}
757
758impl SelectionHistory {
759 fn insert_transaction(
760 &mut self,
761 transaction_id: TransactionId,
762 selections: Arc<[Selection<Anchor>]>,
763 ) {
764 self.selections_by_transaction
765 .insert(transaction_id, (selections, None));
766 }
767
768 #[allow(clippy::type_complexity)]
769 fn transaction(
770 &self,
771 transaction_id: TransactionId,
772 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
773 self.selections_by_transaction.get(&transaction_id)
774 }
775
776 #[allow(clippy::type_complexity)]
777 fn transaction_mut(
778 &mut self,
779 transaction_id: TransactionId,
780 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
781 self.selections_by_transaction.get_mut(&transaction_id)
782 }
783
784 fn push(&mut self, entry: SelectionHistoryEntry) {
785 if !entry.selections.is_empty() {
786 match self.mode {
787 SelectionHistoryMode::Normal => {
788 self.push_undo(entry);
789 self.redo_stack.clear();
790 }
791 SelectionHistoryMode::Undoing => self.push_redo(entry),
792 SelectionHistoryMode::Redoing => self.push_undo(entry),
793 }
794 }
795 }
796
797 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
798 if self
799 .undo_stack
800 .back()
801 .map_or(true, |e| e.selections != entry.selections)
802 {
803 self.undo_stack.push_back(entry);
804 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
805 self.undo_stack.pop_front();
806 }
807 }
808 }
809
810 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
811 if self
812 .redo_stack
813 .back()
814 .map_or(true, |e| e.selections != entry.selections)
815 {
816 self.redo_stack.push_back(entry);
817 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
818 self.redo_stack.pop_front();
819 }
820 }
821 }
822}
823
824struct RowHighlight {
825 index: usize,
826 range: Range<Anchor>,
827 color: Hsla,
828 should_autoscroll: bool,
829}
830
831#[derive(Clone, Debug)]
832struct AddSelectionsState {
833 above: bool,
834 stack: Vec<usize>,
835}
836
837#[derive(Clone)]
838struct SelectNextState {
839 query: AhoCorasick,
840 wordwise: bool,
841 done: bool,
842}
843
844impl std::fmt::Debug for SelectNextState {
845 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
846 f.debug_struct(std::any::type_name::<Self>())
847 .field("wordwise", &self.wordwise)
848 .field("done", &self.done)
849 .finish()
850 }
851}
852
853#[derive(Debug)]
854struct AutocloseRegion {
855 selection_id: usize,
856 range: Range<Anchor>,
857 pair: BracketPair,
858}
859
860#[derive(Debug)]
861struct SnippetState {
862 ranges: Vec<Vec<Range<Anchor>>>,
863 active_index: usize,
864}
865
866#[doc(hidden)]
867pub struct RenameState {
868 pub range: Range<Anchor>,
869 pub old_name: Arc<str>,
870 pub editor: View<Editor>,
871 block_id: CustomBlockId,
872}
873
874struct InvalidationStack<T>(Vec<T>);
875
876struct RegisteredInlineCompletionProvider {
877 provider: Arc<dyn InlineCompletionProviderHandle>,
878 _subscription: Subscription,
879}
880
881enum ContextMenu {
882 Completions(CompletionsMenu),
883 CodeActions(CodeActionsMenu),
884}
885
886impl ContextMenu {
887 fn select_first(
888 &mut self,
889 provider: Option<&dyn CompletionProvider>,
890 cx: &mut ViewContext<Editor>,
891 ) -> bool {
892 if self.visible() {
893 match self {
894 ContextMenu::Completions(menu) => menu.select_first(provider, cx),
895 ContextMenu::CodeActions(menu) => menu.select_first(cx),
896 }
897 true
898 } else {
899 false
900 }
901 }
902
903 fn select_prev(
904 &mut self,
905 provider: Option<&dyn CompletionProvider>,
906 cx: &mut ViewContext<Editor>,
907 ) -> bool {
908 if self.visible() {
909 match self {
910 ContextMenu::Completions(menu) => menu.select_prev(provider, cx),
911 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
912 }
913 true
914 } else {
915 false
916 }
917 }
918
919 fn select_next(
920 &mut self,
921 provider: Option<&dyn CompletionProvider>,
922 cx: &mut ViewContext<Editor>,
923 ) -> bool {
924 if self.visible() {
925 match self {
926 ContextMenu::Completions(menu) => menu.select_next(provider, cx),
927 ContextMenu::CodeActions(menu) => menu.select_next(cx),
928 }
929 true
930 } else {
931 false
932 }
933 }
934
935 fn select_last(
936 &mut self,
937 provider: Option<&dyn CompletionProvider>,
938 cx: &mut ViewContext<Editor>,
939 ) -> bool {
940 if self.visible() {
941 match self {
942 ContextMenu::Completions(menu) => menu.select_last(provider, cx),
943 ContextMenu::CodeActions(menu) => menu.select_last(cx),
944 }
945 true
946 } else {
947 false
948 }
949 }
950
951 fn visible(&self) -> bool {
952 match self {
953 ContextMenu::Completions(menu) => menu.visible(),
954 ContextMenu::CodeActions(menu) => menu.visible(),
955 }
956 }
957
958 fn render(
959 &self,
960 cursor_position: DisplayPoint,
961 style: &EditorStyle,
962 max_height: Pixels,
963 workspace: Option<WeakView<Workspace>>,
964 cx: &mut ViewContext<Editor>,
965 ) -> (ContextMenuOrigin, AnyElement) {
966 match self {
967 ContextMenu::Completions(menu) => (
968 ContextMenuOrigin::EditorPoint(cursor_position),
969 menu.render(style, max_height, workspace, cx),
970 ),
971 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
972 }
973 }
974}
975
976enum ContextMenuOrigin {
977 EditorPoint(DisplayPoint),
978 GutterIndicator(DisplayRow),
979}
980
981#[derive(Clone)]
982struct CompletionsMenu {
983 id: CompletionId,
984 sort_completions: bool,
985 initial_position: Anchor,
986 buffer: Model<Buffer>,
987 completions: Arc<RwLock<Box<[Completion]>>>,
988 match_candidates: Arc<[StringMatchCandidate]>,
989 matches: Arc<[StringMatch]>,
990 selected_item: usize,
991 scroll_handle: UniformListScrollHandle,
992 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
993}
994
995impl CompletionsMenu {
996 fn select_first(
997 &mut self,
998 provider: Option<&dyn CompletionProvider>,
999 cx: &mut ViewContext<Editor>,
1000 ) {
1001 self.selected_item = 0;
1002 self.scroll_handle.scroll_to_item(self.selected_item);
1003 self.attempt_resolve_selected_completion_documentation(provider, cx);
1004 cx.notify();
1005 }
1006
1007 fn select_prev(
1008 &mut self,
1009 provider: Option<&dyn CompletionProvider>,
1010 cx: &mut ViewContext<Editor>,
1011 ) {
1012 if self.selected_item > 0 {
1013 self.selected_item -= 1;
1014 } else {
1015 self.selected_item = self.matches.len() - 1;
1016 }
1017 self.scroll_handle.scroll_to_item(self.selected_item);
1018 self.attempt_resolve_selected_completion_documentation(provider, cx);
1019 cx.notify();
1020 }
1021
1022 fn select_next(
1023 &mut self,
1024 provider: Option<&dyn CompletionProvider>,
1025 cx: &mut ViewContext<Editor>,
1026 ) {
1027 if self.selected_item + 1 < self.matches.len() {
1028 self.selected_item += 1;
1029 } else {
1030 self.selected_item = 0;
1031 }
1032 self.scroll_handle.scroll_to_item(self.selected_item);
1033 self.attempt_resolve_selected_completion_documentation(provider, cx);
1034 cx.notify();
1035 }
1036
1037 fn select_last(
1038 &mut self,
1039 provider: Option<&dyn CompletionProvider>,
1040 cx: &mut ViewContext<Editor>,
1041 ) {
1042 self.selected_item = self.matches.len() - 1;
1043 self.scroll_handle.scroll_to_item(self.selected_item);
1044 self.attempt_resolve_selected_completion_documentation(provider, cx);
1045 cx.notify();
1046 }
1047
1048 fn pre_resolve_completion_documentation(
1049 buffer: Model<Buffer>,
1050 completions: Arc<RwLock<Box<[Completion]>>>,
1051 matches: Arc<[StringMatch]>,
1052 editor: &Editor,
1053 cx: &mut ViewContext<Editor>,
1054 ) -> Task<()> {
1055 let settings = EditorSettings::get_global(cx);
1056 if !settings.show_completion_documentation {
1057 return Task::ready(());
1058 }
1059
1060 let Some(provider) = editor.completion_provider.as_ref() else {
1061 return Task::ready(());
1062 };
1063
1064 let resolve_task = provider.resolve_completions(
1065 buffer,
1066 matches.iter().map(|m| m.candidate_id).collect(),
1067 completions.clone(),
1068 cx,
1069 );
1070
1071 cx.spawn(move |this, mut cx| async move {
1072 if let Some(true) = resolve_task.await.log_err() {
1073 this.update(&mut cx, |_, cx| cx.notify()).ok();
1074 }
1075 })
1076 }
1077
1078 fn attempt_resolve_selected_completion_documentation(
1079 &mut self,
1080 provider: Option<&dyn CompletionProvider>,
1081 cx: &mut ViewContext<Editor>,
1082 ) {
1083 let settings = EditorSettings::get_global(cx);
1084 if !settings.show_completion_documentation {
1085 return;
1086 }
1087
1088 let completion_index = self.matches[self.selected_item].candidate_id;
1089 let Some(provider) = provider else {
1090 return;
1091 };
1092
1093 let resolve_task = provider.resolve_completions(
1094 self.buffer.clone(),
1095 vec![completion_index],
1096 self.completions.clone(),
1097 cx,
1098 );
1099
1100 let delay_ms =
1101 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1102 let delay = Duration::from_millis(delay_ms);
1103
1104 self.selected_completion_documentation_resolve_debounce
1105 .lock()
1106 .fire_new(delay, cx, |_, cx| {
1107 cx.spawn(move |this, mut cx| async move {
1108 if let Some(true) = resolve_task.await.log_err() {
1109 this.update(&mut cx, |_, cx| cx.notify()).ok();
1110 }
1111 })
1112 });
1113 }
1114
1115 fn visible(&self) -> bool {
1116 !self.matches.is_empty()
1117 }
1118
1119 fn render(
1120 &self,
1121 style: &EditorStyle,
1122 max_height: Pixels,
1123 workspace: Option<WeakView<Workspace>>,
1124 cx: &mut ViewContext<Editor>,
1125 ) -> AnyElement {
1126 let settings = EditorSettings::get_global(cx);
1127 let show_completion_documentation = settings.show_completion_documentation;
1128
1129 let widest_completion_ix = self
1130 .matches
1131 .iter()
1132 .enumerate()
1133 .max_by_key(|(_, mat)| {
1134 let completions = self.completions.read();
1135 let completion = &completions[mat.candidate_id];
1136 let documentation = &completion.documentation;
1137
1138 let mut len = completion.label.text.chars().count();
1139 if let Some(Documentation::SingleLine(text)) = documentation {
1140 if show_completion_documentation {
1141 len += text.chars().count();
1142 }
1143 }
1144
1145 len
1146 })
1147 .map(|(ix, _)| ix);
1148
1149 let completions = self.completions.clone();
1150 let matches = self.matches.clone();
1151 let selected_item = self.selected_item;
1152 let style = style.clone();
1153
1154 let multiline_docs = if show_completion_documentation {
1155 let mat = &self.matches[selected_item];
1156 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1157 Some(Documentation::MultiLinePlainText(text)) => {
1158 Some(div().child(SharedString::from(text.clone())))
1159 }
1160 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1161 Some(div().child(render_parsed_markdown(
1162 "completions_markdown",
1163 parsed,
1164 &style,
1165 workspace,
1166 cx,
1167 )))
1168 }
1169 _ => None,
1170 };
1171 multiline_docs.map(|div| {
1172 div.id("multiline_docs")
1173 .max_h(max_height)
1174 .flex_1()
1175 .px_1p5()
1176 .py_1()
1177 .min_w(px(260.))
1178 .max_w(px(640.))
1179 .w(px(500.))
1180 .overflow_y_scroll()
1181 .occlude()
1182 })
1183 } else {
1184 None
1185 };
1186
1187 let list = uniform_list(
1188 cx.view().clone(),
1189 "completions",
1190 matches.len(),
1191 move |_editor, range, cx| {
1192 let start_ix = range.start;
1193 let completions_guard = completions.read();
1194
1195 matches[range]
1196 .iter()
1197 .enumerate()
1198 .map(|(ix, mat)| {
1199 let item_ix = start_ix + ix;
1200 let candidate_id = mat.candidate_id;
1201 let completion = &completions_guard[candidate_id];
1202
1203 let documentation = if show_completion_documentation {
1204 &completion.documentation
1205 } else {
1206 &None
1207 };
1208
1209 let highlights = gpui::combine_highlights(
1210 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1211 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1212 |(range, mut highlight)| {
1213 // Ignore font weight for syntax highlighting, as we'll use it
1214 // for fuzzy matches.
1215 highlight.font_weight = None;
1216
1217 if completion.lsp_completion.deprecated.unwrap_or(false) {
1218 highlight.strikethrough = Some(StrikethroughStyle {
1219 thickness: 1.0.into(),
1220 ..Default::default()
1221 });
1222 highlight.color = Some(cx.theme().colors().text_muted);
1223 }
1224
1225 (range, highlight)
1226 },
1227 ),
1228 );
1229 let completion_label = StyledText::new(completion.label.text.clone())
1230 .with_highlights(&style.text, highlights);
1231 let documentation_label =
1232 if let Some(Documentation::SingleLine(text)) = documentation {
1233 if text.trim().is_empty() {
1234 None
1235 } else {
1236 Some(
1237 Label::new(text.clone())
1238 .ml_4()
1239 .size(LabelSize::Small)
1240 .color(Color::Muted),
1241 )
1242 }
1243 } else {
1244 None
1245 };
1246
1247 let color_swatch = completion
1248 .color()
1249 .map(|color| div().size_4().bg(color).rounded_sm());
1250
1251 div().min_w(px(220.)).max_w(px(540.)).child(
1252 ListItem::new(mat.candidate_id)
1253 .inset(true)
1254 .selected(item_ix == selected_item)
1255 .on_click(cx.listener(move |editor, _event, cx| {
1256 cx.stop_propagation();
1257 if let Some(task) = editor.confirm_completion(
1258 &ConfirmCompletion {
1259 item_ix: Some(item_ix),
1260 },
1261 cx,
1262 ) {
1263 task.detach_and_log_err(cx)
1264 }
1265 }))
1266 .start_slot::<Div>(color_swatch)
1267 .child(h_flex().overflow_hidden().child(completion_label))
1268 .end_slot::<Label>(documentation_label),
1269 )
1270 })
1271 .collect()
1272 },
1273 )
1274 .occlude()
1275 .max_h(max_height)
1276 .track_scroll(self.scroll_handle.clone())
1277 .with_width_from_item(widest_completion_ix)
1278 .with_sizing_behavior(ListSizingBehavior::Infer);
1279
1280 Popover::new()
1281 .child(list)
1282 .when_some(multiline_docs, |popover, multiline_docs| {
1283 popover.aside(multiline_docs)
1284 })
1285 .into_any_element()
1286 }
1287
1288 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1289 let mut matches = if let Some(query) = query {
1290 fuzzy::match_strings(
1291 &self.match_candidates,
1292 query,
1293 query.chars().any(|c| c.is_uppercase()),
1294 100,
1295 &Default::default(),
1296 executor,
1297 )
1298 .await
1299 } else {
1300 self.match_candidates
1301 .iter()
1302 .enumerate()
1303 .map(|(candidate_id, candidate)| StringMatch {
1304 candidate_id,
1305 score: Default::default(),
1306 positions: Default::default(),
1307 string: candidate.string.clone(),
1308 })
1309 .collect()
1310 };
1311
1312 // Remove all candidates where the query's start does not match the start of any word in the candidate
1313 if let Some(query) = query {
1314 if let Some(query_start) = query.chars().next() {
1315 matches.retain(|string_match| {
1316 split_words(&string_match.string).any(|word| {
1317 // Check that the first codepoint of the word as lowercase matches the first
1318 // codepoint of the query as lowercase
1319 word.chars()
1320 .flat_map(|codepoint| codepoint.to_lowercase())
1321 .zip(query_start.to_lowercase())
1322 .all(|(word_cp, query_cp)| word_cp == query_cp)
1323 })
1324 });
1325 }
1326 }
1327
1328 let completions = self.completions.read();
1329 if self.sort_completions {
1330 matches.sort_unstable_by_key(|mat| {
1331 // We do want to strike a balance here between what the language server tells us
1332 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1333 // `Creat` and there is a local variable called `CreateComponent`).
1334 // So what we do is: we bucket all matches into two buckets
1335 // - Strong matches
1336 // - Weak matches
1337 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1338 // and the Weak matches are the rest.
1339 //
1340 // For the strong matches, we sort by the language-servers score first and for the weak
1341 // matches, we prefer our fuzzy finder first.
1342 //
1343 // The thinking behind that: it's useless to take the sort_text the language-server gives
1344 // us into account when it's obviously a bad match.
1345
1346 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1347 enum MatchScore<'a> {
1348 Strong {
1349 sort_text: Option<&'a str>,
1350 score: Reverse<OrderedFloat<f64>>,
1351 sort_key: (usize, &'a str),
1352 },
1353 Weak {
1354 score: Reverse<OrderedFloat<f64>>,
1355 sort_text: Option<&'a str>,
1356 sort_key: (usize, &'a str),
1357 },
1358 }
1359
1360 let completion = &completions[mat.candidate_id];
1361 let sort_key = completion.sort_key();
1362 let sort_text = completion.lsp_completion.sort_text.as_deref();
1363 let score = Reverse(OrderedFloat(mat.score));
1364
1365 if mat.score >= 0.2 {
1366 MatchScore::Strong {
1367 sort_text,
1368 score,
1369 sort_key,
1370 }
1371 } else {
1372 MatchScore::Weak {
1373 score,
1374 sort_text,
1375 sort_key,
1376 }
1377 }
1378 });
1379 }
1380
1381 for mat in &mut matches {
1382 let completion = &completions[mat.candidate_id];
1383 mat.string.clone_from(&completion.label.text);
1384 for position in &mut mat.positions {
1385 *position += completion.label.filter_range.start;
1386 }
1387 }
1388 drop(completions);
1389
1390 self.matches = matches.into();
1391 self.selected_item = 0;
1392 }
1393}
1394
1395struct AvailableCodeAction {
1396 excerpt_id: ExcerptId,
1397 action: CodeAction,
1398 provider: Arc<dyn CodeActionProvider>,
1399}
1400
1401#[derive(Clone)]
1402struct CodeActionContents {
1403 tasks: Option<Arc<ResolvedTasks>>,
1404 actions: Option<Arc<[AvailableCodeAction]>>,
1405}
1406
1407impl CodeActionContents {
1408 fn len(&self) -> usize {
1409 match (&self.tasks, &self.actions) {
1410 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1411 (Some(tasks), None) => tasks.templates.len(),
1412 (None, Some(actions)) => actions.len(),
1413 (None, None) => 0,
1414 }
1415 }
1416
1417 fn is_empty(&self) -> bool {
1418 match (&self.tasks, &self.actions) {
1419 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1420 (Some(tasks), None) => tasks.templates.is_empty(),
1421 (None, Some(actions)) => actions.is_empty(),
1422 (None, None) => true,
1423 }
1424 }
1425
1426 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1427 self.tasks
1428 .iter()
1429 .flat_map(|tasks| {
1430 tasks
1431 .templates
1432 .iter()
1433 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1434 })
1435 .chain(self.actions.iter().flat_map(|actions| {
1436 actions.iter().map(|available| CodeActionsItem::CodeAction {
1437 excerpt_id: available.excerpt_id,
1438 action: available.action.clone(),
1439 provider: available.provider.clone(),
1440 })
1441 }))
1442 }
1443 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1444 match (&self.tasks, &self.actions) {
1445 (Some(tasks), Some(actions)) => {
1446 if index < tasks.templates.len() {
1447 tasks
1448 .templates
1449 .get(index)
1450 .cloned()
1451 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1452 } else {
1453 actions.get(index - tasks.templates.len()).map(|available| {
1454 CodeActionsItem::CodeAction {
1455 excerpt_id: available.excerpt_id,
1456 action: available.action.clone(),
1457 provider: available.provider.clone(),
1458 }
1459 })
1460 }
1461 }
1462 (Some(tasks), None) => tasks
1463 .templates
1464 .get(index)
1465 .cloned()
1466 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1467 (None, Some(actions)) => {
1468 actions
1469 .get(index)
1470 .map(|available| CodeActionsItem::CodeAction {
1471 excerpt_id: available.excerpt_id,
1472 action: available.action.clone(),
1473 provider: available.provider.clone(),
1474 })
1475 }
1476 (None, None) => None,
1477 }
1478 }
1479}
1480
1481#[allow(clippy::large_enum_variant)]
1482#[derive(Clone)]
1483enum CodeActionsItem {
1484 Task(TaskSourceKind, ResolvedTask),
1485 CodeAction {
1486 excerpt_id: ExcerptId,
1487 action: CodeAction,
1488 provider: Arc<dyn CodeActionProvider>,
1489 },
1490}
1491
1492impl CodeActionsItem {
1493 fn as_task(&self) -> Option<&ResolvedTask> {
1494 let Self::Task(_, task) = self else {
1495 return None;
1496 };
1497 Some(task)
1498 }
1499 fn as_code_action(&self) -> Option<&CodeAction> {
1500 let Self::CodeAction { action, .. } = self else {
1501 return None;
1502 };
1503 Some(action)
1504 }
1505 fn label(&self) -> String {
1506 match self {
1507 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1508 Self::Task(_, task) => task.resolved_label.clone(),
1509 }
1510 }
1511}
1512
1513struct CodeActionsMenu {
1514 actions: CodeActionContents,
1515 buffer: Model<Buffer>,
1516 selected_item: usize,
1517 scroll_handle: UniformListScrollHandle,
1518 deployed_from_indicator: Option<DisplayRow>,
1519}
1520
1521impl CodeActionsMenu {
1522 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1523 self.selected_item = 0;
1524 self.scroll_handle.scroll_to_item(self.selected_item);
1525 cx.notify()
1526 }
1527
1528 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1529 if self.selected_item > 0 {
1530 self.selected_item -= 1;
1531 } else {
1532 self.selected_item = self.actions.len() - 1;
1533 }
1534 self.scroll_handle.scroll_to_item(self.selected_item);
1535 cx.notify();
1536 }
1537
1538 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1539 if self.selected_item + 1 < self.actions.len() {
1540 self.selected_item += 1;
1541 } else {
1542 self.selected_item = 0;
1543 }
1544 self.scroll_handle.scroll_to_item(self.selected_item);
1545 cx.notify();
1546 }
1547
1548 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1549 self.selected_item = self.actions.len() - 1;
1550 self.scroll_handle.scroll_to_item(self.selected_item);
1551 cx.notify()
1552 }
1553
1554 fn visible(&self) -> bool {
1555 !self.actions.is_empty()
1556 }
1557
1558 fn render(
1559 &self,
1560 cursor_position: DisplayPoint,
1561 _style: &EditorStyle,
1562 max_height: Pixels,
1563 cx: &mut ViewContext<Editor>,
1564 ) -> (ContextMenuOrigin, AnyElement) {
1565 let actions = self.actions.clone();
1566 let selected_item = self.selected_item;
1567 let element = uniform_list(
1568 cx.view().clone(),
1569 "code_actions_menu",
1570 self.actions.len(),
1571 move |_this, range, cx| {
1572 actions
1573 .iter()
1574 .skip(range.start)
1575 .take(range.end - range.start)
1576 .enumerate()
1577 .map(|(ix, action)| {
1578 let item_ix = range.start + ix;
1579 let selected = selected_item == item_ix;
1580 let colors = cx.theme().colors();
1581 div()
1582 .px_1()
1583 .rounded_md()
1584 .text_color(colors.text)
1585 .when(selected, |style| {
1586 style
1587 .bg(colors.element_active)
1588 .text_color(colors.text_accent)
1589 })
1590 .hover(|style| {
1591 style
1592 .bg(colors.element_hover)
1593 .text_color(colors.text_accent)
1594 })
1595 .whitespace_nowrap()
1596 .when_some(action.as_code_action(), |this, action| {
1597 this.on_mouse_down(
1598 MouseButton::Left,
1599 cx.listener(move |editor, _, cx| {
1600 cx.stop_propagation();
1601 if let Some(task) = editor.confirm_code_action(
1602 &ConfirmCodeAction {
1603 item_ix: Some(item_ix),
1604 },
1605 cx,
1606 ) {
1607 task.detach_and_log_err(cx)
1608 }
1609 }),
1610 )
1611 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1612 .child(SharedString::from(action.lsp_action.title.clone()))
1613 })
1614 .when_some(action.as_task(), |this, task| {
1615 this.on_mouse_down(
1616 MouseButton::Left,
1617 cx.listener(move |editor, _, cx| {
1618 cx.stop_propagation();
1619 if let Some(task) = editor.confirm_code_action(
1620 &ConfirmCodeAction {
1621 item_ix: Some(item_ix),
1622 },
1623 cx,
1624 ) {
1625 task.detach_and_log_err(cx)
1626 }
1627 }),
1628 )
1629 .child(SharedString::from(task.resolved_label.clone()))
1630 })
1631 })
1632 .collect()
1633 },
1634 )
1635 .elevation_1(cx)
1636 .p_1()
1637 .max_h(max_height)
1638 .occlude()
1639 .track_scroll(self.scroll_handle.clone())
1640 .with_width_from_item(
1641 self.actions
1642 .iter()
1643 .enumerate()
1644 .max_by_key(|(_, action)| match action {
1645 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1646 CodeActionsItem::CodeAction { action, .. } => {
1647 action.lsp_action.title.chars().count()
1648 }
1649 })
1650 .map(|(ix, _)| ix),
1651 )
1652 .with_sizing_behavior(ListSizingBehavior::Infer)
1653 .into_any_element();
1654
1655 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1656 ContextMenuOrigin::GutterIndicator(row)
1657 } else {
1658 ContextMenuOrigin::EditorPoint(cursor_position)
1659 };
1660
1661 (cursor_position, element)
1662 }
1663}
1664
1665#[derive(Debug)]
1666struct ActiveDiagnosticGroup {
1667 primary_range: Range<Anchor>,
1668 primary_message: String,
1669 group_id: usize,
1670 blocks: HashMap<CustomBlockId, Diagnostic>,
1671 is_valid: bool,
1672}
1673
1674#[derive(Serialize, Deserialize, Clone, Debug)]
1675pub struct ClipboardSelection {
1676 pub len: usize,
1677 pub is_entire_line: bool,
1678 pub first_line_indent: u32,
1679}
1680
1681#[derive(Debug)]
1682pub(crate) struct NavigationData {
1683 cursor_anchor: Anchor,
1684 cursor_position: Point,
1685 scroll_anchor: ScrollAnchor,
1686 scroll_top_row: u32,
1687}
1688
1689#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1690pub enum GotoDefinitionKind {
1691 Symbol,
1692 Declaration,
1693 Type,
1694 Implementation,
1695}
1696
1697#[derive(Debug, Clone)]
1698enum InlayHintRefreshReason {
1699 Toggle(bool),
1700 SettingsChange(InlayHintSettings),
1701 NewLinesShown,
1702 BufferEdited(HashSet<Arc<Language>>),
1703 RefreshRequested,
1704 ExcerptsRemoved(Vec<ExcerptId>),
1705}
1706
1707impl InlayHintRefreshReason {
1708 fn description(&self) -> &'static str {
1709 match self {
1710 Self::Toggle(_) => "toggle",
1711 Self::SettingsChange(_) => "settings change",
1712 Self::NewLinesShown => "new lines shown",
1713 Self::BufferEdited(_) => "buffer edited",
1714 Self::RefreshRequested => "refresh requested",
1715 Self::ExcerptsRemoved(_) => "excerpts removed",
1716 }
1717 }
1718}
1719
1720pub(crate) struct FocusedBlock {
1721 id: BlockId,
1722 focus_handle: WeakFocusHandle,
1723}
1724
1725impl Editor {
1726 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1727 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1728 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1729 Self::new(
1730 EditorMode::SingleLine { auto_width: false },
1731 buffer,
1732 None,
1733 false,
1734 cx,
1735 )
1736 }
1737
1738 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1739 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1740 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1741 Self::new(EditorMode::Full, buffer, None, false, cx)
1742 }
1743
1744 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1745 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1746 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1747 Self::new(
1748 EditorMode::SingleLine { auto_width: true },
1749 buffer,
1750 None,
1751 false,
1752 cx,
1753 )
1754 }
1755
1756 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1757 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1758 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1759 Self::new(
1760 EditorMode::AutoHeight { max_lines },
1761 buffer,
1762 None,
1763 false,
1764 cx,
1765 )
1766 }
1767
1768 pub fn for_buffer(
1769 buffer: Model<Buffer>,
1770 project: Option<Model<Project>>,
1771 cx: &mut ViewContext<Self>,
1772 ) -> Self {
1773 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1774 Self::new(EditorMode::Full, buffer, project, false, cx)
1775 }
1776
1777 pub fn for_multibuffer(
1778 buffer: Model<MultiBuffer>,
1779 project: Option<Model<Project>>,
1780 show_excerpt_controls: bool,
1781 cx: &mut ViewContext<Self>,
1782 ) -> Self {
1783 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1784 }
1785
1786 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1787 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1788 let mut clone = Self::new(
1789 self.mode,
1790 self.buffer.clone(),
1791 self.project.clone(),
1792 show_excerpt_controls,
1793 cx,
1794 );
1795 self.display_map.update(cx, |display_map, cx| {
1796 let snapshot = display_map.snapshot(cx);
1797 clone.display_map.update(cx, |display_map, cx| {
1798 display_map.set_state(&snapshot, cx);
1799 });
1800 });
1801 clone.selections.clone_state(&self.selections);
1802 clone.scroll_manager.clone_state(&self.scroll_manager);
1803 clone.searchable = self.searchable;
1804 clone
1805 }
1806
1807 pub fn new(
1808 mode: EditorMode,
1809 buffer: Model<MultiBuffer>,
1810 project: Option<Model<Project>>,
1811 show_excerpt_controls: bool,
1812 cx: &mut ViewContext<Self>,
1813 ) -> Self {
1814 let style = cx.text_style();
1815 let font_size = style.font_size.to_pixels(cx.rem_size());
1816 let editor = cx.view().downgrade();
1817 let fold_placeholder = FoldPlaceholder {
1818 constrain_width: true,
1819 render: Arc::new(move |fold_id, fold_range, cx| {
1820 let editor = editor.clone();
1821 div()
1822 .id(fold_id)
1823 .bg(cx.theme().colors().ghost_element_background)
1824 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1825 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1826 .rounded_sm()
1827 .size_full()
1828 .cursor_pointer()
1829 .child("⋯")
1830 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1831 .on_click(move |_, cx| {
1832 editor
1833 .update(cx, |editor, cx| {
1834 editor.unfold_ranges(
1835 [fold_range.start..fold_range.end],
1836 true,
1837 false,
1838 cx,
1839 );
1840 cx.stop_propagation();
1841 })
1842 .ok();
1843 })
1844 .into_any()
1845 }),
1846 merge_adjacent: true,
1847 };
1848 let display_map = cx.new_model(|cx| {
1849 DisplayMap::new(
1850 buffer.clone(),
1851 style.font(),
1852 font_size,
1853 None,
1854 show_excerpt_controls,
1855 FILE_HEADER_HEIGHT,
1856 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1857 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1858 fold_placeholder,
1859 cx,
1860 )
1861 });
1862
1863 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1864
1865 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1866
1867 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1868 .then(|| language_settings::SoftWrap::None);
1869
1870 let mut project_subscriptions = Vec::new();
1871 if mode == EditorMode::Full {
1872 if let Some(project) = project.as_ref() {
1873 if buffer.read(cx).is_singleton() {
1874 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1875 cx.emit(EditorEvent::TitleChanged);
1876 }));
1877 }
1878 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1879 if let project::Event::RefreshInlayHints = event {
1880 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1881 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1882 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1883 let focus_handle = editor.focus_handle(cx);
1884 if focus_handle.is_focused(cx) {
1885 let snapshot = buffer.read(cx).snapshot();
1886 for (range, snippet) in snippet_edits {
1887 let editor_range =
1888 language::range_from_lsp(*range).to_offset(&snapshot);
1889 editor
1890 .insert_snippet(&[editor_range], snippet.clone(), cx)
1891 .ok();
1892 }
1893 }
1894 }
1895 }
1896 }));
1897 if let Some(task_inventory) = project
1898 .read(cx)
1899 .task_store()
1900 .read(cx)
1901 .task_inventory()
1902 .cloned()
1903 {
1904 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1905 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1906 }));
1907 }
1908 }
1909 }
1910
1911 let inlay_hint_settings = inlay_hint_settings(
1912 selections.newest_anchor().head(),
1913 &buffer.read(cx).snapshot(cx),
1914 cx,
1915 );
1916 let focus_handle = cx.focus_handle();
1917 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1918 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1919 .detach();
1920 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1921 .detach();
1922 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1923
1924 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1925 Some(false)
1926 } else {
1927 None
1928 };
1929
1930 let mut code_action_providers = Vec::new();
1931 if let Some(project) = project.clone() {
1932 code_action_providers.push(Arc::new(project) as Arc<_>);
1933 }
1934
1935 let mut this = Self {
1936 focus_handle,
1937 show_cursor_when_unfocused: false,
1938 last_focused_descendant: None,
1939 buffer: buffer.clone(),
1940 display_map: display_map.clone(),
1941 selections,
1942 scroll_manager: ScrollManager::new(cx),
1943 columnar_selection_tail: None,
1944 add_selections_state: None,
1945 select_next_state: None,
1946 select_prev_state: None,
1947 selection_history: Default::default(),
1948 autoclose_regions: Default::default(),
1949 snippet_stack: Default::default(),
1950 select_larger_syntax_node_stack: Vec::new(),
1951 ime_transaction: Default::default(),
1952 active_diagnostics: None,
1953 soft_wrap_mode_override,
1954 completion_provider: project.clone().map(|project| Box::new(project) as _),
1955 semantics_provider: project.clone().map(|project| Rc::new(project) as _),
1956 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1957 project,
1958 blink_manager: blink_manager.clone(),
1959 show_local_selections: true,
1960 mode,
1961 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1962 show_gutter: mode == EditorMode::Full,
1963 show_line_numbers: None,
1964 use_relative_line_numbers: None,
1965 show_git_diff_gutter: None,
1966 show_code_actions: None,
1967 show_runnables: None,
1968 show_wrap_guides: None,
1969 show_indent_guides,
1970 placeholder_text: None,
1971 highlight_order: 0,
1972 highlighted_rows: HashMap::default(),
1973 background_highlights: Default::default(),
1974 gutter_highlights: TreeMap::default(),
1975 scrollbar_marker_state: ScrollbarMarkerState::default(),
1976 active_indent_guides_state: ActiveIndentGuidesState::default(),
1977 nav_history: None,
1978 context_menu: RwLock::new(None),
1979 mouse_context_menu: None,
1980 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1981 completion_tasks: Default::default(),
1982 signature_help_state: SignatureHelpState::default(),
1983 auto_signature_help: None,
1984 find_all_references_task_sources: Vec::new(),
1985 next_completion_id: 0,
1986 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1987 next_inlay_id: 0,
1988 code_action_providers,
1989 available_code_actions: Default::default(),
1990 code_actions_task: Default::default(),
1991 document_highlights_task: Default::default(),
1992 linked_editing_range_task: Default::default(),
1993 pending_rename: Default::default(),
1994 searchable: true,
1995 cursor_shape: EditorSettings::get_global(cx)
1996 .cursor_shape
1997 .unwrap_or_default(),
1998 current_line_highlight: None,
1999 autoindent_mode: Some(AutoindentMode::EachLine),
2000 collapse_matches: false,
2001 workspace: None,
2002 input_enabled: true,
2003 use_modal_editing: mode == EditorMode::Full,
2004 read_only: false,
2005 use_autoclose: true,
2006 use_auto_surround: true,
2007 auto_replace_emoji_shortcode: false,
2008 leader_peer_id: None,
2009 remote_id: None,
2010 hover_state: Default::default(),
2011 hovered_link_state: Default::default(),
2012 inline_completion_provider: None,
2013 active_inline_completion: None,
2014 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
2015 expanded_hunks: ExpandedHunks::default(),
2016 gutter_hovered: false,
2017 pixel_position_of_newest_cursor: None,
2018 last_bounds: None,
2019 expect_bounds_change: None,
2020 gutter_dimensions: GutterDimensions::default(),
2021 style: None,
2022 show_cursor_names: false,
2023 hovered_cursors: Default::default(),
2024 next_editor_action_id: EditorActionId::default(),
2025 editor_actions: Rc::default(),
2026 show_inline_completions_override: None,
2027 enable_inline_completions: true,
2028 custom_context_menu: None,
2029 show_git_blame_gutter: false,
2030 show_git_blame_inline: false,
2031 show_selection_menu: None,
2032 show_git_blame_inline_delay_task: None,
2033 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2034 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2035 .session
2036 .restore_unsaved_buffers,
2037 blame: None,
2038 blame_subscription: None,
2039 tasks: Default::default(),
2040 _subscriptions: vec![
2041 cx.observe(&buffer, Self::on_buffer_changed),
2042 cx.subscribe(&buffer, Self::on_buffer_event),
2043 cx.observe(&display_map, Self::on_display_map_changed),
2044 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2045 cx.observe_global::<SettingsStore>(Self::settings_changed),
2046 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2047 cx.observe_window_activation(|editor, cx| {
2048 let active = cx.is_window_active();
2049 editor.blink_manager.update(cx, |blink_manager, cx| {
2050 if active {
2051 blink_manager.enable(cx);
2052 } else {
2053 blink_manager.disable(cx);
2054 }
2055 });
2056 }),
2057 ],
2058 tasks_update_task: None,
2059 linked_edit_ranges: Default::default(),
2060 previous_search_ranges: None,
2061 breadcrumb_header: None,
2062 focused_block: None,
2063 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2064 addons: HashMap::default(),
2065 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2066 };
2067 this.tasks_update_task = Some(this.refresh_runnables(cx));
2068 this._subscriptions.extend(project_subscriptions);
2069
2070 this.end_selection(cx);
2071 this.scroll_manager.show_scrollbar(cx);
2072
2073 if mode == EditorMode::Full {
2074 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2075 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2076
2077 if this.git_blame_inline_enabled {
2078 this.git_blame_inline_enabled = true;
2079 this.start_git_blame_inline(false, cx);
2080 }
2081 }
2082
2083 this.report_editor_event("open", None, cx);
2084 this
2085 }
2086
2087 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2088 self.mouse_context_menu
2089 .as_ref()
2090 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2091 }
2092
2093 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2094 let mut key_context = KeyContext::new_with_defaults();
2095 key_context.add("Editor");
2096 let mode = match self.mode {
2097 EditorMode::SingleLine { .. } => "single_line",
2098 EditorMode::AutoHeight { .. } => "auto_height",
2099 EditorMode::Full => "full",
2100 };
2101
2102 if EditorSettings::jupyter_enabled(cx) {
2103 key_context.add("jupyter");
2104 }
2105
2106 key_context.set("mode", mode);
2107 if self.pending_rename.is_some() {
2108 key_context.add("renaming");
2109 }
2110 if self.context_menu_visible() {
2111 match self.context_menu.read().as_ref() {
2112 Some(ContextMenu::Completions(_)) => {
2113 key_context.add("menu");
2114 key_context.add("showing_completions")
2115 }
2116 Some(ContextMenu::CodeActions(_)) => {
2117 key_context.add("menu");
2118 key_context.add("showing_code_actions")
2119 }
2120 None => {}
2121 }
2122 }
2123
2124 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2125 if !self.focus_handle(cx).contains_focused(cx)
2126 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2127 {
2128 for addon in self.addons.values() {
2129 addon.extend_key_context(&mut key_context, cx)
2130 }
2131 }
2132
2133 if let Some(extension) = self
2134 .buffer
2135 .read(cx)
2136 .as_singleton()
2137 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2138 {
2139 key_context.set("extension", extension.to_string());
2140 }
2141
2142 if self.has_active_inline_completion(cx) {
2143 key_context.add("copilot_suggestion");
2144 key_context.add("inline_completion");
2145 }
2146
2147 key_context
2148 }
2149
2150 pub fn new_file(
2151 workspace: &mut Workspace,
2152 _: &workspace::NewFile,
2153 cx: &mut ViewContext<Workspace>,
2154 ) {
2155 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2156 "Failed to create buffer",
2157 cx,
2158 |e, _| match e.error_code() {
2159 ErrorCode::RemoteUpgradeRequired => Some(format!(
2160 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2161 e.error_tag("required").unwrap_or("the latest version")
2162 )),
2163 _ => None,
2164 },
2165 );
2166 }
2167
2168 pub fn new_in_workspace(
2169 workspace: &mut Workspace,
2170 cx: &mut ViewContext<Workspace>,
2171 ) -> Task<Result<View<Editor>>> {
2172 let project = workspace.project().clone();
2173 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2174
2175 cx.spawn(|workspace, mut cx| async move {
2176 let buffer = create.await?;
2177 workspace.update(&mut cx, |workspace, cx| {
2178 let editor =
2179 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2180 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2181 editor
2182 })
2183 })
2184 }
2185
2186 fn new_file_vertical(
2187 workspace: &mut Workspace,
2188 _: &workspace::NewFileSplitVertical,
2189 cx: &mut ViewContext<Workspace>,
2190 ) {
2191 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2192 }
2193
2194 fn new_file_horizontal(
2195 workspace: &mut Workspace,
2196 _: &workspace::NewFileSplitHorizontal,
2197 cx: &mut ViewContext<Workspace>,
2198 ) {
2199 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2200 }
2201
2202 fn new_file_in_direction(
2203 workspace: &mut Workspace,
2204 direction: SplitDirection,
2205 cx: &mut ViewContext<Workspace>,
2206 ) {
2207 let project = workspace.project().clone();
2208 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2209
2210 cx.spawn(|workspace, mut cx| async move {
2211 let buffer = create.await?;
2212 workspace.update(&mut cx, move |workspace, cx| {
2213 workspace.split_item(
2214 direction,
2215 Box::new(
2216 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2217 ),
2218 cx,
2219 )
2220 })?;
2221 anyhow::Ok(())
2222 })
2223 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2224 ErrorCode::RemoteUpgradeRequired => Some(format!(
2225 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2226 e.error_tag("required").unwrap_or("the latest version")
2227 )),
2228 _ => None,
2229 });
2230 }
2231
2232 pub fn leader_peer_id(&self) -> Option<PeerId> {
2233 self.leader_peer_id
2234 }
2235
2236 pub fn buffer(&self) -> &Model<MultiBuffer> {
2237 &self.buffer
2238 }
2239
2240 pub fn workspace(&self) -> Option<View<Workspace>> {
2241 self.workspace.as_ref()?.0.upgrade()
2242 }
2243
2244 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2245 self.buffer().read(cx).title(cx)
2246 }
2247
2248 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2249 let git_blame_gutter_max_author_length = self
2250 .render_git_blame_gutter(cx)
2251 .then(|| {
2252 if let Some(blame) = self.blame.as_ref() {
2253 let max_author_length =
2254 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2255 Some(max_author_length)
2256 } else {
2257 None
2258 }
2259 })
2260 .flatten();
2261
2262 EditorSnapshot {
2263 mode: self.mode,
2264 show_gutter: self.show_gutter,
2265 show_line_numbers: self.show_line_numbers,
2266 show_git_diff_gutter: self.show_git_diff_gutter,
2267 show_code_actions: self.show_code_actions,
2268 show_runnables: self.show_runnables,
2269 git_blame_gutter_max_author_length,
2270 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2271 scroll_anchor: self.scroll_manager.anchor(),
2272 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2273 placeholder_text: self.placeholder_text.clone(),
2274 is_focused: self.focus_handle.is_focused(cx),
2275 current_line_highlight: self
2276 .current_line_highlight
2277 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2278 gutter_hovered: self.gutter_hovered,
2279 }
2280 }
2281
2282 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2283 self.buffer.read(cx).language_at(point, cx)
2284 }
2285
2286 pub fn file_at<T: ToOffset>(
2287 &self,
2288 point: T,
2289 cx: &AppContext,
2290 ) -> Option<Arc<dyn language::File>> {
2291 self.buffer.read(cx).read(cx).file_at(point).cloned()
2292 }
2293
2294 pub fn active_excerpt(
2295 &self,
2296 cx: &AppContext,
2297 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2298 self.buffer
2299 .read(cx)
2300 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2301 }
2302
2303 pub fn mode(&self) -> EditorMode {
2304 self.mode
2305 }
2306
2307 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2308 self.collaboration_hub.as_deref()
2309 }
2310
2311 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2312 self.collaboration_hub = Some(hub);
2313 }
2314
2315 pub fn set_custom_context_menu(
2316 &mut self,
2317 f: impl 'static
2318 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2319 ) {
2320 self.custom_context_menu = Some(Box::new(f))
2321 }
2322
2323 pub fn set_completion_provider(&mut self, provider: Option<Box<dyn CompletionProvider>>) {
2324 self.completion_provider = provider;
2325 }
2326
2327 pub fn semantics_provider(&self) -> Option<Rc<dyn SemanticsProvider>> {
2328 self.semantics_provider.clone()
2329 }
2330
2331 pub fn set_semantics_provider(&mut self, provider: Option<Rc<dyn SemanticsProvider>>) {
2332 self.semantics_provider = provider;
2333 }
2334
2335 pub fn set_inline_completion_provider<T>(
2336 &mut self,
2337 provider: Option<Model<T>>,
2338 cx: &mut ViewContext<Self>,
2339 ) where
2340 T: InlineCompletionProvider,
2341 {
2342 self.inline_completion_provider =
2343 provider.map(|provider| RegisteredInlineCompletionProvider {
2344 _subscription: cx.observe(&provider, |this, _, cx| {
2345 if this.focus_handle.is_focused(cx) {
2346 this.update_visible_inline_completion(cx);
2347 }
2348 }),
2349 provider: Arc::new(provider),
2350 });
2351 self.refresh_inline_completion(false, false, cx);
2352 }
2353
2354 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2355 self.placeholder_text.as_deref()
2356 }
2357
2358 pub fn set_placeholder_text(
2359 &mut self,
2360 placeholder_text: impl Into<Arc<str>>,
2361 cx: &mut ViewContext<Self>,
2362 ) {
2363 let placeholder_text = Some(placeholder_text.into());
2364 if self.placeholder_text != placeholder_text {
2365 self.placeholder_text = placeholder_text;
2366 cx.notify();
2367 }
2368 }
2369
2370 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2371 self.cursor_shape = cursor_shape;
2372
2373 // Disrupt blink for immediate user feedback that the cursor shape has changed
2374 self.blink_manager.update(cx, BlinkManager::show_cursor);
2375
2376 cx.notify();
2377 }
2378
2379 pub fn set_current_line_highlight(
2380 &mut self,
2381 current_line_highlight: Option<CurrentLineHighlight>,
2382 ) {
2383 self.current_line_highlight = current_line_highlight;
2384 }
2385
2386 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2387 self.collapse_matches = collapse_matches;
2388 }
2389
2390 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2391 if self.collapse_matches {
2392 return range.start..range.start;
2393 }
2394 range.clone()
2395 }
2396
2397 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2398 if self.display_map.read(cx).clip_at_line_ends != clip {
2399 self.display_map
2400 .update(cx, |map, _| map.clip_at_line_ends = clip);
2401 }
2402 }
2403
2404 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2405 self.input_enabled = input_enabled;
2406 }
2407
2408 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2409 self.enable_inline_completions = enabled;
2410 }
2411
2412 pub fn set_autoindent(&mut self, autoindent: bool) {
2413 if autoindent {
2414 self.autoindent_mode = Some(AutoindentMode::EachLine);
2415 } else {
2416 self.autoindent_mode = None;
2417 }
2418 }
2419
2420 pub fn read_only(&self, cx: &AppContext) -> bool {
2421 self.read_only || self.buffer.read(cx).read_only()
2422 }
2423
2424 pub fn set_read_only(&mut self, read_only: bool) {
2425 self.read_only = read_only;
2426 }
2427
2428 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2429 self.use_autoclose = autoclose;
2430 }
2431
2432 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2433 self.use_auto_surround = auto_surround;
2434 }
2435
2436 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2437 self.auto_replace_emoji_shortcode = auto_replace;
2438 }
2439
2440 pub fn toggle_inline_completions(
2441 &mut self,
2442 _: &ToggleInlineCompletions,
2443 cx: &mut ViewContext<Self>,
2444 ) {
2445 if self.show_inline_completions_override.is_some() {
2446 self.set_show_inline_completions(None, cx);
2447 } else {
2448 let cursor = self.selections.newest_anchor().head();
2449 if let Some((buffer, cursor_buffer_position)) =
2450 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2451 {
2452 let show_inline_completions =
2453 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2454 self.set_show_inline_completions(Some(show_inline_completions), cx);
2455 }
2456 }
2457 }
2458
2459 pub fn set_show_inline_completions(
2460 &mut self,
2461 show_inline_completions: Option<bool>,
2462 cx: &mut ViewContext<Self>,
2463 ) {
2464 self.show_inline_completions_override = show_inline_completions;
2465 self.refresh_inline_completion(false, true, cx);
2466 }
2467
2468 fn should_show_inline_completions(
2469 &self,
2470 buffer: &Model<Buffer>,
2471 buffer_position: language::Anchor,
2472 cx: &AppContext,
2473 ) -> bool {
2474 if let Some(provider) = self.inline_completion_provider() {
2475 if let Some(show_inline_completions) = self.show_inline_completions_override {
2476 show_inline_completions
2477 } else {
2478 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2479 }
2480 } else {
2481 false
2482 }
2483 }
2484
2485 pub fn set_use_modal_editing(&mut self, to: bool) {
2486 self.use_modal_editing = to;
2487 }
2488
2489 pub fn use_modal_editing(&self) -> bool {
2490 self.use_modal_editing
2491 }
2492
2493 fn selections_did_change(
2494 &mut self,
2495 local: bool,
2496 old_cursor_position: &Anchor,
2497 show_completions: bool,
2498 cx: &mut ViewContext<Self>,
2499 ) {
2500 cx.invalidate_character_coordinates();
2501
2502 // Copy selections to primary selection buffer
2503 #[cfg(target_os = "linux")]
2504 if local {
2505 let selections = self.selections.all::<usize>(cx);
2506 let buffer_handle = self.buffer.read(cx).read(cx);
2507
2508 let mut text = String::new();
2509 for (index, selection) in selections.iter().enumerate() {
2510 let text_for_selection = buffer_handle
2511 .text_for_range(selection.start..selection.end)
2512 .collect::<String>();
2513
2514 text.push_str(&text_for_selection);
2515 if index != selections.len() - 1 {
2516 text.push('\n');
2517 }
2518 }
2519
2520 if !text.is_empty() {
2521 cx.write_to_primary(ClipboardItem::new_string(text));
2522 }
2523 }
2524
2525 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2526 self.buffer.update(cx, |buffer, cx| {
2527 buffer.set_active_selections(
2528 &self.selections.disjoint_anchors(),
2529 self.selections.line_mode,
2530 self.cursor_shape,
2531 cx,
2532 )
2533 });
2534 }
2535 let display_map = self
2536 .display_map
2537 .update(cx, |display_map, cx| display_map.snapshot(cx));
2538 let buffer = &display_map.buffer_snapshot;
2539 self.add_selections_state = None;
2540 self.select_next_state = None;
2541 self.select_prev_state = None;
2542 self.select_larger_syntax_node_stack.clear();
2543 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2544 self.snippet_stack
2545 .invalidate(&self.selections.disjoint_anchors(), buffer);
2546 self.take_rename(false, cx);
2547
2548 let new_cursor_position = self.selections.newest_anchor().head();
2549
2550 self.push_to_nav_history(
2551 *old_cursor_position,
2552 Some(new_cursor_position.to_point(buffer)),
2553 cx,
2554 );
2555
2556 if local {
2557 let new_cursor_position = self.selections.newest_anchor().head();
2558 let mut context_menu = self.context_menu.write();
2559 let completion_menu = match context_menu.as_ref() {
2560 Some(ContextMenu::Completions(menu)) => Some(menu),
2561
2562 _ => {
2563 *context_menu = None;
2564 None
2565 }
2566 };
2567
2568 if let Some(completion_menu) = completion_menu {
2569 let cursor_position = new_cursor_position.to_offset(buffer);
2570 let (word_range, kind) =
2571 buffer.surrounding_word(completion_menu.initial_position, true);
2572 if kind == Some(CharKind::Word)
2573 && word_range.to_inclusive().contains(&cursor_position)
2574 {
2575 let mut completion_menu = completion_menu.clone();
2576 drop(context_menu);
2577
2578 let query = Self::completion_query(buffer, cursor_position);
2579 cx.spawn(move |this, mut cx| async move {
2580 completion_menu
2581 .filter(query.as_deref(), cx.background_executor().clone())
2582 .await;
2583
2584 this.update(&mut cx, |this, cx| {
2585 let mut context_menu = this.context_menu.write();
2586 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2587 return;
2588 };
2589
2590 if menu.id > completion_menu.id {
2591 return;
2592 }
2593
2594 *context_menu = Some(ContextMenu::Completions(completion_menu));
2595 drop(context_menu);
2596 cx.notify();
2597 })
2598 })
2599 .detach();
2600
2601 if show_completions {
2602 self.show_completions(&ShowCompletions { trigger: None }, cx);
2603 }
2604 } else {
2605 drop(context_menu);
2606 self.hide_context_menu(cx);
2607 }
2608 } else {
2609 drop(context_menu);
2610 }
2611
2612 hide_hover(self, cx);
2613
2614 if old_cursor_position.to_display_point(&display_map).row()
2615 != new_cursor_position.to_display_point(&display_map).row()
2616 {
2617 self.available_code_actions.take();
2618 }
2619 self.refresh_code_actions(cx);
2620 self.refresh_document_highlights(cx);
2621 refresh_matching_bracket_highlights(self, cx);
2622 self.discard_inline_completion(false, cx);
2623 linked_editing_ranges::refresh_linked_ranges(self, cx);
2624 if self.git_blame_inline_enabled {
2625 self.start_inline_blame_timer(cx);
2626 }
2627 }
2628
2629 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2630 cx.emit(EditorEvent::SelectionsChanged { local });
2631
2632 if self.selections.disjoint_anchors().len() == 1 {
2633 cx.emit(SearchEvent::ActiveMatchChanged)
2634 }
2635 cx.notify();
2636 }
2637
2638 pub fn change_selections<R>(
2639 &mut self,
2640 autoscroll: Option<Autoscroll>,
2641 cx: &mut ViewContext<Self>,
2642 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2643 ) -> R {
2644 self.change_selections_inner(autoscroll, true, cx, change)
2645 }
2646
2647 pub fn change_selections_inner<R>(
2648 &mut self,
2649 autoscroll: Option<Autoscroll>,
2650 request_completions: bool,
2651 cx: &mut ViewContext<Self>,
2652 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2653 ) -> R {
2654 let old_cursor_position = self.selections.newest_anchor().head();
2655 self.push_to_selection_history();
2656
2657 let (changed, result) = self.selections.change_with(cx, change);
2658
2659 if changed {
2660 if let Some(autoscroll) = autoscroll {
2661 self.request_autoscroll(autoscroll, cx);
2662 }
2663 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2664
2665 if self.should_open_signature_help_automatically(
2666 &old_cursor_position,
2667 self.signature_help_state.backspace_pressed(),
2668 cx,
2669 ) {
2670 self.show_signature_help(&ShowSignatureHelp, cx);
2671 }
2672 self.signature_help_state.set_backspace_pressed(false);
2673 }
2674
2675 result
2676 }
2677
2678 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2679 where
2680 I: IntoIterator<Item = (Range<S>, T)>,
2681 S: ToOffset,
2682 T: Into<Arc<str>>,
2683 {
2684 if self.read_only(cx) {
2685 return;
2686 }
2687
2688 self.buffer
2689 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2690 }
2691
2692 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2693 where
2694 I: IntoIterator<Item = (Range<S>, T)>,
2695 S: ToOffset,
2696 T: Into<Arc<str>>,
2697 {
2698 if self.read_only(cx) {
2699 return;
2700 }
2701
2702 self.buffer.update(cx, |buffer, cx| {
2703 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2704 });
2705 }
2706
2707 pub fn edit_with_block_indent<I, S, T>(
2708 &mut self,
2709 edits: I,
2710 original_indent_columns: Vec<u32>,
2711 cx: &mut ViewContext<Self>,
2712 ) where
2713 I: IntoIterator<Item = (Range<S>, T)>,
2714 S: ToOffset,
2715 T: Into<Arc<str>>,
2716 {
2717 if self.read_only(cx) {
2718 return;
2719 }
2720
2721 self.buffer.update(cx, |buffer, cx| {
2722 buffer.edit(
2723 edits,
2724 Some(AutoindentMode::Block {
2725 original_indent_columns,
2726 }),
2727 cx,
2728 )
2729 });
2730 }
2731
2732 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2733 self.hide_context_menu(cx);
2734
2735 match phase {
2736 SelectPhase::Begin {
2737 position,
2738 add,
2739 click_count,
2740 } => self.begin_selection(position, add, click_count, cx),
2741 SelectPhase::BeginColumnar {
2742 position,
2743 goal_column,
2744 reset,
2745 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2746 SelectPhase::Extend {
2747 position,
2748 click_count,
2749 } => self.extend_selection(position, click_count, cx),
2750 SelectPhase::Update {
2751 position,
2752 goal_column,
2753 scroll_delta,
2754 } => self.update_selection(position, goal_column, scroll_delta, cx),
2755 SelectPhase::End => self.end_selection(cx),
2756 }
2757 }
2758
2759 fn extend_selection(
2760 &mut self,
2761 position: DisplayPoint,
2762 click_count: usize,
2763 cx: &mut ViewContext<Self>,
2764 ) {
2765 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2766 let tail = self.selections.newest::<usize>(cx).tail();
2767 self.begin_selection(position, false, click_count, cx);
2768
2769 let position = position.to_offset(&display_map, Bias::Left);
2770 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2771
2772 let mut pending_selection = self
2773 .selections
2774 .pending_anchor()
2775 .expect("extend_selection not called with pending selection");
2776 if position >= tail {
2777 pending_selection.start = tail_anchor;
2778 } else {
2779 pending_selection.end = tail_anchor;
2780 pending_selection.reversed = true;
2781 }
2782
2783 let mut pending_mode = self.selections.pending_mode().unwrap();
2784 match &mut pending_mode {
2785 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2786 _ => {}
2787 }
2788
2789 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2790 s.set_pending(pending_selection, pending_mode)
2791 });
2792 }
2793
2794 fn begin_selection(
2795 &mut self,
2796 position: DisplayPoint,
2797 add: bool,
2798 click_count: usize,
2799 cx: &mut ViewContext<Self>,
2800 ) {
2801 if !self.focus_handle.is_focused(cx) {
2802 self.last_focused_descendant = None;
2803 cx.focus(&self.focus_handle);
2804 }
2805
2806 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2807 let buffer = &display_map.buffer_snapshot;
2808 let newest_selection = self.selections.newest_anchor().clone();
2809 let position = display_map.clip_point(position, Bias::Left);
2810
2811 let start;
2812 let end;
2813 let mode;
2814 let auto_scroll;
2815 match click_count {
2816 1 => {
2817 start = buffer.anchor_before(position.to_point(&display_map));
2818 end = start;
2819 mode = SelectMode::Character;
2820 auto_scroll = true;
2821 }
2822 2 => {
2823 let range = movement::surrounding_word(&display_map, position);
2824 start = buffer.anchor_before(range.start.to_point(&display_map));
2825 end = buffer.anchor_before(range.end.to_point(&display_map));
2826 mode = SelectMode::Word(start..end);
2827 auto_scroll = true;
2828 }
2829 3 => {
2830 let position = display_map
2831 .clip_point(position, Bias::Left)
2832 .to_point(&display_map);
2833 let line_start = display_map.prev_line_boundary(position).0;
2834 let next_line_start = buffer.clip_point(
2835 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2836 Bias::Left,
2837 );
2838 start = buffer.anchor_before(line_start);
2839 end = buffer.anchor_before(next_line_start);
2840 mode = SelectMode::Line(start..end);
2841 auto_scroll = true;
2842 }
2843 _ => {
2844 start = buffer.anchor_before(0);
2845 end = buffer.anchor_before(buffer.len());
2846 mode = SelectMode::All;
2847 auto_scroll = false;
2848 }
2849 }
2850
2851 let point_to_delete: Option<usize> = {
2852 let selected_points: Vec<Selection<Point>> =
2853 self.selections.disjoint_in_range(start..end, cx);
2854
2855 if !add || click_count > 1 {
2856 None
2857 } else if !selected_points.is_empty() {
2858 Some(selected_points[0].id)
2859 } else {
2860 let clicked_point_already_selected =
2861 self.selections.disjoint.iter().find(|selection| {
2862 selection.start.to_point(buffer) == start.to_point(buffer)
2863 || selection.end.to_point(buffer) == end.to_point(buffer)
2864 });
2865
2866 clicked_point_already_selected.map(|selection| selection.id)
2867 }
2868 };
2869
2870 let selections_count = self.selections.count();
2871
2872 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2873 if let Some(point_to_delete) = point_to_delete {
2874 s.delete(point_to_delete);
2875
2876 if selections_count == 1 {
2877 s.set_pending_anchor_range(start..end, mode);
2878 }
2879 } else {
2880 if !add {
2881 s.clear_disjoint();
2882 } else if click_count > 1 {
2883 s.delete(newest_selection.id)
2884 }
2885
2886 s.set_pending_anchor_range(start..end, mode);
2887 }
2888 });
2889 }
2890
2891 fn begin_columnar_selection(
2892 &mut self,
2893 position: DisplayPoint,
2894 goal_column: u32,
2895 reset: bool,
2896 cx: &mut ViewContext<Self>,
2897 ) {
2898 if !self.focus_handle.is_focused(cx) {
2899 self.last_focused_descendant = None;
2900 cx.focus(&self.focus_handle);
2901 }
2902
2903 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2904
2905 if reset {
2906 let pointer_position = display_map
2907 .buffer_snapshot
2908 .anchor_before(position.to_point(&display_map));
2909
2910 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2911 s.clear_disjoint();
2912 s.set_pending_anchor_range(
2913 pointer_position..pointer_position,
2914 SelectMode::Character,
2915 );
2916 });
2917 }
2918
2919 let tail = self.selections.newest::<Point>(cx).tail();
2920 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2921
2922 if !reset {
2923 self.select_columns(
2924 tail.to_display_point(&display_map),
2925 position,
2926 goal_column,
2927 &display_map,
2928 cx,
2929 );
2930 }
2931 }
2932
2933 fn update_selection(
2934 &mut self,
2935 position: DisplayPoint,
2936 goal_column: u32,
2937 scroll_delta: gpui::Point<f32>,
2938 cx: &mut ViewContext<Self>,
2939 ) {
2940 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2941
2942 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2943 let tail = tail.to_display_point(&display_map);
2944 self.select_columns(tail, position, goal_column, &display_map, cx);
2945 } else if let Some(mut pending) = self.selections.pending_anchor() {
2946 let buffer = self.buffer.read(cx).snapshot(cx);
2947 let head;
2948 let tail;
2949 let mode = self.selections.pending_mode().unwrap();
2950 match &mode {
2951 SelectMode::Character => {
2952 head = position.to_point(&display_map);
2953 tail = pending.tail().to_point(&buffer);
2954 }
2955 SelectMode::Word(original_range) => {
2956 let original_display_range = original_range.start.to_display_point(&display_map)
2957 ..original_range.end.to_display_point(&display_map);
2958 let original_buffer_range = original_display_range.start.to_point(&display_map)
2959 ..original_display_range.end.to_point(&display_map);
2960 if movement::is_inside_word(&display_map, position)
2961 || original_display_range.contains(&position)
2962 {
2963 let word_range = movement::surrounding_word(&display_map, position);
2964 if word_range.start < original_display_range.start {
2965 head = word_range.start.to_point(&display_map);
2966 } else {
2967 head = word_range.end.to_point(&display_map);
2968 }
2969 } else {
2970 head = position.to_point(&display_map);
2971 }
2972
2973 if head <= original_buffer_range.start {
2974 tail = original_buffer_range.end;
2975 } else {
2976 tail = original_buffer_range.start;
2977 }
2978 }
2979 SelectMode::Line(original_range) => {
2980 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2981
2982 let position = display_map
2983 .clip_point(position, Bias::Left)
2984 .to_point(&display_map);
2985 let line_start = display_map.prev_line_boundary(position).0;
2986 let next_line_start = buffer.clip_point(
2987 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2988 Bias::Left,
2989 );
2990
2991 if line_start < original_range.start {
2992 head = line_start
2993 } else {
2994 head = next_line_start
2995 }
2996
2997 if head <= original_range.start {
2998 tail = original_range.end;
2999 } else {
3000 tail = original_range.start;
3001 }
3002 }
3003 SelectMode::All => {
3004 return;
3005 }
3006 };
3007
3008 if head < tail {
3009 pending.start = buffer.anchor_before(head);
3010 pending.end = buffer.anchor_before(tail);
3011 pending.reversed = true;
3012 } else {
3013 pending.start = buffer.anchor_before(tail);
3014 pending.end = buffer.anchor_before(head);
3015 pending.reversed = false;
3016 }
3017
3018 self.change_selections(None, cx, |s| {
3019 s.set_pending(pending, mode);
3020 });
3021 } else {
3022 log::error!("update_selection dispatched with no pending selection");
3023 return;
3024 }
3025
3026 self.apply_scroll_delta(scroll_delta, cx);
3027 cx.notify();
3028 }
3029
3030 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3031 self.columnar_selection_tail.take();
3032 if self.selections.pending_anchor().is_some() {
3033 let selections = self.selections.all::<usize>(cx);
3034 self.change_selections(None, cx, |s| {
3035 s.select(selections);
3036 s.clear_pending();
3037 });
3038 }
3039 }
3040
3041 fn select_columns(
3042 &mut self,
3043 tail: DisplayPoint,
3044 head: DisplayPoint,
3045 goal_column: u32,
3046 display_map: &DisplaySnapshot,
3047 cx: &mut ViewContext<Self>,
3048 ) {
3049 let start_row = cmp::min(tail.row(), head.row());
3050 let end_row = cmp::max(tail.row(), head.row());
3051 let start_column = cmp::min(tail.column(), goal_column);
3052 let end_column = cmp::max(tail.column(), goal_column);
3053 let reversed = start_column < tail.column();
3054
3055 let selection_ranges = (start_row.0..=end_row.0)
3056 .map(DisplayRow)
3057 .filter_map(|row| {
3058 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3059 let start = display_map
3060 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3061 .to_point(display_map);
3062 let end = display_map
3063 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3064 .to_point(display_map);
3065 if reversed {
3066 Some(end..start)
3067 } else {
3068 Some(start..end)
3069 }
3070 } else {
3071 None
3072 }
3073 })
3074 .collect::<Vec<_>>();
3075
3076 self.change_selections(None, cx, |s| {
3077 s.select_ranges(selection_ranges);
3078 });
3079 cx.notify();
3080 }
3081
3082 pub fn has_pending_nonempty_selection(&self) -> bool {
3083 let pending_nonempty_selection = match self.selections.pending_anchor() {
3084 Some(Selection { start, end, .. }) => start != end,
3085 None => false,
3086 };
3087
3088 pending_nonempty_selection
3089 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3090 }
3091
3092 pub fn has_pending_selection(&self) -> bool {
3093 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3094 }
3095
3096 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3097 if self.clear_expanded_diff_hunks(cx) {
3098 cx.notify();
3099 return;
3100 }
3101 if self.dismiss_menus_and_popups(true, cx) {
3102 return;
3103 }
3104
3105 if self.mode == EditorMode::Full
3106 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3107 {
3108 return;
3109 }
3110
3111 cx.propagate();
3112 }
3113
3114 pub fn dismiss_menus_and_popups(
3115 &mut self,
3116 should_report_inline_completion_event: bool,
3117 cx: &mut ViewContext<Self>,
3118 ) -> bool {
3119 if self.take_rename(false, cx).is_some() {
3120 return true;
3121 }
3122
3123 if hide_hover(self, cx) {
3124 return true;
3125 }
3126
3127 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3128 return true;
3129 }
3130
3131 if self.hide_context_menu(cx).is_some() {
3132 return true;
3133 }
3134
3135 if self.mouse_context_menu.take().is_some() {
3136 return true;
3137 }
3138
3139 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3140 return true;
3141 }
3142
3143 if self.snippet_stack.pop().is_some() {
3144 return true;
3145 }
3146
3147 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3148 self.dismiss_diagnostics(cx);
3149 return true;
3150 }
3151
3152 false
3153 }
3154
3155 fn linked_editing_ranges_for(
3156 &self,
3157 selection: Range<text::Anchor>,
3158 cx: &AppContext,
3159 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3160 if self.linked_edit_ranges.is_empty() {
3161 return None;
3162 }
3163 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3164 selection.end.buffer_id.and_then(|end_buffer_id| {
3165 if selection.start.buffer_id != Some(end_buffer_id) {
3166 return None;
3167 }
3168 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3169 let snapshot = buffer.read(cx).snapshot();
3170 self.linked_edit_ranges
3171 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3172 .map(|ranges| (ranges, snapshot, buffer))
3173 })?;
3174 use text::ToOffset as TO;
3175 // find offset from the start of current range to current cursor position
3176 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3177
3178 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3179 let start_difference = start_offset - start_byte_offset;
3180 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3181 let end_difference = end_offset - start_byte_offset;
3182 // Current range has associated linked ranges.
3183 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3184 for range in linked_ranges.iter() {
3185 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3186 let end_offset = start_offset + end_difference;
3187 let start_offset = start_offset + start_difference;
3188 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3189 continue;
3190 }
3191 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3192 if s.start.buffer_id != selection.start.buffer_id
3193 || s.end.buffer_id != selection.end.buffer_id
3194 {
3195 return false;
3196 }
3197 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3198 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3199 }) {
3200 continue;
3201 }
3202 let start = buffer_snapshot.anchor_after(start_offset);
3203 let end = buffer_snapshot.anchor_after(end_offset);
3204 linked_edits
3205 .entry(buffer.clone())
3206 .or_default()
3207 .push(start..end);
3208 }
3209 Some(linked_edits)
3210 }
3211
3212 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3213 let text: Arc<str> = text.into();
3214
3215 if self.read_only(cx) {
3216 return;
3217 }
3218
3219 let selections = self.selections.all_adjusted(cx);
3220 let mut bracket_inserted = false;
3221 let mut edits = Vec::new();
3222 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3223 let mut new_selections = Vec::with_capacity(selections.len());
3224 let mut new_autoclose_regions = Vec::new();
3225 let snapshot = self.buffer.read(cx).read(cx);
3226
3227 for (selection, autoclose_region) in
3228 self.selections_with_autoclose_regions(selections, &snapshot)
3229 {
3230 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3231 // Determine if the inserted text matches the opening or closing
3232 // bracket of any of this language's bracket pairs.
3233 let mut bracket_pair = None;
3234 let mut is_bracket_pair_start = false;
3235 let mut is_bracket_pair_end = false;
3236 if !text.is_empty() {
3237 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3238 // and they are removing the character that triggered IME popup.
3239 for (pair, enabled) in scope.brackets() {
3240 if !pair.close && !pair.surround {
3241 continue;
3242 }
3243
3244 if enabled && pair.start.ends_with(text.as_ref()) {
3245 bracket_pair = Some(pair.clone());
3246 is_bracket_pair_start = true;
3247 break;
3248 }
3249 if pair.end.as_str() == text.as_ref() {
3250 bracket_pair = Some(pair.clone());
3251 is_bracket_pair_end = true;
3252 break;
3253 }
3254 }
3255 }
3256
3257 if let Some(bracket_pair) = bracket_pair {
3258 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3259 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3260 let auto_surround =
3261 self.use_auto_surround && snapshot_settings.use_auto_surround;
3262 if selection.is_empty() {
3263 if is_bracket_pair_start {
3264 let prefix_len = bracket_pair.start.len() - text.len();
3265
3266 // If the inserted text is a suffix of an opening bracket and the
3267 // selection is preceded by the rest of the opening bracket, then
3268 // insert the closing bracket.
3269 let following_text_allows_autoclose = snapshot
3270 .chars_at(selection.start)
3271 .next()
3272 .map_or(true, |c| scope.should_autoclose_before(c));
3273 let preceding_text_matches_prefix = prefix_len == 0
3274 || (selection.start.column >= (prefix_len as u32)
3275 && snapshot.contains_str_at(
3276 Point::new(
3277 selection.start.row,
3278 selection.start.column - (prefix_len as u32),
3279 ),
3280 &bracket_pair.start[..prefix_len],
3281 ));
3282
3283 if autoclose
3284 && bracket_pair.close
3285 && following_text_allows_autoclose
3286 && preceding_text_matches_prefix
3287 {
3288 let anchor = snapshot.anchor_before(selection.end);
3289 new_selections.push((selection.map(|_| anchor), text.len()));
3290 new_autoclose_regions.push((
3291 anchor,
3292 text.len(),
3293 selection.id,
3294 bracket_pair.clone(),
3295 ));
3296 edits.push((
3297 selection.range(),
3298 format!("{}{}", text, bracket_pair.end).into(),
3299 ));
3300 bracket_inserted = true;
3301 continue;
3302 }
3303 }
3304
3305 if let Some(region) = autoclose_region {
3306 // If the selection is followed by an auto-inserted closing bracket,
3307 // then don't insert that closing bracket again; just move the selection
3308 // past the closing bracket.
3309 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3310 && text.as_ref() == region.pair.end.as_str();
3311 if should_skip {
3312 let anchor = snapshot.anchor_after(selection.end);
3313 new_selections
3314 .push((selection.map(|_| anchor), region.pair.end.len()));
3315 continue;
3316 }
3317 }
3318
3319 let always_treat_brackets_as_autoclosed = snapshot
3320 .settings_at(selection.start, cx)
3321 .always_treat_brackets_as_autoclosed;
3322 if always_treat_brackets_as_autoclosed
3323 && is_bracket_pair_end
3324 && snapshot.contains_str_at(selection.end, text.as_ref())
3325 {
3326 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3327 // and the inserted text is a closing bracket and the selection is followed
3328 // by the closing bracket then move the selection past the closing bracket.
3329 let anchor = snapshot.anchor_after(selection.end);
3330 new_selections.push((selection.map(|_| anchor), text.len()));
3331 continue;
3332 }
3333 }
3334 // If an opening bracket is 1 character long and is typed while
3335 // text is selected, then surround that text with the bracket pair.
3336 else if auto_surround
3337 && bracket_pair.surround
3338 && is_bracket_pair_start
3339 && bracket_pair.start.chars().count() == 1
3340 {
3341 edits.push((selection.start..selection.start, text.clone()));
3342 edits.push((
3343 selection.end..selection.end,
3344 bracket_pair.end.as_str().into(),
3345 ));
3346 bracket_inserted = true;
3347 new_selections.push((
3348 Selection {
3349 id: selection.id,
3350 start: snapshot.anchor_after(selection.start),
3351 end: snapshot.anchor_before(selection.end),
3352 reversed: selection.reversed,
3353 goal: selection.goal,
3354 },
3355 0,
3356 ));
3357 continue;
3358 }
3359 }
3360 }
3361
3362 if self.auto_replace_emoji_shortcode
3363 && selection.is_empty()
3364 && text.as_ref().ends_with(':')
3365 {
3366 if let Some(possible_emoji_short_code) =
3367 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3368 {
3369 if !possible_emoji_short_code.is_empty() {
3370 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3371 let emoji_shortcode_start = Point::new(
3372 selection.start.row,
3373 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3374 );
3375
3376 // Remove shortcode from buffer
3377 edits.push((
3378 emoji_shortcode_start..selection.start,
3379 "".to_string().into(),
3380 ));
3381 new_selections.push((
3382 Selection {
3383 id: selection.id,
3384 start: snapshot.anchor_after(emoji_shortcode_start),
3385 end: snapshot.anchor_before(selection.start),
3386 reversed: selection.reversed,
3387 goal: selection.goal,
3388 },
3389 0,
3390 ));
3391
3392 // Insert emoji
3393 let selection_start_anchor = snapshot.anchor_after(selection.start);
3394 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3395 edits.push((selection.start..selection.end, emoji.to_string().into()));
3396
3397 continue;
3398 }
3399 }
3400 }
3401 }
3402
3403 // If not handling any auto-close operation, then just replace the selected
3404 // text with the given input and move the selection to the end of the
3405 // newly inserted text.
3406 let anchor = snapshot.anchor_after(selection.end);
3407 if !self.linked_edit_ranges.is_empty() {
3408 let start_anchor = snapshot.anchor_before(selection.start);
3409
3410 let is_word_char = text.chars().next().map_or(true, |char| {
3411 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3412 classifier.is_word(char)
3413 });
3414
3415 if is_word_char {
3416 if let Some(ranges) = self
3417 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3418 {
3419 for (buffer, edits) in ranges {
3420 linked_edits
3421 .entry(buffer.clone())
3422 .or_default()
3423 .extend(edits.into_iter().map(|range| (range, text.clone())));
3424 }
3425 }
3426 }
3427 }
3428
3429 new_selections.push((selection.map(|_| anchor), 0));
3430 edits.push((selection.start..selection.end, text.clone()));
3431 }
3432
3433 drop(snapshot);
3434
3435 self.transact(cx, |this, cx| {
3436 this.buffer.update(cx, |buffer, cx| {
3437 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3438 });
3439 for (buffer, edits) in linked_edits {
3440 buffer.update(cx, |buffer, cx| {
3441 let snapshot = buffer.snapshot();
3442 let edits = edits
3443 .into_iter()
3444 .map(|(range, text)| {
3445 use text::ToPoint as TP;
3446 let end_point = TP::to_point(&range.end, &snapshot);
3447 let start_point = TP::to_point(&range.start, &snapshot);
3448 (start_point..end_point, text)
3449 })
3450 .sorted_by_key(|(range, _)| range.start)
3451 .collect::<Vec<_>>();
3452 buffer.edit(edits, None, cx);
3453 })
3454 }
3455 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3456 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3457 let snapshot = this.buffer.read(cx).read(cx);
3458 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3459 .zip(new_selection_deltas)
3460 .map(|(selection, delta)| Selection {
3461 id: selection.id,
3462 start: selection.start + delta,
3463 end: selection.end + delta,
3464 reversed: selection.reversed,
3465 goal: SelectionGoal::None,
3466 })
3467 .collect::<Vec<_>>();
3468
3469 let mut i = 0;
3470 for (position, delta, selection_id, pair) in new_autoclose_regions {
3471 let position = position.to_offset(&snapshot) + delta;
3472 let start = snapshot.anchor_before(position);
3473 let end = snapshot.anchor_after(position);
3474 while let Some(existing_state) = this.autoclose_regions.get(i) {
3475 match existing_state.range.start.cmp(&start, &snapshot) {
3476 Ordering::Less => i += 1,
3477 Ordering::Greater => break,
3478 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3479 Ordering::Less => i += 1,
3480 Ordering::Equal => break,
3481 Ordering::Greater => break,
3482 },
3483 }
3484 }
3485 this.autoclose_regions.insert(
3486 i,
3487 AutocloseRegion {
3488 selection_id,
3489 range: start..end,
3490 pair,
3491 },
3492 );
3493 }
3494
3495 drop(snapshot);
3496 let had_active_inline_completion = this.has_active_inline_completion(cx);
3497 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3498 s.select(new_selections)
3499 });
3500
3501 if !bracket_inserted {
3502 if let Some(on_type_format_task) =
3503 this.trigger_on_type_formatting(text.to_string(), cx)
3504 {
3505 on_type_format_task.detach_and_log_err(cx);
3506 }
3507 }
3508
3509 let editor_settings = EditorSettings::get_global(cx);
3510 if bracket_inserted
3511 && (editor_settings.auto_signature_help
3512 || editor_settings.show_signature_help_after_edits)
3513 {
3514 this.show_signature_help(&ShowSignatureHelp, cx);
3515 }
3516
3517 let trigger_in_words = !had_active_inline_completion;
3518 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3519 linked_editing_ranges::refresh_linked_ranges(this, cx);
3520 this.refresh_inline_completion(true, false, cx);
3521 });
3522 }
3523
3524 fn find_possible_emoji_shortcode_at_position(
3525 snapshot: &MultiBufferSnapshot,
3526 position: Point,
3527 ) -> Option<String> {
3528 let mut chars = Vec::new();
3529 let mut found_colon = false;
3530 for char in snapshot.reversed_chars_at(position).take(100) {
3531 // Found a possible emoji shortcode in the middle of the buffer
3532 if found_colon {
3533 if char.is_whitespace() {
3534 chars.reverse();
3535 return Some(chars.iter().collect());
3536 }
3537 // If the previous character is not a whitespace, we are in the middle of a word
3538 // and we only want to complete the shortcode if the word is made up of other emojis
3539 let mut containing_word = String::new();
3540 for ch in snapshot
3541 .reversed_chars_at(position)
3542 .skip(chars.len() + 1)
3543 .take(100)
3544 {
3545 if ch.is_whitespace() {
3546 break;
3547 }
3548 containing_word.push(ch);
3549 }
3550 let containing_word = containing_word.chars().rev().collect::<String>();
3551 if util::word_consists_of_emojis(containing_word.as_str()) {
3552 chars.reverse();
3553 return Some(chars.iter().collect());
3554 }
3555 }
3556
3557 if char.is_whitespace() || !char.is_ascii() {
3558 return None;
3559 }
3560 if char == ':' {
3561 found_colon = true;
3562 } else {
3563 chars.push(char);
3564 }
3565 }
3566 // Found a possible emoji shortcode at the beginning of the buffer
3567 chars.reverse();
3568 Some(chars.iter().collect())
3569 }
3570
3571 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3572 self.transact(cx, |this, cx| {
3573 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3574 let selections = this.selections.all::<usize>(cx);
3575 let multi_buffer = this.buffer.read(cx);
3576 let buffer = multi_buffer.snapshot(cx);
3577 selections
3578 .iter()
3579 .map(|selection| {
3580 let start_point = selection.start.to_point(&buffer);
3581 let mut indent =
3582 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3583 indent.len = cmp::min(indent.len, start_point.column);
3584 let start = selection.start;
3585 let end = selection.end;
3586 let selection_is_empty = start == end;
3587 let language_scope = buffer.language_scope_at(start);
3588 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3589 &language_scope
3590 {
3591 let leading_whitespace_len = buffer
3592 .reversed_chars_at(start)
3593 .take_while(|c| c.is_whitespace() && *c != '\n')
3594 .map(|c| c.len_utf8())
3595 .sum::<usize>();
3596
3597 let trailing_whitespace_len = buffer
3598 .chars_at(end)
3599 .take_while(|c| c.is_whitespace() && *c != '\n')
3600 .map(|c| c.len_utf8())
3601 .sum::<usize>();
3602
3603 let insert_extra_newline =
3604 language.brackets().any(|(pair, enabled)| {
3605 let pair_start = pair.start.trim_end();
3606 let pair_end = pair.end.trim_start();
3607
3608 enabled
3609 && pair.newline
3610 && buffer.contains_str_at(
3611 end + trailing_whitespace_len,
3612 pair_end,
3613 )
3614 && buffer.contains_str_at(
3615 (start - leading_whitespace_len)
3616 .saturating_sub(pair_start.len()),
3617 pair_start,
3618 )
3619 });
3620
3621 // Comment extension on newline is allowed only for cursor selections
3622 let comment_delimiter = maybe!({
3623 if !selection_is_empty {
3624 return None;
3625 }
3626
3627 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3628 return None;
3629 }
3630
3631 let delimiters = language.line_comment_prefixes();
3632 let max_len_of_delimiter =
3633 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3634 let (snapshot, range) =
3635 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3636
3637 let mut index_of_first_non_whitespace = 0;
3638 let comment_candidate = snapshot
3639 .chars_for_range(range)
3640 .skip_while(|c| {
3641 let should_skip = c.is_whitespace();
3642 if should_skip {
3643 index_of_first_non_whitespace += 1;
3644 }
3645 should_skip
3646 })
3647 .take(max_len_of_delimiter)
3648 .collect::<String>();
3649 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3650 comment_candidate.starts_with(comment_prefix.as_ref())
3651 })?;
3652 let cursor_is_placed_after_comment_marker =
3653 index_of_first_non_whitespace + comment_prefix.len()
3654 <= start_point.column as usize;
3655 if cursor_is_placed_after_comment_marker {
3656 Some(comment_prefix.clone())
3657 } else {
3658 None
3659 }
3660 });
3661 (comment_delimiter, insert_extra_newline)
3662 } else {
3663 (None, false)
3664 };
3665
3666 let capacity_for_delimiter = comment_delimiter
3667 .as_deref()
3668 .map(str::len)
3669 .unwrap_or_default();
3670 let mut new_text =
3671 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3672 new_text.push('\n');
3673 new_text.extend(indent.chars());
3674 if let Some(delimiter) = &comment_delimiter {
3675 new_text.push_str(delimiter);
3676 }
3677 if insert_extra_newline {
3678 new_text = new_text.repeat(2);
3679 }
3680
3681 let anchor = buffer.anchor_after(end);
3682 let new_selection = selection.map(|_| anchor);
3683 (
3684 (start..end, new_text),
3685 (insert_extra_newline, new_selection),
3686 )
3687 })
3688 .unzip()
3689 };
3690
3691 this.edit_with_autoindent(edits, cx);
3692 let buffer = this.buffer.read(cx).snapshot(cx);
3693 let new_selections = selection_fixup_info
3694 .into_iter()
3695 .map(|(extra_newline_inserted, new_selection)| {
3696 let mut cursor = new_selection.end.to_point(&buffer);
3697 if extra_newline_inserted {
3698 cursor.row -= 1;
3699 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3700 }
3701 new_selection.map(|_| cursor)
3702 })
3703 .collect();
3704
3705 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3706 this.refresh_inline_completion(true, false, cx);
3707 });
3708 }
3709
3710 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3711 let buffer = self.buffer.read(cx);
3712 let snapshot = buffer.snapshot(cx);
3713
3714 let mut edits = Vec::new();
3715 let mut rows = Vec::new();
3716
3717 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3718 let cursor = selection.head();
3719 let row = cursor.row;
3720
3721 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3722
3723 let newline = "\n".to_string();
3724 edits.push((start_of_line..start_of_line, newline));
3725
3726 rows.push(row + rows_inserted as u32);
3727 }
3728
3729 self.transact(cx, |editor, cx| {
3730 editor.edit(edits, cx);
3731
3732 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3733 let mut index = 0;
3734 s.move_cursors_with(|map, _, _| {
3735 let row = rows[index];
3736 index += 1;
3737
3738 let point = Point::new(row, 0);
3739 let boundary = map.next_line_boundary(point).1;
3740 let clipped = map.clip_point(boundary, Bias::Left);
3741
3742 (clipped, SelectionGoal::None)
3743 });
3744 });
3745
3746 let mut indent_edits = Vec::new();
3747 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3748 for row in rows {
3749 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3750 for (row, indent) in indents {
3751 if indent.len == 0 {
3752 continue;
3753 }
3754
3755 let text = match indent.kind {
3756 IndentKind::Space => " ".repeat(indent.len as usize),
3757 IndentKind::Tab => "\t".repeat(indent.len as usize),
3758 };
3759 let point = Point::new(row.0, 0);
3760 indent_edits.push((point..point, text));
3761 }
3762 }
3763 editor.edit(indent_edits, cx);
3764 });
3765 }
3766
3767 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3768 let buffer = self.buffer.read(cx);
3769 let snapshot = buffer.snapshot(cx);
3770
3771 let mut edits = Vec::new();
3772 let mut rows = Vec::new();
3773 let mut rows_inserted = 0;
3774
3775 for selection in self.selections.all_adjusted(cx) {
3776 let cursor = selection.head();
3777 let row = cursor.row;
3778
3779 let point = Point::new(row + 1, 0);
3780 let start_of_line = snapshot.clip_point(point, Bias::Left);
3781
3782 let newline = "\n".to_string();
3783 edits.push((start_of_line..start_of_line, newline));
3784
3785 rows_inserted += 1;
3786 rows.push(row + rows_inserted);
3787 }
3788
3789 self.transact(cx, |editor, cx| {
3790 editor.edit(edits, cx);
3791
3792 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3793 let mut index = 0;
3794 s.move_cursors_with(|map, _, _| {
3795 let row = rows[index];
3796 index += 1;
3797
3798 let point = Point::new(row, 0);
3799 let boundary = map.next_line_boundary(point).1;
3800 let clipped = map.clip_point(boundary, Bias::Left);
3801
3802 (clipped, SelectionGoal::None)
3803 });
3804 });
3805
3806 let mut indent_edits = Vec::new();
3807 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3808 for row in rows {
3809 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3810 for (row, indent) in indents {
3811 if indent.len == 0 {
3812 continue;
3813 }
3814
3815 let text = match indent.kind {
3816 IndentKind::Space => " ".repeat(indent.len as usize),
3817 IndentKind::Tab => "\t".repeat(indent.len as usize),
3818 };
3819 let point = Point::new(row.0, 0);
3820 indent_edits.push((point..point, text));
3821 }
3822 }
3823 editor.edit(indent_edits, cx);
3824 });
3825 }
3826
3827 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3828 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3829 original_indent_columns: Vec::new(),
3830 });
3831 self.insert_with_autoindent_mode(text, autoindent, cx);
3832 }
3833
3834 fn insert_with_autoindent_mode(
3835 &mut self,
3836 text: &str,
3837 autoindent_mode: Option<AutoindentMode>,
3838 cx: &mut ViewContext<Self>,
3839 ) {
3840 if self.read_only(cx) {
3841 return;
3842 }
3843
3844 let text: Arc<str> = text.into();
3845 self.transact(cx, |this, cx| {
3846 let old_selections = this.selections.all_adjusted(cx);
3847 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3848 let anchors = {
3849 let snapshot = buffer.read(cx);
3850 old_selections
3851 .iter()
3852 .map(|s| {
3853 let anchor = snapshot.anchor_after(s.head());
3854 s.map(|_| anchor)
3855 })
3856 .collect::<Vec<_>>()
3857 };
3858 buffer.edit(
3859 old_selections
3860 .iter()
3861 .map(|s| (s.start..s.end, text.clone())),
3862 autoindent_mode,
3863 cx,
3864 );
3865 anchors
3866 });
3867
3868 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3869 s.select_anchors(selection_anchors);
3870 })
3871 });
3872 }
3873
3874 fn trigger_completion_on_input(
3875 &mut self,
3876 text: &str,
3877 trigger_in_words: bool,
3878 cx: &mut ViewContext<Self>,
3879 ) {
3880 if self.is_completion_trigger(text, trigger_in_words, cx) {
3881 self.show_completions(
3882 &ShowCompletions {
3883 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3884 },
3885 cx,
3886 );
3887 } else {
3888 self.hide_context_menu(cx);
3889 }
3890 }
3891
3892 fn is_completion_trigger(
3893 &self,
3894 text: &str,
3895 trigger_in_words: bool,
3896 cx: &mut ViewContext<Self>,
3897 ) -> bool {
3898 let position = self.selections.newest_anchor().head();
3899 let multibuffer = self.buffer.read(cx);
3900 let Some(buffer) = position
3901 .buffer_id
3902 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3903 else {
3904 return false;
3905 };
3906
3907 if let Some(completion_provider) = &self.completion_provider {
3908 completion_provider.is_completion_trigger(
3909 &buffer,
3910 position.text_anchor,
3911 text,
3912 trigger_in_words,
3913 cx,
3914 )
3915 } else {
3916 false
3917 }
3918 }
3919
3920 /// If any empty selections is touching the start of its innermost containing autoclose
3921 /// region, expand it to select the brackets.
3922 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3923 let selections = self.selections.all::<usize>(cx);
3924 let buffer = self.buffer.read(cx).read(cx);
3925 let new_selections = self
3926 .selections_with_autoclose_regions(selections, &buffer)
3927 .map(|(mut selection, region)| {
3928 if !selection.is_empty() {
3929 return selection;
3930 }
3931
3932 if let Some(region) = region {
3933 let mut range = region.range.to_offset(&buffer);
3934 if selection.start == range.start && range.start >= region.pair.start.len() {
3935 range.start -= region.pair.start.len();
3936 if buffer.contains_str_at(range.start, ®ion.pair.start)
3937 && buffer.contains_str_at(range.end, ®ion.pair.end)
3938 {
3939 range.end += region.pair.end.len();
3940 selection.start = range.start;
3941 selection.end = range.end;
3942
3943 return selection;
3944 }
3945 }
3946 }
3947
3948 let always_treat_brackets_as_autoclosed = buffer
3949 .settings_at(selection.start, cx)
3950 .always_treat_brackets_as_autoclosed;
3951
3952 if !always_treat_brackets_as_autoclosed {
3953 return selection;
3954 }
3955
3956 if let Some(scope) = buffer.language_scope_at(selection.start) {
3957 for (pair, enabled) in scope.brackets() {
3958 if !enabled || !pair.close {
3959 continue;
3960 }
3961
3962 if buffer.contains_str_at(selection.start, &pair.end) {
3963 let pair_start_len = pair.start.len();
3964 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3965 {
3966 selection.start -= pair_start_len;
3967 selection.end += pair.end.len();
3968
3969 return selection;
3970 }
3971 }
3972 }
3973 }
3974
3975 selection
3976 })
3977 .collect();
3978
3979 drop(buffer);
3980 self.change_selections(None, cx, |selections| selections.select(new_selections));
3981 }
3982
3983 /// Iterate the given selections, and for each one, find the smallest surrounding
3984 /// autoclose region. This uses the ordering of the selections and the autoclose
3985 /// regions to avoid repeated comparisons.
3986 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3987 &'a self,
3988 selections: impl IntoIterator<Item = Selection<D>>,
3989 buffer: &'a MultiBufferSnapshot,
3990 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3991 let mut i = 0;
3992 let mut regions = self.autoclose_regions.as_slice();
3993 selections.into_iter().map(move |selection| {
3994 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3995
3996 let mut enclosing = None;
3997 while let Some(pair_state) = regions.get(i) {
3998 if pair_state.range.end.to_offset(buffer) < range.start {
3999 regions = ®ions[i + 1..];
4000 i = 0;
4001 } else if pair_state.range.start.to_offset(buffer) > range.end {
4002 break;
4003 } else {
4004 if pair_state.selection_id == selection.id {
4005 enclosing = Some(pair_state);
4006 }
4007 i += 1;
4008 }
4009 }
4010
4011 (selection.clone(), enclosing)
4012 })
4013 }
4014
4015 /// Remove any autoclose regions that no longer contain their selection.
4016 fn invalidate_autoclose_regions(
4017 &mut self,
4018 mut selections: &[Selection<Anchor>],
4019 buffer: &MultiBufferSnapshot,
4020 ) {
4021 self.autoclose_regions.retain(|state| {
4022 let mut i = 0;
4023 while let Some(selection) = selections.get(i) {
4024 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4025 selections = &selections[1..];
4026 continue;
4027 }
4028 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4029 break;
4030 }
4031 if selection.id == state.selection_id {
4032 return true;
4033 } else {
4034 i += 1;
4035 }
4036 }
4037 false
4038 });
4039 }
4040
4041 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4042 let offset = position.to_offset(buffer);
4043 let (word_range, kind) = buffer.surrounding_word(offset, true);
4044 if offset > word_range.start && kind == Some(CharKind::Word) {
4045 Some(
4046 buffer
4047 .text_for_range(word_range.start..offset)
4048 .collect::<String>(),
4049 )
4050 } else {
4051 None
4052 }
4053 }
4054
4055 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4056 self.refresh_inlay_hints(
4057 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4058 cx,
4059 );
4060 }
4061
4062 pub fn inlay_hints_enabled(&self) -> bool {
4063 self.inlay_hint_cache.enabled
4064 }
4065
4066 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4067 if self.semantics_provider.is_none() || self.mode != EditorMode::Full {
4068 return;
4069 }
4070
4071 let reason_description = reason.description();
4072 let ignore_debounce = matches!(
4073 reason,
4074 InlayHintRefreshReason::SettingsChange(_)
4075 | InlayHintRefreshReason::Toggle(_)
4076 | InlayHintRefreshReason::ExcerptsRemoved(_)
4077 );
4078 let (invalidate_cache, required_languages) = match reason {
4079 InlayHintRefreshReason::Toggle(enabled) => {
4080 self.inlay_hint_cache.enabled = enabled;
4081 if enabled {
4082 (InvalidationStrategy::RefreshRequested, None)
4083 } else {
4084 self.inlay_hint_cache.clear();
4085 self.splice_inlays(
4086 self.visible_inlay_hints(cx)
4087 .iter()
4088 .map(|inlay| inlay.id)
4089 .collect(),
4090 Vec::new(),
4091 cx,
4092 );
4093 return;
4094 }
4095 }
4096 InlayHintRefreshReason::SettingsChange(new_settings) => {
4097 match self.inlay_hint_cache.update_settings(
4098 &self.buffer,
4099 new_settings,
4100 self.visible_inlay_hints(cx),
4101 cx,
4102 ) {
4103 ControlFlow::Break(Some(InlaySplice {
4104 to_remove,
4105 to_insert,
4106 })) => {
4107 self.splice_inlays(to_remove, to_insert, cx);
4108 return;
4109 }
4110 ControlFlow::Break(None) => return,
4111 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4112 }
4113 }
4114 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4115 if let Some(InlaySplice {
4116 to_remove,
4117 to_insert,
4118 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4119 {
4120 self.splice_inlays(to_remove, to_insert, cx);
4121 }
4122 return;
4123 }
4124 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4125 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4126 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4127 }
4128 InlayHintRefreshReason::RefreshRequested => {
4129 (InvalidationStrategy::RefreshRequested, None)
4130 }
4131 };
4132
4133 if let Some(InlaySplice {
4134 to_remove,
4135 to_insert,
4136 }) = self.inlay_hint_cache.spawn_hint_refresh(
4137 reason_description,
4138 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4139 invalidate_cache,
4140 ignore_debounce,
4141 cx,
4142 ) {
4143 self.splice_inlays(to_remove, to_insert, cx);
4144 }
4145 }
4146
4147 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4148 self.display_map
4149 .read(cx)
4150 .current_inlays()
4151 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4152 .cloned()
4153 .collect()
4154 }
4155
4156 pub fn excerpts_for_inlay_hints_query(
4157 &self,
4158 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4159 cx: &mut ViewContext<Editor>,
4160 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4161 let Some(project) = self.project.as_ref() else {
4162 return HashMap::default();
4163 };
4164 let project = project.read(cx);
4165 let multi_buffer = self.buffer().read(cx);
4166 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4167 let multi_buffer_visible_start = self
4168 .scroll_manager
4169 .anchor()
4170 .anchor
4171 .to_point(&multi_buffer_snapshot);
4172 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4173 multi_buffer_visible_start
4174 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4175 Bias::Left,
4176 );
4177 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4178 multi_buffer
4179 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4180 .into_iter()
4181 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4182 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4183 let buffer = buffer_handle.read(cx);
4184 let buffer_file = project::File::from_dyn(buffer.file())?;
4185 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4186 let worktree_entry = buffer_worktree
4187 .read(cx)
4188 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4189 if worktree_entry.is_ignored {
4190 return None;
4191 }
4192
4193 let language = buffer.language()?;
4194 if let Some(restrict_to_languages) = restrict_to_languages {
4195 if !restrict_to_languages.contains(language) {
4196 return None;
4197 }
4198 }
4199 Some((
4200 excerpt_id,
4201 (
4202 buffer_handle,
4203 buffer.version().clone(),
4204 excerpt_visible_range,
4205 ),
4206 ))
4207 })
4208 .collect()
4209 }
4210
4211 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4212 TextLayoutDetails {
4213 text_system: cx.text_system().clone(),
4214 editor_style: self.style.clone().unwrap(),
4215 rem_size: cx.rem_size(),
4216 scroll_anchor: self.scroll_manager.anchor(),
4217 visible_rows: self.visible_line_count(),
4218 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4219 }
4220 }
4221
4222 fn splice_inlays(
4223 &self,
4224 to_remove: Vec<InlayId>,
4225 to_insert: Vec<Inlay>,
4226 cx: &mut ViewContext<Self>,
4227 ) {
4228 self.display_map.update(cx, |display_map, cx| {
4229 display_map.splice_inlays(to_remove, to_insert, cx);
4230 });
4231 cx.notify();
4232 }
4233
4234 fn trigger_on_type_formatting(
4235 &self,
4236 input: String,
4237 cx: &mut ViewContext<Self>,
4238 ) -> Option<Task<Result<()>>> {
4239 if input.len() != 1 {
4240 return None;
4241 }
4242
4243 let project = self.project.as_ref()?;
4244 let position = self.selections.newest_anchor().head();
4245 let (buffer, buffer_position) = self
4246 .buffer
4247 .read(cx)
4248 .text_anchor_for_position(position, cx)?;
4249
4250 let settings = language_settings::language_settings(
4251 buffer.read(cx).language_at(buffer_position).as_ref(),
4252 buffer.read(cx).file(),
4253 cx,
4254 );
4255 if !settings.use_on_type_format {
4256 return None;
4257 }
4258
4259 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4260 // hence we do LSP request & edit on host side only — add formats to host's history.
4261 let push_to_lsp_host_history = true;
4262 // If this is not the host, append its history with new edits.
4263 let push_to_client_history = project.read(cx).is_via_collab();
4264
4265 let on_type_formatting = project.update(cx, |project, cx| {
4266 project.on_type_format(
4267 buffer.clone(),
4268 buffer_position,
4269 input,
4270 push_to_lsp_host_history,
4271 cx,
4272 )
4273 });
4274 Some(cx.spawn(|editor, mut cx| async move {
4275 if let Some(transaction) = on_type_formatting.await? {
4276 if push_to_client_history {
4277 buffer
4278 .update(&mut cx, |buffer, _| {
4279 buffer.push_transaction(transaction, Instant::now());
4280 })
4281 .ok();
4282 }
4283 editor.update(&mut cx, |editor, cx| {
4284 editor.refresh_document_highlights(cx);
4285 })?;
4286 }
4287 Ok(())
4288 }))
4289 }
4290
4291 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4292 if self.pending_rename.is_some() {
4293 return;
4294 }
4295
4296 let Some(provider) = self.completion_provider.as_ref() else {
4297 return;
4298 };
4299
4300 let position = self.selections.newest_anchor().head();
4301 let (buffer, buffer_position) =
4302 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4303 output
4304 } else {
4305 return;
4306 };
4307
4308 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4309 let is_followup_invoke = {
4310 let context_menu_state = self.context_menu.read();
4311 matches!(
4312 context_menu_state.deref(),
4313 Some(ContextMenu::Completions(_))
4314 )
4315 };
4316 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4317 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4318 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4319 CompletionTriggerKind::TRIGGER_CHARACTER
4320 }
4321
4322 _ => CompletionTriggerKind::INVOKED,
4323 };
4324 let completion_context = CompletionContext {
4325 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4326 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4327 Some(String::from(trigger))
4328 } else {
4329 None
4330 }
4331 }),
4332 trigger_kind,
4333 };
4334 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4335 let sort_completions = provider.sort_completions();
4336
4337 let id = post_inc(&mut self.next_completion_id);
4338 let task = cx.spawn(|this, mut cx| {
4339 async move {
4340 this.update(&mut cx, |this, _| {
4341 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4342 })?;
4343 let completions = completions.await.log_err();
4344 let menu = if let Some(completions) = completions {
4345 let mut menu = CompletionsMenu {
4346 id,
4347 sort_completions,
4348 initial_position: position,
4349 match_candidates: completions
4350 .iter()
4351 .enumerate()
4352 .map(|(id, completion)| {
4353 StringMatchCandidate::new(
4354 id,
4355 completion.label.text[completion.label.filter_range.clone()]
4356 .into(),
4357 )
4358 })
4359 .collect(),
4360 buffer: buffer.clone(),
4361 completions: Arc::new(RwLock::new(completions.into())),
4362 matches: Vec::new().into(),
4363 selected_item: 0,
4364 scroll_handle: UniformListScrollHandle::new(),
4365 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4366 DebouncedDelay::new(),
4367 )),
4368 };
4369 menu.filter(query.as_deref(), cx.background_executor().clone())
4370 .await;
4371
4372 if menu.matches.is_empty() {
4373 None
4374 } else {
4375 this.update(&mut cx, |editor, cx| {
4376 let completions = menu.completions.clone();
4377 let matches = menu.matches.clone();
4378
4379 let delay_ms = EditorSettings::get_global(cx)
4380 .completion_documentation_secondary_query_debounce;
4381 let delay = Duration::from_millis(delay_ms);
4382 editor
4383 .completion_documentation_pre_resolve_debounce
4384 .fire_new(delay, cx, |editor, cx| {
4385 CompletionsMenu::pre_resolve_completion_documentation(
4386 buffer,
4387 completions,
4388 matches,
4389 editor,
4390 cx,
4391 )
4392 });
4393 })
4394 .ok();
4395 Some(menu)
4396 }
4397 } else {
4398 None
4399 };
4400
4401 this.update(&mut cx, |this, cx| {
4402 let mut context_menu = this.context_menu.write();
4403 match context_menu.as_ref() {
4404 None => {}
4405
4406 Some(ContextMenu::Completions(prev_menu)) => {
4407 if prev_menu.id > id {
4408 return;
4409 }
4410 }
4411
4412 _ => return,
4413 }
4414
4415 if this.focus_handle.is_focused(cx) && menu.is_some() {
4416 let menu = menu.unwrap();
4417 *context_menu = Some(ContextMenu::Completions(menu));
4418 drop(context_menu);
4419 this.discard_inline_completion(false, cx);
4420 cx.notify();
4421 } else if this.completion_tasks.len() <= 1 {
4422 // If there are no more completion tasks and the last menu was
4423 // empty, we should hide it. If it was already hidden, we should
4424 // also show the copilot completion when available.
4425 drop(context_menu);
4426 if this.hide_context_menu(cx).is_none() {
4427 this.update_visible_inline_completion(cx);
4428 }
4429 }
4430 })?;
4431
4432 Ok::<_, anyhow::Error>(())
4433 }
4434 .log_err()
4435 });
4436
4437 self.completion_tasks.push((id, task));
4438 }
4439
4440 pub fn confirm_completion(
4441 &mut self,
4442 action: &ConfirmCompletion,
4443 cx: &mut ViewContext<Self>,
4444 ) -> Option<Task<Result<()>>> {
4445 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4446 }
4447
4448 pub fn compose_completion(
4449 &mut self,
4450 action: &ComposeCompletion,
4451 cx: &mut ViewContext<Self>,
4452 ) -> Option<Task<Result<()>>> {
4453 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4454 }
4455
4456 fn do_completion(
4457 &mut self,
4458 item_ix: Option<usize>,
4459 intent: CompletionIntent,
4460 cx: &mut ViewContext<Editor>,
4461 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4462 use language::ToOffset as _;
4463
4464 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4465 menu
4466 } else {
4467 return None;
4468 };
4469
4470 let mat = completions_menu
4471 .matches
4472 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4473 let buffer_handle = completions_menu.buffer;
4474 let completions = completions_menu.completions.read();
4475 let completion = completions.get(mat.candidate_id)?;
4476 cx.stop_propagation();
4477
4478 let snippet;
4479 let text;
4480
4481 if completion.is_snippet() {
4482 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4483 text = snippet.as_ref().unwrap().text.clone();
4484 } else {
4485 snippet = None;
4486 text = completion.new_text.clone();
4487 };
4488 let selections = self.selections.all::<usize>(cx);
4489 let buffer = buffer_handle.read(cx);
4490 let old_range = completion.old_range.to_offset(buffer);
4491 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4492
4493 let newest_selection = self.selections.newest_anchor();
4494 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4495 return None;
4496 }
4497
4498 let lookbehind = newest_selection
4499 .start
4500 .text_anchor
4501 .to_offset(buffer)
4502 .saturating_sub(old_range.start);
4503 let lookahead = old_range
4504 .end
4505 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4506 let mut common_prefix_len = old_text
4507 .bytes()
4508 .zip(text.bytes())
4509 .take_while(|(a, b)| a == b)
4510 .count();
4511
4512 let snapshot = self.buffer.read(cx).snapshot(cx);
4513 let mut range_to_replace: Option<Range<isize>> = None;
4514 let mut ranges = Vec::new();
4515 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4516 for selection in &selections {
4517 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4518 let start = selection.start.saturating_sub(lookbehind);
4519 let end = selection.end + lookahead;
4520 if selection.id == newest_selection.id {
4521 range_to_replace = Some(
4522 ((start + common_prefix_len) as isize - selection.start as isize)
4523 ..(end as isize - selection.start as isize),
4524 );
4525 }
4526 ranges.push(start + common_prefix_len..end);
4527 } else {
4528 common_prefix_len = 0;
4529 ranges.clear();
4530 ranges.extend(selections.iter().map(|s| {
4531 if s.id == newest_selection.id {
4532 range_to_replace = Some(
4533 old_range.start.to_offset_utf16(&snapshot).0 as isize
4534 - selection.start as isize
4535 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4536 - selection.start as isize,
4537 );
4538 old_range.clone()
4539 } else {
4540 s.start..s.end
4541 }
4542 }));
4543 break;
4544 }
4545 if !self.linked_edit_ranges.is_empty() {
4546 let start_anchor = snapshot.anchor_before(selection.head());
4547 let end_anchor = snapshot.anchor_after(selection.tail());
4548 if let Some(ranges) = self
4549 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4550 {
4551 for (buffer, edits) in ranges {
4552 linked_edits.entry(buffer.clone()).or_default().extend(
4553 edits
4554 .into_iter()
4555 .map(|range| (range, text[common_prefix_len..].to_owned())),
4556 );
4557 }
4558 }
4559 }
4560 }
4561 let text = &text[common_prefix_len..];
4562
4563 cx.emit(EditorEvent::InputHandled {
4564 utf16_range_to_replace: range_to_replace,
4565 text: text.into(),
4566 });
4567
4568 self.transact(cx, |this, cx| {
4569 if let Some(mut snippet) = snippet {
4570 snippet.text = text.to_string();
4571 for tabstop in snippet.tabstops.iter_mut().flatten() {
4572 tabstop.start -= common_prefix_len as isize;
4573 tabstop.end -= common_prefix_len as isize;
4574 }
4575
4576 this.insert_snippet(&ranges, snippet, cx).log_err();
4577 } else {
4578 this.buffer.update(cx, |buffer, cx| {
4579 buffer.edit(
4580 ranges.iter().map(|range| (range.clone(), text)),
4581 this.autoindent_mode.clone(),
4582 cx,
4583 );
4584 });
4585 }
4586 for (buffer, edits) in linked_edits {
4587 buffer.update(cx, |buffer, cx| {
4588 let snapshot = buffer.snapshot();
4589 let edits = edits
4590 .into_iter()
4591 .map(|(range, text)| {
4592 use text::ToPoint as TP;
4593 let end_point = TP::to_point(&range.end, &snapshot);
4594 let start_point = TP::to_point(&range.start, &snapshot);
4595 (start_point..end_point, text)
4596 })
4597 .sorted_by_key(|(range, _)| range.start)
4598 .collect::<Vec<_>>();
4599 buffer.edit(edits, None, cx);
4600 })
4601 }
4602
4603 this.refresh_inline_completion(true, false, cx);
4604 });
4605
4606 let show_new_completions_on_confirm = completion
4607 .confirm
4608 .as_ref()
4609 .map_or(false, |confirm| confirm(intent, cx));
4610 if show_new_completions_on_confirm {
4611 self.show_completions(&ShowCompletions { trigger: None }, cx);
4612 }
4613
4614 let provider = self.completion_provider.as_ref()?;
4615 let apply_edits = provider.apply_additional_edits_for_completion(
4616 buffer_handle,
4617 completion.clone(),
4618 true,
4619 cx,
4620 );
4621
4622 let editor_settings = EditorSettings::get_global(cx);
4623 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4624 // After the code completion is finished, users often want to know what signatures are needed.
4625 // so we should automatically call signature_help
4626 self.show_signature_help(&ShowSignatureHelp, cx);
4627 }
4628
4629 Some(cx.foreground_executor().spawn(async move {
4630 apply_edits.await?;
4631 Ok(())
4632 }))
4633 }
4634
4635 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4636 let mut context_menu = self.context_menu.write();
4637 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4638 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4639 // Toggle if we're selecting the same one
4640 *context_menu = None;
4641 cx.notify();
4642 return;
4643 } else {
4644 // Otherwise, clear it and start a new one
4645 *context_menu = None;
4646 cx.notify();
4647 }
4648 }
4649 drop(context_menu);
4650 let snapshot = self.snapshot(cx);
4651 let deployed_from_indicator = action.deployed_from_indicator;
4652 let mut task = self.code_actions_task.take();
4653 let action = action.clone();
4654 cx.spawn(|editor, mut cx| async move {
4655 while let Some(prev_task) = task {
4656 prev_task.await.log_err();
4657 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4658 }
4659
4660 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4661 if editor.focus_handle.is_focused(cx) {
4662 let multibuffer_point = action
4663 .deployed_from_indicator
4664 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4665 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4666 let (buffer, buffer_row) = snapshot
4667 .buffer_snapshot
4668 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4669 .and_then(|(buffer_snapshot, range)| {
4670 editor
4671 .buffer
4672 .read(cx)
4673 .buffer(buffer_snapshot.remote_id())
4674 .map(|buffer| (buffer, range.start.row))
4675 })?;
4676 let (_, code_actions) = editor
4677 .available_code_actions
4678 .clone()
4679 .and_then(|(location, code_actions)| {
4680 let snapshot = location.buffer.read(cx).snapshot();
4681 let point_range = location.range.to_point(&snapshot);
4682 let point_range = point_range.start.row..=point_range.end.row;
4683 if point_range.contains(&buffer_row) {
4684 Some((location, code_actions))
4685 } else {
4686 None
4687 }
4688 })
4689 .unzip();
4690 let buffer_id = buffer.read(cx).remote_id();
4691 let tasks = editor
4692 .tasks
4693 .get(&(buffer_id, buffer_row))
4694 .map(|t| Arc::new(t.to_owned()));
4695 if tasks.is_none() && code_actions.is_none() {
4696 return None;
4697 }
4698
4699 editor.completion_tasks.clear();
4700 editor.discard_inline_completion(false, cx);
4701 let task_context =
4702 tasks
4703 .as_ref()
4704 .zip(editor.project.clone())
4705 .map(|(tasks, project)| {
4706 let position = Point::new(buffer_row, tasks.column);
4707 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4708 let location = Location {
4709 buffer: buffer.clone(),
4710 range: range_start..range_start,
4711 };
4712 // Fill in the environmental variables from the tree-sitter captures
4713 let mut captured_task_variables = TaskVariables::default();
4714 for (capture_name, value) in tasks.extra_variables.clone() {
4715 captured_task_variables.insert(
4716 task::VariableName::Custom(capture_name.into()),
4717 value.clone(),
4718 );
4719 }
4720 project.update(cx, |project, cx| {
4721 project.task_store().update(cx, |task_store, cx| {
4722 task_store.task_context_for_location(
4723 captured_task_variables,
4724 location,
4725 cx,
4726 )
4727 })
4728 })
4729 });
4730
4731 Some(cx.spawn(|editor, mut cx| async move {
4732 let task_context = match task_context {
4733 Some(task_context) => task_context.await,
4734 None => None,
4735 };
4736 let resolved_tasks =
4737 tasks.zip(task_context).map(|(tasks, task_context)| {
4738 Arc::new(ResolvedTasks {
4739 templates: tasks
4740 .templates
4741 .iter()
4742 .filter_map(|(kind, template)| {
4743 template
4744 .resolve_task(&kind.to_id_base(), &task_context)
4745 .map(|task| (kind.clone(), task))
4746 })
4747 .collect(),
4748 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4749 multibuffer_point.row,
4750 tasks.column,
4751 )),
4752 })
4753 });
4754 let spawn_straight_away = resolved_tasks
4755 .as_ref()
4756 .map_or(false, |tasks| tasks.templates.len() == 1)
4757 && code_actions
4758 .as_ref()
4759 .map_or(true, |actions| actions.is_empty());
4760 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4761 *editor.context_menu.write() =
4762 Some(ContextMenu::CodeActions(CodeActionsMenu {
4763 buffer,
4764 actions: CodeActionContents {
4765 tasks: resolved_tasks,
4766 actions: code_actions,
4767 },
4768 selected_item: Default::default(),
4769 scroll_handle: UniformListScrollHandle::default(),
4770 deployed_from_indicator,
4771 }));
4772 if spawn_straight_away {
4773 if let Some(task) = editor.confirm_code_action(
4774 &ConfirmCodeAction { item_ix: Some(0) },
4775 cx,
4776 ) {
4777 cx.notify();
4778 return task;
4779 }
4780 }
4781 cx.notify();
4782 Task::ready(Ok(()))
4783 }) {
4784 task.await
4785 } else {
4786 Ok(())
4787 }
4788 }))
4789 } else {
4790 Some(Task::ready(Ok(())))
4791 }
4792 })?;
4793 if let Some(task) = spawned_test_task {
4794 task.await?;
4795 }
4796
4797 Ok::<_, anyhow::Error>(())
4798 })
4799 .detach_and_log_err(cx);
4800 }
4801
4802 pub fn confirm_code_action(
4803 &mut self,
4804 action: &ConfirmCodeAction,
4805 cx: &mut ViewContext<Self>,
4806 ) -> Option<Task<Result<()>>> {
4807 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4808 menu
4809 } else {
4810 return None;
4811 };
4812 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4813 let action = actions_menu.actions.get(action_ix)?;
4814 let title = action.label();
4815 let buffer = actions_menu.buffer;
4816 let workspace = self.workspace()?;
4817
4818 match action {
4819 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4820 workspace.update(cx, |workspace, cx| {
4821 workspace::tasks::schedule_resolved_task(
4822 workspace,
4823 task_source_kind,
4824 resolved_task,
4825 false,
4826 cx,
4827 );
4828
4829 Some(Task::ready(Ok(())))
4830 })
4831 }
4832 CodeActionsItem::CodeAction {
4833 excerpt_id,
4834 action,
4835 provider,
4836 } => {
4837 let apply_code_action =
4838 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4839 let workspace = workspace.downgrade();
4840 Some(cx.spawn(|editor, cx| async move {
4841 let project_transaction = apply_code_action.await?;
4842 Self::open_project_transaction(
4843 &editor,
4844 workspace,
4845 project_transaction,
4846 title,
4847 cx,
4848 )
4849 .await
4850 }))
4851 }
4852 }
4853 }
4854
4855 pub async fn open_project_transaction(
4856 this: &WeakView<Editor>,
4857 workspace: WeakView<Workspace>,
4858 transaction: ProjectTransaction,
4859 title: String,
4860 mut cx: AsyncWindowContext,
4861 ) -> Result<()> {
4862 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4863 cx.update(|cx| {
4864 entries.sort_unstable_by_key(|(buffer, _)| {
4865 buffer.read(cx).file().map(|f| f.path().clone())
4866 });
4867 })?;
4868
4869 // If the project transaction's edits are all contained within this editor, then
4870 // avoid opening a new editor to display them.
4871
4872 if let Some((buffer, transaction)) = entries.first() {
4873 if entries.len() == 1 {
4874 let excerpt = this.update(&mut cx, |editor, cx| {
4875 editor
4876 .buffer()
4877 .read(cx)
4878 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4879 })?;
4880 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4881 if excerpted_buffer == *buffer {
4882 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4883 let excerpt_range = excerpt_range.to_offset(buffer);
4884 buffer
4885 .edited_ranges_for_transaction::<usize>(transaction)
4886 .all(|range| {
4887 excerpt_range.start <= range.start
4888 && excerpt_range.end >= range.end
4889 })
4890 })?;
4891
4892 if all_edits_within_excerpt {
4893 return Ok(());
4894 }
4895 }
4896 }
4897 }
4898 } else {
4899 return Ok(());
4900 }
4901
4902 let mut ranges_to_highlight = Vec::new();
4903 let excerpt_buffer = cx.new_model(|cx| {
4904 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4905 for (buffer_handle, transaction) in &entries {
4906 let buffer = buffer_handle.read(cx);
4907 ranges_to_highlight.extend(
4908 multibuffer.push_excerpts_with_context_lines(
4909 buffer_handle.clone(),
4910 buffer
4911 .edited_ranges_for_transaction::<usize>(transaction)
4912 .collect(),
4913 DEFAULT_MULTIBUFFER_CONTEXT,
4914 cx,
4915 ),
4916 );
4917 }
4918 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4919 multibuffer
4920 })?;
4921
4922 workspace.update(&mut cx, |workspace, cx| {
4923 let project = workspace.project().clone();
4924 let editor =
4925 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4926 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4927 editor.update(cx, |editor, cx| {
4928 editor.highlight_background::<Self>(
4929 &ranges_to_highlight,
4930 |theme| theme.editor_highlighted_line_background,
4931 cx,
4932 );
4933 });
4934 })?;
4935
4936 Ok(())
4937 }
4938
4939 pub fn clear_code_action_providers(&mut self) {
4940 self.code_action_providers.clear();
4941 self.available_code_actions.take();
4942 }
4943
4944 pub fn push_code_action_provider(
4945 &mut self,
4946 provider: Arc<dyn CodeActionProvider>,
4947 cx: &mut ViewContext<Self>,
4948 ) {
4949 self.code_action_providers.push(provider);
4950 self.refresh_code_actions(cx);
4951 }
4952
4953 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4954 let buffer = self.buffer.read(cx);
4955 let newest_selection = self.selections.newest_anchor().clone();
4956 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4957 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4958 if start_buffer != end_buffer {
4959 return None;
4960 }
4961
4962 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4963 cx.background_executor()
4964 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4965 .await;
4966
4967 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4968 let providers = this.code_action_providers.clone();
4969 let tasks = this
4970 .code_action_providers
4971 .iter()
4972 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4973 .collect::<Vec<_>>();
4974 (providers, tasks)
4975 })?;
4976
4977 let mut actions = Vec::new();
4978 for (provider, provider_actions) in
4979 providers.into_iter().zip(future::join_all(tasks).await)
4980 {
4981 if let Some(provider_actions) = provider_actions.log_err() {
4982 actions.extend(provider_actions.into_iter().map(|action| {
4983 AvailableCodeAction {
4984 excerpt_id: newest_selection.start.excerpt_id,
4985 action,
4986 provider: provider.clone(),
4987 }
4988 }));
4989 }
4990 }
4991
4992 this.update(&mut cx, |this, cx| {
4993 this.available_code_actions = if actions.is_empty() {
4994 None
4995 } else {
4996 Some((
4997 Location {
4998 buffer: start_buffer,
4999 range: start..end,
5000 },
5001 actions.into(),
5002 ))
5003 };
5004 cx.notify();
5005 })
5006 }));
5007 None
5008 }
5009
5010 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5011 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5012 self.show_git_blame_inline = false;
5013
5014 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5015 cx.background_executor().timer(delay).await;
5016
5017 this.update(&mut cx, |this, cx| {
5018 this.show_git_blame_inline = true;
5019 cx.notify();
5020 })
5021 .log_err();
5022 }));
5023 }
5024 }
5025
5026 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5027 if self.pending_rename.is_some() {
5028 return None;
5029 }
5030
5031 let provider = self.semantics_provider.clone()?;
5032 let buffer = self.buffer.read(cx);
5033 let newest_selection = self.selections.newest_anchor().clone();
5034 let cursor_position = newest_selection.head();
5035 let (cursor_buffer, cursor_buffer_position) =
5036 buffer.text_anchor_for_position(cursor_position, cx)?;
5037 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5038 if cursor_buffer != tail_buffer {
5039 return None;
5040 }
5041
5042 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5043 cx.background_executor()
5044 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5045 .await;
5046
5047 let highlights = if let Some(highlights) = cx
5048 .update(|cx| {
5049 provider.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5050 })
5051 .ok()
5052 .flatten()
5053 {
5054 highlights.await.log_err()
5055 } else {
5056 None
5057 };
5058
5059 if let Some(highlights) = highlights {
5060 this.update(&mut cx, |this, cx| {
5061 if this.pending_rename.is_some() {
5062 return;
5063 }
5064
5065 let buffer_id = cursor_position.buffer_id;
5066 let buffer = this.buffer.read(cx);
5067 if !buffer
5068 .text_anchor_for_position(cursor_position, cx)
5069 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5070 {
5071 return;
5072 }
5073
5074 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5075 let mut write_ranges = Vec::new();
5076 let mut read_ranges = Vec::new();
5077 for highlight in highlights {
5078 for (excerpt_id, excerpt_range) in
5079 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5080 {
5081 let start = highlight
5082 .range
5083 .start
5084 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5085 let end = highlight
5086 .range
5087 .end
5088 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5089 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5090 continue;
5091 }
5092
5093 let range = Anchor {
5094 buffer_id,
5095 excerpt_id,
5096 text_anchor: start,
5097 }..Anchor {
5098 buffer_id,
5099 excerpt_id,
5100 text_anchor: end,
5101 };
5102 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5103 write_ranges.push(range);
5104 } else {
5105 read_ranges.push(range);
5106 }
5107 }
5108 }
5109
5110 this.highlight_background::<DocumentHighlightRead>(
5111 &read_ranges,
5112 |theme| theme.editor_document_highlight_read_background,
5113 cx,
5114 );
5115 this.highlight_background::<DocumentHighlightWrite>(
5116 &write_ranges,
5117 |theme| theme.editor_document_highlight_write_background,
5118 cx,
5119 );
5120 cx.notify();
5121 })
5122 .log_err();
5123 }
5124 }));
5125 None
5126 }
5127
5128 pub fn refresh_inline_completion(
5129 &mut self,
5130 debounce: bool,
5131 user_requested: bool,
5132 cx: &mut ViewContext<Self>,
5133 ) -> Option<()> {
5134 let provider = self.inline_completion_provider()?;
5135 let cursor = self.selections.newest_anchor().head();
5136 let (buffer, cursor_buffer_position) =
5137 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5138
5139 if !user_requested
5140 && (!self.enable_inline_completions
5141 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5142 {
5143 self.discard_inline_completion(false, cx);
5144 return None;
5145 }
5146
5147 self.update_visible_inline_completion(cx);
5148 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5149 Some(())
5150 }
5151
5152 fn cycle_inline_completion(
5153 &mut self,
5154 direction: Direction,
5155 cx: &mut ViewContext<Self>,
5156 ) -> Option<()> {
5157 let provider = self.inline_completion_provider()?;
5158 let cursor = self.selections.newest_anchor().head();
5159 let (buffer, cursor_buffer_position) =
5160 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5161 if !self.enable_inline_completions
5162 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5163 {
5164 return None;
5165 }
5166
5167 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5168 self.update_visible_inline_completion(cx);
5169
5170 Some(())
5171 }
5172
5173 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5174 if !self.has_active_inline_completion(cx) {
5175 self.refresh_inline_completion(false, true, cx);
5176 return;
5177 }
5178
5179 self.update_visible_inline_completion(cx);
5180 }
5181
5182 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5183 self.show_cursor_names(cx);
5184 }
5185
5186 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5187 self.show_cursor_names = true;
5188 cx.notify();
5189 cx.spawn(|this, mut cx| async move {
5190 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5191 this.update(&mut cx, |this, cx| {
5192 this.show_cursor_names = false;
5193 cx.notify()
5194 })
5195 .ok()
5196 })
5197 .detach();
5198 }
5199
5200 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5201 if self.has_active_inline_completion(cx) {
5202 self.cycle_inline_completion(Direction::Next, cx);
5203 } else {
5204 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5205 if is_copilot_disabled {
5206 cx.propagate();
5207 }
5208 }
5209 }
5210
5211 pub fn previous_inline_completion(
5212 &mut self,
5213 _: &PreviousInlineCompletion,
5214 cx: &mut ViewContext<Self>,
5215 ) {
5216 if self.has_active_inline_completion(cx) {
5217 self.cycle_inline_completion(Direction::Prev, cx);
5218 } else {
5219 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5220 if is_copilot_disabled {
5221 cx.propagate();
5222 }
5223 }
5224 }
5225
5226 pub fn accept_inline_completion(
5227 &mut self,
5228 _: &AcceptInlineCompletion,
5229 cx: &mut ViewContext<Self>,
5230 ) {
5231 let Some(completion) = self.take_active_inline_completion(cx) else {
5232 return;
5233 };
5234 if let Some(provider) = self.inline_completion_provider() {
5235 provider.accept(cx);
5236 }
5237
5238 cx.emit(EditorEvent::InputHandled {
5239 utf16_range_to_replace: None,
5240 text: completion.text.to_string().into(),
5241 });
5242
5243 if let Some(range) = completion.delete_range {
5244 self.change_selections(None, cx, |s| s.select_ranges([range]))
5245 }
5246 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5247 self.refresh_inline_completion(true, true, cx);
5248 cx.notify();
5249 }
5250
5251 pub fn accept_partial_inline_completion(
5252 &mut self,
5253 _: &AcceptPartialInlineCompletion,
5254 cx: &mut ViewContext<Self>,
5255 ) {
5256 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5257 if let Some(completion) = self.take_active_inline_completion(cx) {
5258 let mut partial_completion = completion
5259 .text
5260 .chars()
5261 .by_ref()
5262 .take_while(|c| c.is_alphabetic())
5263 .collect::<String>();
5264 if partial_completion.is_empty() {
5265 partial_completion = completion
5266 .text
5267 .chars()
5268 .by_ref()
5269 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5270 .collect::<String>();
5271 }
5272
5273 cx.emit(EditorEvent::InputHandled {
5274 utf16_range_to_replace: None,
5275 text: partial_completion.clone().into(),
5276 });
5277
5278 if let Some(range) = completion.delete_range {
5279 self.change_selections(None, cx, |s| s.select_ranges([range]))
5280 }
5281 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5282
5283 self.refresh_inline_completion(true, true, cx);
5284 cx.notify();
5285 }
5286 }
5287 }
5288
5289 fn discard_inline_completion(
5290 &mut self,
5291 should_report_inline_completion_event: bool,
5292 cx: &mut ViewContext<Self>,
5293 ) -> bool {
5294 if let Some(provider) = self.inline_completion_provider() {
5295 provider.discard(should_report_inline_completion_event, cx);
5296 }
5297
5298 self.take_active_inline_completion(cx).is_some()
5299 }
5300
5301 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5302 if let Some(completion) = self.active_inline_completion.as_ref() {
5303 let buffer = self.buffer.read(cx).read(cx);
5304 completion.position.is_valid(&buffer)
5305 } else {
5306 false
5307 }
5308 }
5309
5310 fn take_active_inline_completion(
5311 &mut self,
5312 cx: &mut ViewContext<Self>,
5313 ) -> Option<CompletionState> {
5314 let completion = self.active_inline_completion.take()?;
5315 let render_inlay_ids = completion.render_inlay_ids.clone();
5316 self.display_map.update(cx, |map, cx| {
5317 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5318 });
5319 let buffer = self.buffer.read(cx).read(cx);
5320
5321 if completion.position.is_valid(&buffer) {
5322 Some(completion)
5323 } else {
5324 None
5325 }
5326 }
5327
5328 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5329 let selection = self.selections.newest_anchor();
5330 let cursor = selection.head();
5331
5332 let excerpt_id = cursor.excerpt_id;
5333
5334 if self.context_menu.read().is_none()
5335 && self.completion_tasks.is_empty()
5336 && selection.start == selection.end
5337 {
5338 if let Some(provider) = self.inline_completion_provider() {
5339 if let Some((buffer, cursor_buffer_position)) =
5340 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5341 {
5342 if let Some(proposal) =
5343 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5344 {
5345 let mut to_remove = Vec::new();
5346 if let Some(completion) = self.active_inline_completion.take() {
5347 to_remove.extend(completion.render_inlay_ids.iter());
5348 }
5349
5350 let to_add = proposal
5351 .inlays
5352 .iter()
5353 .filter_map(|inlay| {
5354 let snapshot = self.buffer.read(cx).snapshot(cx);
5355 let id = post_inc(&mut self.next_inlay_id);
5356 match inlay {
5357 InlayProposal::Hint(position, hint) => {
5358 let position =
5359 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5360 Some(Inlay::hint(id, position, hint))
5361 }
5362 InlayProposal::Suggestion(position, text) => {
5363 let position =
5364 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5365 Some(Inlay::suggestion(id, position, text.clone()))
5366 }
5367 }
5368 })
5369 .collect_vec();
5370
5371 self.active_inline_completion = Some(CompletionState {
5372 position: cursor,
5373 text: proposal.text,
5374 delete_range: proposal.delete_range.and_then(|range| {
5375 let snapshot = self.buffer.read(cx).snapshot(cx);
5376 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5377 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5378 Some(start?..end?)
5379 }),
5380 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5381 });
5382
5383 self.display_map
5384 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5385
5386 cx.notify();
5387 return;
5388 }
5389 }
5390 }
5391 }
5392
5393 self.discard_inline_completion(false, cx);
5394 }
5395
5396 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5397 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5398 }
5399
5400 fn render_code_actions_indicator(
5401 &self,
5402 _style: &EditorStyle,
5403 row: DisplayRow,
5404 is_active: bool,
5405 cx: &mut ViewContext<Self>,
5406 ) -> Option<IconButton> {
5407 if self.available_code_actions.is_some() {
5408 Some(
5409 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5410 .shape(ui::IconButtonShape::Square)
5411 .icon_size(IconSize::XSmall)
5412 .icon_color(Color::Muted)
5413 .selected(is_active)
5414 .tooltip({
5415 let focus_handle = self.focus_handle.clone();
5416 move |cx| {
5417 Tooltip::for_action_in(
5418 "Toggle Code Actions",
5419 &ToggleCodeActions {
5420 deployed_from_indicator: None,
5421 },
5422 &focus_handle,
5423 cx,
5424 )
5425 }
5426 })
5427 .on_click(cx.listener(move |editor, _e, cx| {
5428 editor.focus(cx);
5429 editor.toggle_code_actions(
5430 &ToggleCodeActions {
5431 deployed_from_indicator: Some(row),
5432 },
5433 cx,
5434 );
5435 })),
5436 )
5437 } else {
5438 None
5439 }
5440 }
5441
5442 fn clear_tasks(&mut self) {
5443 self.tasks.clear()
5444 }
5445
5446 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5447 if self.tasks.insert(key, value).is_some() {
5448 // This case should hopefully be rare, but just in case...
5449 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5450 }
5451 }
5452
5453 fn render_run_indicator(
5454 &self,
5455 _style: &EditorStyle,
5456 is_active: bool,
5457 row: DisplayRow,
5458 cx: &mut ViewContext<Self>,
5459 ) -> IconButton {
5460 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5461 .shape(ui::IconButtonShape::Square)
5462 .icon_size(IconSize::XSmall)
5463 .icon_color(Color::Muted)
5464 .selected(is_active)
5465 .on_click(cx.listener(move |editor, _e, cx| {
5466 editor.focus(cx);
5467 editor.toggle_code_actions(
5468 &ToggleCodeActions {
5469 deployed_from_indicator: Some(row),
5470 },
5471 cx,
5472 );
5473 }))
5474 }
5475
5476 pub fn context_menu_visible(&self) -> bool {
5477 self.context_menu
5478 .read()
5479 .as_ref()
5480 .map_or(false, |menu| menu.visible())
5481 }
5482
5483 fn render_context_menu(
5484 &self,
5485 cursor_position: DisplayPoint,
5486 style: &EditorStyle,
5487 max_height: Pixels,
5488 cx: &mut ViewContext<Editor>,
5489 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5490 self.context_menu.read().as_ref().map(|menu| {
5491 menu.render(
5492 cursor_position,
5493 style,
5494 max_height,
5495 self.workspace.as_ref().map(|(w, _)| w.clone()),
5496 cx,
5497 )
5498 })
5499 }
5500
5501 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5502 cx.notify();
5503 self.completion_tasks.clear();
5504 let context_menu = self.context_menu.write().take();
5505 if context_menu.is_some() {
5506 self.update_visible_inline_completion(cx);
5507 }
5508 context_menu
5509 }
5510
5511 pub fn insert_snippet(
5512 &mut self,
5513 insertion_ranges: &[Range<usize>],
5514 snippet: Snippet,
5515 cx: &mut ViewContext<Self>,
5516 ) -> Result<()> {
5517 struct Tabstop<T> {
5518 is_end_tabstop: bool,
5519 ranges: Vec<Range<T>>,
5520 }
5521
5522 let tabstops = self.buffer.update(cx, |buffer, cx| {
5523 let snippet_text: Arc<str> = snippet.text.clone().into();
5524 buffer.edit(
5525 insertion_ranges
5526 .iter()
5527 .cloned()
5528 .map(|range| (range, snippet_text.clone())),
5529 Some(AutoindentMode::EachLine),
5530 cx,
5531 );
5532
5533 let snapshot = &*buffer.read(cx);
5534 let snippet = &snippet;
5535 snippet
5536 .tabstops
5537 .iter()
5538 .map(|tabstop| {
5539 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5540 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5541 });
5542 let mut tabstop_ranges = tabstop
5543 .iter()
5544 .flat_map(|tabstop_range| {
5545 let mut delta = 0_isize;
5546 insertion_ranges.iter().map(move |insertion_range| {
5547 let insertion_start = insertion_range.start as isize + delta;
5548 delta +=
5549 snippet.text.len() as isize - insertion_range.len() as isize;
5550
5551 let start = ((insertion_start + tabstop_range.start) as usize)
5552 .min(snapshot.len());
5553 let end = ((insertion_start + tabstop_range.end) as usize)
5554 .min(snapshot.len());
5555 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5556 })
5557 })
5558 .collect::<Vec<_>>();
5559 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5560
5561 Tabstop {
5562 is_end_tabstop,
5563 ranges: tabstop_ranges,
5564 }
5565 })
5566 .collect::<Vec<_>>()
5567 });
5568 if let Some(tabstop) = tabstops.first() {
5569 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5570 s.select_ranges(tabstop.ranges.iter().cloned());
5571 });
5572
5573 // If we're already at the last tabstop and it's at the end of the snippet,
5574 // we're done, we don't need to keep the state around.
5575 if !tabstop.is_end_tabstop {
5576 let ranges = tabstops
5577 .into_iter()
5578 .map(|tabstop| tabstop.ranges)
5579 .collect::<Vec<_>>();
5580 self.snippet_stack.push(SnippetState {
5581 active_index: 0,
5582 ranges,
5583 });
5584 }
5585
5586 // Check whether the just-entered snippet ends with an auto-closable bracket.
5587 if self.autoclose_regions.is_empty() {
5588 let snapshot = self.buffer.read(cx).snapshot(cx);
5589 for selection in &mut self.selections.all::<Point>(cx) {
5590 let selection_head = selection.head();
5591 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5592 continue;
5593 };
5594
5595 let mut bracket_pair = None;
5596 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5597 let prev_chars = snapshot
5598 .reversed_chars_at(selection_head)
5599 .collect::<String>();
5600 for (pair, enabled) in scope.brackets() {
5601 if enabled
5602 && pair.close
5603 && prev_chars.starts_with(pair.start.as_str())
5604 && next_chars.starts_with(pair.end.as_str())
5605 {
5606 bracket_pair = Some(pair.clone());
5607 break;
5608 }
5609 }
5610 if let Some(pair) = bracket_pair {
5611 let start = snapshot.anchor_after(selection_head);
5612 let end = snapshot.anchor_after(selection_head);
5613 self.autoclose_regions.push(AutocloseRegion {
5614 selection_id: selection.id,
5615 range: start..end,
5616 pair,
5617 });
5618 }
5619 }
5620 }
5621 }
5622 Ok(())
5623 }
5624
5625 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5626 self.move_to_snippet_tabstop(Bias::Right, cx)
5627 }
5628
5629 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5630 self.move_to_snippet_tabstop(Bias::Left, cx)
5631 }
5632
5633 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5634 if let Some(mut snippet) = self.snippet_stack.pop() {
5635 match bias {
5636 Bias::Left => {
5637 if snippet.active_index > 0 {
5638 snippet.active_index -= 1;
5639 } else {
5640 self.snippet_stack.push(snippet);
5641 return false;
5642 }
5643 }
5644 Bias::Right => {
5645 if snippet.active_index + 1 < snippet.ranges.len() {
5646 snippet.active_index += 1;
5647 } else {
5648 self.snippet_stack.push(snippet);
5649 return false;
5650 }
5651 }
5652 }
5653 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5654 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5655 s.select_anchor_ranges(current_ranges.iter().cloned())
5656 });
5657 // If snippet state is not at the last tabstop, push it back on the stack
5658 if snippet.active_index + 1 < snippet.ranges.len() {
5659 self.snippet_stack.push(snippet);
5660 }
5661 return true;
5662 }
5663 }
5664
5665 false
5666 }
5667
5668 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5669 self.transact(cx, |this, cx| {
5670 this.select_all(&SelectAll, cx);
5671 this.insert("", cx);
5672 });
5673 }
5674
5675 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5676 self.transact(cx, |this, cx| {
5677 this.select_autoclose_pair(cx);
5678 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5679 if !this.linked_edit_ranges.is_empty() {
5680 let selections = this.selections.all::<MultiBufferPoint>(cx);
5681 let snapshot = this.buffer.read(cx).snapshot(cx);
5682
5683 for selection in selections.iter() {
5684 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5685 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5686 if selection_start.buffer_id != selection_end.buffer_id {
5687 continue;
5688 }
5689 if let Some(ranges) =
5690 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5691 {
5692 for (buffer, entries) in ranges {
5693 linked_ranges.entry(buffer).or_default().extend(entries);
5694 }
5695 }
5696 }
5697 }
5698
5699 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5700 if !this.selections.line_mode {
5701 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5702 for selection in &mut selections {
5703 if selection.is_empty() {
5704 let old_head = selection.head();
5705 let mut new_head =
5706 movement::left(&display_map, old_head.to_display_point(&display_map))
5707 .to_point(&display_map);
5708 if let Some((buffer, line_buffer_range)) = display_map
5709 .buffer_snapshot
5710 .buffer_line_for_row(MultiBufferRow(old_head.row))
5711 {
5712 let indent_size =
5713 buffer.indent_size_for_line(line_buffer_range.start.row);
5714 let indent_len = match indent_size.kind {
5715 IndentKind::Space => {
5716 buffer.settings_at(line_buffer_range.start, cx).tab_size
5717 }
5718 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5719 };
5720 if old_head.column <= indent_size.len && old_head.column > 0 {
5721 let indent_len = indent_len.get();
5722 new_head = cmp::min(
5723 new_head,
5724 MultiBufferPoint::new(
5725 old_head.row,
5726 ((old_head.column - 1) / indent_len) * indent_len,
5727 ),
5728 );
5729 }
5730 }
5731
5732 selection.set_head(new_head, SelectionGoal::None);
5733 }
5734 }
5735 }
5736
5737 this.signature_help_state.set_backspace_pressed(true);
5738 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5739 this.insert("", cx);
5740 let empty_str: Arc<str> = Arc::from("");
5741 for (buffer, edits) in linked_ranges {
5742 let snapshot = buffer.read(cx).snapshot();
5743 use text::ToPoint as TP;
5744
5745 let edits = edits
5746 .into_iter()
5747 .map(|range| {
5748 let end_point = TP::to_point(&range.end, &snapshot);
5749 let mut start_point = TP::to_point(&range.start, &snapshot);
5750
5751 if end_point == start_point {
5752 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5753 .saturating_sub(1);
5754 start_point = TP::to_point(&offset, &snapshot);
5755 };
5756
5757 (start_point..end_point, empty_str.clone())
5758 })
5759 .sorted_by_key(|(range, _)| range.start)
5760 .collect::<Vec<_>>();
5761 buffer.update(cx, |this, cx| {
5762 this.edit(edits, None, cx);
5763 })
5764 }
5765 this.refresh_inline_completion(true, false, cx);
5766 linked_editing_ranges::refresh_linked_ranges(this, cx);
5767 });
5768 }
5769
5770 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5771 self.transact(cx, |this, cx| {
5772 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5773 let line_mode = s.line_mode;
5774 s.move_with(|map, selection| {
5775 if selection.is_empty() && !line_mode {
5776 let cursor = movement::right(map, selection.head());
5777 selection.end = cursor;
5778 selection.reversed = true;
5779 selection.goal = SelectionGoal::None;
5780 }
5781 })
5782 });
5783 this.insert("", cx);
5784 this.refresh_inline_completion(true, false, cx);
5785 });
5786 }
5787
5788 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5789 if self.move_to_prev_snippet_tabstop(cx) {
5790 return;
5791 }
5792
5793 self.outdent(&Outdent, cx);
5794 }
5795
5796 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5797 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5798 return;
5799 }
5800
5801 let mut selections = self.selections.all_adjusted(cx);
5802 let buffer = self.buffer.read(cx);
5803 let snapshot = buffer.snapshot(cx);
5804 let rows_iter = selections.iter().map(|s| s.head().row);
5805 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5806
5807 let mut edits = Vec::new();
5808 let mut prev_edited_row = 0;
5809 let mut row_delta = 0;
5810 for selection in &mut selections {
5811 if selection.start.row != prev_edited_row {
5812 row_delta = 0;
5813 }
5814 prev_edited_row = selection.end.row;
5815
5816 // If the selection is non-empty, then increase the indentation of the selected lines.
5817 if !selection.is_empty() {
5818 row_delta =
5819 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5820 continue;
5821 }
5822
5823 // If the selection is empty and the cursor is in the leading whitespace before the
5824 // suggested indentation, then auto-indent the line.
5825 let cursor = selection.head();
5826 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5827 if let Some(suggested_indent) =
5828 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5829 {
5830 if cursor.column < suggested_indent.len
5831 && cursor.column <= current_indent.len
5832 && current_indent.len <= suggested_indent.len
5833 {
5834 selection.start = Point::new(cursor.row, suggested_indent.len);
5835 selection.end = selection.start;
5836 if row_delta == 0 {
5837 edits.extend(Buffer::edit_for_indent_size_adjustment(
5838 cursor.row,
5839 current_indent,
5840 suggested_indent,
5841 ));
5842 row_delta = suggested_indent.len - current_indent.len;
5843 }
5844 continue;
5845 }
5846 }
5847
5848 // Otherwise, insert a hard or soft tab.
5849 let settings = buffer.settings_at(cursor, cx);
5850 let tab_size = if settings.hard_tabs {
5851 IndentSize::tab()
5852 } else {
5853 let tab_size = settings.tab_size.get();
5854 let char_column = snapshot
5855 .text_for_range(Point::new(cursor.row, 0)..cursor)
5856 .flat_map(str::chars)
5857 .count()
5858 + row_delta as usize;
5859 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5860 IndentSize::spaces(chars_to_next_tab_stop)
5861 };
5862 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5863 selection.end = selection.start;
5864 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5865 row_delta += tab_size.len;
5866 }
5867
5868 self.transact(cx, |this, cx| {
5869 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5870 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5871 this.refresh_inline_completion(true, false, cx);
5872 });
5873 }
5874
5875 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5876 if self.read_only(cx) {
5877 return;
5878 }
5879 let mut selections = self.selections.all::<Point>(cx);
5880 let mut prev_edited_row = 0;
5881 let mut row_delta = 0;
5882 let mut edits = Vec::new();
5883 let buffer = self.buffer.read(cx);
5884 let snapshot = buffer.snapshot(cx);
5885 for selection in &mut selections {
5886 if selection.start.row != prev_edited_row {
5887 row_delta = 0;
5888 }
5889 prev_edited_row = selection.end.row;
5890
5891 row_delta =
5892 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5893 }
5894
5895 self.transact(cx, |this, cx| {
5896 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5897 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5898 });
5899 }
5900
5901 fn indent_selection(
5902 buffer: &MultiBuffer,
5903 snapshot: &MultiBufferSnapshot,
5904 selection: &mut Selection<Point>,
5905 edits: &mut Vec<(Range<Point>, String)>,
5906 delta_for_start_row: u32,
5907 cx: &AppContext,
5908 ) -> u32 {
5909 let settings = buffer.settings_at(selection.start, cx);
5910 let tab_size = settings.tab_size.get();
5911 let indent_kind = if settings.hard_tabs {
5912 IndentKind::Tab
5913 } else {
5914 IndentKind::Space
5915 };
5916 let mut start_row = selection.start.row;
5917 let mut end_row = selection.end.row + 1;
5918
5919 // If a selection ends at the beginning of a line, don't indent
5920 // that last line.
5921 if selection.end.column == 0 && selection.end.row > selection.start.row {
5922 end_row -= 1;
5923 }
5924
5925 // Avoid re-indenting a row that has already been indented by a
5926 // previous selection, but still update this selection's column
5927 // to reflect that indentation.
5928 if delta_for_start_row > 0 {
5929 start_row += 1;
5930 selection.start.column += delta_for_start_row;
5931 if selection.end.row == selection.start.row {
5932 selection.end.column += delta_for_start_row;
5933 }
5934 }
5935
5936 let mut delta_for_end_row = 0;
5937 let has_multiple_rows = start_row + 1 != end_row;
5938 for row in start_row..end_row {
5939 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5940 let indent_delta = match (current_indent.kind, indent_kind) {
5941 (IndentKind::Space, IndentKind::Space) => {
5942 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5943 IndentSize::spaces(columns_to_next_tab_stop)
5944 }
5945 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5946 (_, IndentKind::Tab) => IndentSize::tab(),
5947 };
5948
5949 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5950 0
5951 } else {
5952 selection.start.column
5953 };
5954 let row_start = Point::new(row, start);
5955 edits.push((
5956 row_start..row_start,
5957 indent_delta.chars().collect::<String>(),
5958 ));
5959
5960 // Update this selection's endpoints to reflect the indentation.
5961 if row == selection.start.row {
5962 selection.start.column += indent_delta.len;
5963 }
5964 if row == selection.end.row {
5965 selection.end.column += indent_delta.len;
5966 delta_for_end_row = indent_delta.len;
5967 }
5968 }
5969
5970 if selection.start.row == selection.end.row {
5971 delta_for_start_row + delta_for_end_row
5972 } else {
5973 delta_for_end_row
5974 }
5975 }
5976
5977 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5978 if self.read_only(cx) {
5979 return;
5980 }
5981 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5982 let selections = self.selections.all::<Point>(cx);
5983 let mut deletion_ranges = Vec::new();
5984 let mut last_outdent = None;
5985 {
5986 let buffer = self.buffer.read(cx);
5987 let snapshot = buffer.snapshot(cx);
5988 for selection in &selections {
5989 let settings = buffer.settings_at(selection.start, cx);
5990 let tab_size = settings.tab_size.get();
5991 let mut rows = selection.spanned_rows(false, &display_map);
5992
5993 // Avoid re-outdenting a row that has already been outdented by a
5994 // previous selection.
5995 if let Some(last_row) = last_outdent {
5996 if last_row == rows.start {
5997 rows.start = rows.start.next_row();
5998 }
5999 }
6000 let has_multiple_rows = rows.len() > 1;
6001 for row in rows.iter_rows() {
6002 let indent_size = snapshot.indent_size_for_line(row);
6003 if indent_size.len > 0 {
6004 let deletion_len = match indent_size.kind {
6005 IndentKind::Space => {
6006 let columns_to_prev_tab_stop = indent_size.len % tab_size;
6007 if columns_to_prev_tab_stop == 0 {
6008 tab_size
6009 } else {
6010 columns_to_prev_tab_stop
6011 }
6012 }
6013 IndentKind::Tab => 1,
6014 };
6015 let start = if has_multiple_rows
6016 || deletion_len > selection.start.column
6017 || indent_size.len < selection.start.column
6018 {
6019 0
6020 } else {
6021 selection.start.column - deletion_len
6022 };
6023 deletion_ranges.push(
6024 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6025 );
6026 last_outdent = Some(row);
6027 }
6028 }
6029 }
6030 }
6031
6032 self.transact(cx, |this, cx| {
6033 this.buffer.update(cx, |buffer, cx| {
6034 let empty_str: Arc<str> = Arc::default();
6035 buffer.edit(
6036 deletion_ranges
6037 .into_iter()
6038 .map(|range| (range, empty_str.clone())),
6039 None,
6040 cx,
6041 );
6042 });
6043 let selections = this.selections.all::<usize>(cx);
6044 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6045 });
6046 }
6047
6048 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6049 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6050 let selections = self.selections.all::<Point>(cx);
6051
6052 let mut new_cursors = Vec::new();
6053 let mut edit_ranges = Vec::new();
6054 let mut selections = selections.iter().peekable();
6055 while let Some(selection) = selections.next() {
6056 let mut rows = selection.spanned_rows(false, &display_map);
6057 let goal_display_column = selection.head().to_display_point(&display_map).column();
6058
6059 // Accumulate contiguous regions of rows that we want to delete.
6060 while let Some(next_selection) = selections.peek() {
6061 let next_rows = next_selection.spanned_rows(false, &display_map);
6062 if next_rows.start <= rows.end {
6063 rows.end = next_rows.end;
6064 selections.next().unwrap();
6065 } else {
6066 break;
6067 }
6068 }
6069
6070 let buffer = &display_map.buffer_snapshot;
6071 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6072 let edit_end;
6073 let cursor_buffer_row;
6074 if buffer.max_point().row >= rows.end.0 {
6075 // If there's a line after the range, delete the \n from the end of the row range
6076 // and position the cursor on the next line.
6077 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6078 cursor_buffer_row = rows.end;
6079 } else {
6080 // If there isn't a line after the range, delete the \n from the line before the
6081 // start of the row range and position the cursor there.
6082 edit_start = edit_start.saturating_sub(1);
6083 edit_end = buffer.len();
6084 cursor_buffer_row = rows.start.previous_row();
6085 }
6086
6087 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6088 *cursor.column_mut() =
6089 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6090
6091 new_cursors.push((
6092 selection.id,
6093 buffer.anchor_after(cursor.to_point(&display_map)),
6094 ));
6095 edit_ranges.push(edit_start..edit_end);
6096 }
6097
6098 self.transact(cx, |this, cx| {
6099 let buffer = this.buffer.update(cx, |buffer, cx| {
6100 let empty_str: Arc<str> = Arc::default();
6101 buffer.edit(
6102 edit_ranges
6103 .into_iter()
6104 .map(|range| (range, empty_str.clone())),
6105 None,
6106 cx,
6107 );
6108 buffer.snapshot(cx)
6109 });
6110 let new_selections = new_cursors
6111 .into_iter()
6112 .map(|(id, cursor)| {
6113 let cursor = cursor.to_point(&buffer);
6114 Selection {
6115 id,
6116 start: cursor,
6117 end: cursor,
6118 reversed: false,
6119 goal: SelectionGoal::None,
6120 }
6121 })
6122 .collect();
6123
6124 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6125 s.select(new_selections);
6126 });
6127 });
6128 }
6129
6130 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6131 if self.read_only(cx) {
6132 return;
6133 }
6134 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6135 for selection in self.selections.all::<Point>(cx) {
6136 let start = MultiBufferRow(selection.start.row);
6137 let end = if selection.start.row == selection.end.row {
6138 MultiBufferRow(selection.start.row + 1)
6139 } else {
6140 MultiBufferRow(selection.end.row)
6141 };
6142
6143 if let Some(last_row_range) = row_ranges.last_mut() {
6144 if start <= last_row_range.end {
6145 last_row_range.end = end;
6146 continue;
6147 }
6148 }
6149 row_ranges.push(start..end);
6150 }
6151
6152 let snapshot = self.buffer.read(cx).snapshot(cx);
6153 let mut cursor_positions = Vec::new();
6154 for row_range in &row_ranges {
6155 let anchor = snapshot.anchor_before(Point::new(
6156 row_range.end.previous_row().0,
6157 snapshot.line_len(row_range.end.previous_row()),
6158 ));
6159 cursor_positions.push(anchor..anchor);
6160 }
6161
6162 self.transact(cx, |this, cx| {
6163 for row_range in row_ranges.into_iter().rev() {
6164 for row in row_range.iter_rows().rev() {
6165 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6166 let next_line_row = row.next_row();
6167 let indent = snapshot.indent_size_for_line(next_line_row);
6168 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6169
6170 let replace = if snapshot.line_len(next_line_row) > indent.len {
6171 " "
6172 } else {
6173 ""
6174 };
6175
6176 this.buffer.update(cx, |buffer, cx| {
6177 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6178 });
6179 }
6180 }
6181
6182 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6183 s.select_anchor_ranges(cursor_positions)
6184 });
6185 });
6186 }
6187
6188 pub fn sort_lines_case_sensitive(
6189 &mut self,
6190 _: &SortLinesCaseSensitive,
6191 cx: &mut ViewContext<Self>,
6192 ) {
6193 self.manipulate_lines(cx, |lines| lines.sort())
6194 }
6195
6196 pub fn sort_lines_case_insensitive(
6197 &mut self,
6198 _: &SortLinesCaseInsensitive,
6199 cx: &mut ViewContext<Self>,
6200 ) {
6201 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6202 }
6203
6204 pub fn unique_lines_case_insensitive(
6205 &mut self,
6206 _: &UniqueLinesCaseInsensitive,
6207 cx: &mut ViewContext<Self>,
6208 ) {
6209 self.manipulate_lines(cx, |lines| {
6210 let mut seen = HashSet::default();
6211 lines.retain(|line| seen.insert(line.to_lowercase()));
6212 })
6213 }
6214
6215 pub fn unique_lines_case_sensitive(
6216 &mut self,
6217 _: &UniqueLinesCaseSensitive,
6218 cx: &mut ViewContext<Self>,
6219 ) {
6220 self.manipulate_lines(cx, |lines| {
6221 let mut seen = HashSet::default();
6222 lines.retain(|line| seen.insert(*line));
6223 })
6224 }
6225
6226 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6227 let mut revert_changes = HashMap::default();
6228 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6229 for hunk in hunks_for_rows(
6230 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6231 &multi_buffer_snapshot,
6232 ) {
6233 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6234 }
6235 if !revert_changes.is_empty() {
6236 self.transact(cx, |editor, cx| {
6237 editor.revert(revert_changes, cx);
6238 });
6239 }
6240 }
6241
6242 pub fn reload_file(&mut self, _: &ReloadFile, cx: &mut ViewContext<Self>) {
6243 let Some(project) = self.project.clone() else {
6244 return;
6245 };
6246 self.reload(project, cx).detach_and_notify_err(cx);
6247 }
6248
6249 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6250 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6251 if !revert_changes.is_empty() {
6252 self.transact(cx, |editor, cx| {
6253 editor.revert(revert_changes, cx);
6254 });
6255 }
6256 }
6257
6258 fn apply_selected_diff_hunks(&mut self, _: &ApplyDiffHunk, cx: &mut ViewContext<Self>) {
6259 let snapshot = self.buffer.read(cx).snapshot(cx);
6260 let hunks = hunks_for_selections(&snapshot, &self.selections.disjoint_anchors());
6261 let mut ranges_by_buffer = HashMap::default();
6262 self.transact(cx, |editor, cx| {
6263 for hunk in hunks {
6264 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
6265 ranges_by_buffer
6266 .entry(buffer.clone())
6267 .or_insert_with(Vec::new)
6268 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
6269 }
6270 }
6271
6272 for (buffer, ranges) in ranges_by_buffer {
6273 buffer.update(cx, |buffer, cx| {
6274 buffer.merge_into_base(ranges, cx);
6275 });
6276 }
6277 });
6278 }
6279
6280 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6281 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6282 let project_path = buffer.read(cx).project_path(cx)?;
6283 let project = self.project.as_ref()?.read(cx);
6284 let entry = project.entry_for_path(&project_path, cx)?;
6285 let parent = match &entry.canonical_path {
6286 Some(canonical_path) => canonical_path.to_path_buf(),
6287 None => project.absolute_path(&project_path, cx)?,
6288 }
6289 .parent()?
6290 .to_path_buf();
6291 Some(parent)
6292 }) {
6293 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6294 }
6295 }
6296
6297 fn gather_revert_changes(
6298 &mut self,
6299 selections: &[Selection<Anchor>],
6300 cx: &mut ViewContext<'_, Editor>,
6301 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6302 let mut revert_changes = HashMap::default();
6303 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6304 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6305 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6306 }
6307 revert_changes
6308 }
6309
6310 pub fn prepare_revert_change(
6311 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6312 multi_buffer: &Model<MultiBuffer>,
6313 hunk: &MultiBufferDiffHunk,
6314 cx: &AppContext,
6315 ) -> Option<()> {
6316 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6317 let buffer = buffer.read(cx);
6318 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6319 let buffer_snapshot = buffer.snapshot();
6320 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6321 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6322 probe
6323 .0
6324 .start
6325 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6326 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6327 }) {
6328 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6329 Some(())
6330 } else {
6331 None
6332 }
6333 }
6334
6335 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6336 self.manipulate_lines(cx, |lines| lines.reverse())
6337 }
6338
6339 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6340 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6341 }
6342
6343 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6344 where
6345 Fn: FnMut(&mut Vec<&str>),
6346 {
6347 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6348 let buffer = self.buffer.read(cx).snapshot(cx);
6349
6350 let mut edits = Vec::new();
6351
6352 let selections = self.selections.all::<Point>(cx);
6353 let mut selections = selections.iter().peekable();
6354 let mut contiguous_row_selections = Vec::new();
6355 let mut new_selections = Vec::new();
6356 let mut added_lines = 0;
6357 let mut removed_lines = 0;
6358
6359 while let Some(selection) = selections.next() {
6360 let (start_row, end_row) = consume_contiguous_rows(
6361 &mut contiguous_row_selections,
6362 selection,
6363 &display_map,
6364 &mut selections,
6365 );
6366
6367 let start_point = Point::new(start_row.0, 0);
6368 let end_point = Point::new(
6369 end_row.previous_row().0,
6370 buffer.line_len(end_row.previous_row()),
6371 );
6372 let text = buffer
6373 .text_for_range(start_point..end_point)
6374 .collect::<String>();
6375
6376 let mut lines = text.split('\n').collect_vec();
6377
6378 let lines_before = lines.len();
6379 callback(&mut lines);
6380 let lines_after = lines.len();
6381
6382 edits.push((start_point..end_point, lines.join("\n")));
6383
6384 // Selections must change based on added and removed line count
6385 let start_row =
6386 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6387 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6388 new_selections.push(Selection {
6389 id: selection.id,
6390 start: start_row,
6391 end: end_row,
6392 goal: SelectionGoal::None,
6393 reversed: selection.reversed,
6394 });
6395
6396 if lines_after > lines_before {
6397 added_lines += lines_after - lines_before;
6398 } else if lines_before > lines_after {
6399 removed_lines += lines_before - lines_after;
6400 }
6401 }
6402
6403 self.transact(cx, |this, cx| {
6404 let buffer = this.buffer.update(cx, |buffer, cx| {
6405 buffer.edit(edits, None, cx);
6406 buffer.snapshot(cx)
6407 });
6408
6409 // Recalculate offsets on newly edited buffer
6410 let new_selections = new_selections
6411 .iter()
6412 .map(|s| {
6413 let start_point = Point::new(s.start.0, 0);
6414 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6415 Selection {
6416 id: s.id,
6417 start: buffer.point_to_offset(start_point),
6418 end: buffer.point_to_offset(end_point),
6419 goal: s.goal,
6420 reversed: s.reversed,
6421 }
6422 })
6423 .collect();
6424
6425 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6426 s.select(new_selections);
6427 });
6428
6429 this.request_autoscroll(Autoscroll::fit(), cx);
6430 });
6431 }
6432
6433 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6434 self.manipulate_text(cx, |text| text.to_uppercase())
6435 }
6436
6437 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6438 self.manipulate_text(cx, |text| text.to_lowercase())
6439 }
6440
6441 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6442 self.manipulate_text(cx, |text| {
6443 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6444 // https://github.com/rutrum/convert-case/issues/16
6445 text.split('\n')
6446 .map(|line| line.to_case(Case::Title))
6447 .join("\n")
6448 })
6449 }
6450
6451 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6452 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6453 }
6454
6455 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6456 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6457 }
6458
6459 pub fn convert_to_upper_camel_case(
6460 &mut self,
6461 _: &ConvertToUpperCamelCase,
6462 cx: &mut ViewContext<Self>,
6463 ) {
6464 self.manipulate_text(cx, |text| {
6465 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6466 // https://github.com/rutrum/convert-case/issues/16
6467 text.split('\n')
6468 .map(|line| line.to_case(Case::UpperCamel))
6469 .join("\n")
6470 })
6471 }
6472
6473 pub fn convert_to_lower_camel_case(
6474 &mut self,
6475 _: &ConvertToLowerCamelCase,
6476 cx: &mut ViewContext<Self>,
6477 ) {
6478 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6479 }
6480
6481 pub fn convert_to_opposite_case(
6482 &mut self,
6483 _: &ConvertToOppositeCase,
6484 cx: &mut ViewContext<Self>,
6485 ) {
6486 self.manipulate_text(cx, |text| {
6487 text.chars()
6488 .fold(String::with_capacity(text.len()), |mut t, c| {
6489 if c.is_uppercase() {
6490 t.extend(c.to_lowercase());
6491 } else {
6492 t.extend(c.to_uppercase());
6493 }
6494 t
6495 })
6496 })
6497 }
6498
6499 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6500 where
6501 Fn: FnMut(&str) -> String,
6502 {
6503 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6504 let buffer = self.buffer.read(cx).snapshot(cx);
6505
6506 let mut new_selections = Vec::new();
6507 let mut edits = Vec::new();
6508 let mut selection_adjustment = 0i32;
6509
6510 for selection in self.selections.all::<usize>(cx) {
6511 let selection_is_empty = selection.is_empty();
6512
6513 let (start, end) = if selection_is_empty {
6514 let word_range = movement::surrounding_word(
6515 &display_map,
6516 selection.start.to_display_point(&display_map),
6517 );
6518 let start = word_range.start.to_offset(&display_map, Bias::Left);
6519 let end = word_range.end.to_offset(&display_map, Bias::Left);
6520 (start, end)
6521 } else {
6522 (selection.start, selection.end)
6523 };
6524
6525 let text = buffer.text_for_range(start..end).collect::<String>();
6526 let old_length = text.len() as i32;
6527 let text = callback(&text);
6528
6529 new_selections.push(Selection {
6530 start: (start as i32 - selection_adjustment) as usize,
6531 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6532 goal: SelectionGoal::None,
6533 ..selection
6534 });
6535
6536 selection_adjustment += old_length - text.len() as i32;
6537
6538 edits.push((start..end, text));
6539 }
6540
6541 self.transact(cx, |this, cx| {
6542 this.buffer.update(cx, |buffer, cx| {
6543 buffer.edit(edits, None, cx);
6544 });
6545
6546 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6547 s.select(new_selections);
6548 });
6549
6550 this.request_autoscroll(Autoscroll::fit(), cx);
6551 });
6552 }
6553
6554 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6555 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6556 let buffer = &display_map.buffer_snapshot;
6557 let selections = self.selections.all::<Point>(cx);
6558
6559 let mut edits = Vec::new();
6560 let mut selections_iter = selections.iter().peekable();
6561 while let Some(selection) = selections_iter.next() {
6562 // Avoid duplicating the same lines twice.
6563 let mut rows = selection.spanned_rows(false, &display_map);
6564
6565 while let Some(next_selection) = selections_iter.peek() {
6566 let next_rows = next_selection.spanned_rows(false, &display_map);
6567 if next_rows.start < rows.end {
6568 rows.end = next_rows.end;
6569 selections_iter.next().unwrap();
6570 } else {
6571 break;
6572 }
6573 }
6574
6575 // Copy the text from the selected row region and splice it either at the start
6576 // or end of the region.
6577 let start = Point::new(rows.start.0, 0);
6578 let end = Point::new(
6579 rows.end.previous_row().0,
6580 buffer.line_len(rows.end.previous_row()),
6581 );
6582 let text = buffer
6583 .text_for_range(start..end)
6584 .chain(Some("\n"))
6585 .collect::<String>();
6586 let insert_location = if upwards {
6587 Point::new(rows.end.0, 0)
6588 } else {
6589 start
6590 };
6591 edits.push((insert_location..insert_location, text));
6592 }
6593
6594 self.transact(cx, |this, cx| {
6595 this.buffer.update(cx, |buffer, cx| {
6596 buffer.edit(edits, None, cx);
6597 });
6598
6599 this.request_autoscroll(Autoscroll::fit(), cx);
6600 });
6601 }
6602
6603 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6604 self.duplicate_line(true, cx);
6605 }
6606
6607 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6608 self.duplicate_line(false, cx);
6609 }
6610
6611 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6612 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6613 let buffer = self.buffer.read(cx).snapshot(cx);
6614
6615 let mut edits = Vec::new();
6616 let mut unfold_ranges = Vec::new();
6617 let mut refold_ranges = Vec::new();
6618
6619 let selections = self.selections.all::<Point>(cx);
6620 let mut selections = selections.iter().peekable();
6621 let mut contiguous_row_selections = Vec::new();
6622 let mut new_selections = Vec::new();
6623
6624 while let Some(selection) = selections.next() {
6625 // Find all the selections that span a contiguous row range
6626 let (start_row, end_row) = consume_contiguous_rows(
6627 &mut contiguous_row_selections,
6628 selection,
6629 &display_map,
6630 &mut selections,
6631 );
6632
6633 // Move the text spanned by the row range to be before the line preceding the row range
6634 if start_row.0 > 0 {
6635 let range_to_move = Point::new(
6636 start_row.previous_row().0,
6637 buffer.line_len(start_row.previous_row()),
6638 )
6639 ..Point::new(
6640 end_row.previous_row().0,
6641 buffer.line_len(end_row.previous_row()),
6642 );
6643 let insertion_point = display_map
6644 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6645 .0;
6646
6647 // Don't move lines across excerpts
6648 if buffer
6649 .excerpt_boundaries_in_range((
6650 Bound::Excluded(insertion_point),
6651 Bound::Included(range_to_move.end),
6652 ))
6653 .next()
6654 .is_none()
6655 {
6656 let text = buffer
6657 .text_for_range(range_to_move.clone())
6658 .flat_map(|s| s.chars())
6659 .skip(1)
6660 .chain(['\n'])
6661 .collect::<String>();
6662
6663 edits.push((
6664 buffer.anchor_after(range_to_move.start)
6665 ..buffer.anchor_before(range_to_move.end),
6666 String::new(),
6667 ));
6668 let insertion_anchor = buffer.anchor_after(insertion_point);
6669 edits.push((insertion_anchor..insertion_anchor, text));
6670
6671 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6672
6673 // Move selections up
6674 new_selections.extend(contiguous_row_selections.drain(..).map(
6675 |mut selection| {
6676 selection.start.row -= row_delta;
6677 selection.end.row -= row_delta;
6678 selection
6679 },
6680 ));
6681
6682 // Move folds up
6683 unfold_ranges.push(range_to_move.clone());
6684 for fold in display_map.folds_in_range(
6685 buffer.anchor_before(range_to_move.start)
6686 ..buffer.anchor_after(range_to_move.end),
6687 ) {
6688 let mut start = fold.range.start.to_point(&buffer);
6689 let mut end = fold.range.end.to_point(&buffer);
6690 start.row -= row_delta;
6691 end.row -= row_delta;
6692 refold_ranges.push((start..end, fold.placeholder.clone()));
6693 }
6694 }
6695 }
6696
6697 // If we didn't move line(s), preserve the existing selections
6698 new_selections.append(&mut contiguous_row_selections);
6699 }
6700
6701 self.transact(cx, |this, cx| {
6702 this.unfold_ranges(unfold_ranges, true, true, cx);
6703 this.buffer.update(cx, |buffer, cx| {
6704 for (range, text) in edits {
6705 buffer.edit([(range, text)], None, cx);
6706 }
6707 });
6708 this.fold_ranges(refold_ranges, true, cx);
6709 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6710 s.select(new_selections);
6711 })
6712 });
6713 }
6714
6715 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6716 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6717 let buffer = self.buffer.read(cx).snapshot(cx);
6718
6719 let mut edits = Vec::new();
6720 let mut unfold_ranges = Vec::new();
6721 let mut refold_ranges = Vec::new();
6722
6723 let selections = self.selections.all::<Point>(cx);
6724 let mut selections = selections.iter().peekable();
6725 let mut contiguous_row_selections = Vec::new();
6726 let mut new_selections = Vec::new();
6727
6728 while let Some(selection) = selections.next() {
6729 // Find all the selections that span a contiguous row range
6730 let (start_row, end_row) = consume_contiguous_rows(
6731 &mut contiguous_row_selections,
6732 selection,
6733 &display_map,
6734 &mut selections,
6735 );
6736
6737 // Move the text spanned by the row range to be after the last line of the row range
6738 if end_row.0 <= buffer.max_point().row {
6739 let range_to_move =
6740 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6741 let insertion_point = display_map
6742 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6743 .0;
6744
6745 // Don't move lines across excerpt boundaries
6746 if buffer
6747 .excerpt_boundaries_in_range((
6748 Bound::Excluded(range_to_move.start),
6749 Bound::Included(insertion_point),
6750 ))
6751 .next()
6752 .is_none()
6753 {
6754 let mut text = String::from("\n");
6755 text.extend(buffer.text_for_range(range_to_move.clone()));
6756 text.pop(); // Drop trailing newline
6757 edits.push((
6758 buffer.anchor_after(range_to_move.start)
6759 ..buffer.anchor_before(range_to_move.end),
6760 String::new(),
6761 ));
6762 let insertion_anchor = buffer.anchor_after(insertion_point);
6763 edits.push((insertion_anchor..insertion_anchor, text));
6764
6765 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6766
6767 // Move selections down
6768 new_selections.extend(contiguous_row_selections.drain(..).map(
6769 |mut selection| {
6770 selection.start.row += row_delta;
6771 selection.end.row += row_delta;
6772 selection
6773 },
6774 ));
6775
6776 // Move folds down
6777 unfold_ranges.push(range_to_move.clone());
6778 for fold in display_map.folds_in_range(
6779 buffer.anchor_before(range_to_move.start)
6780 ..buffer.anchor_after(range_to_move.end),
6781 ) {
6782 let mut start = fold.range.start.to_point(&buffer);
6783 let mut end = fold.range.end.to_point(&buffer);
6784 start.row += row_delta;
6785 end.row += row_delta;
6786 refold_ranges.push((start..end, fold.placeholder.clone()));
6787 }
6788 }
6789 }
6790
6791 // If we didn't move line(s), preserve the existing selections
6792 new_selections.append(&mut contiguous_row_selections);
6793 }
6794
6795 self.transact(cx, |this, cx| {
6796 this.unfold_ranges(unfold_ranges, true, true, cx);
6797 this.buffer.update(cx, |buffer, cx| {
6798 for (range, text) in edits {
6799 buffer.edit([(range, text)], None, cx);
6800 }
6801 });
6802 this.fold_ranges(refold_ranges, true, cx);
6803 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6804 });
6805 }
6806
6807 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6808 let text_layout_details = &self.text_layout_details(cx);
6809 self.transact(cx, |this, cx| {
6810 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6811 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6812 let line_mode = s.line_mode;
6813 s.move_with(|display_map, selection| {
6814 if !selection.is_empty() || line_mode {
6815 return;
6816 }
6817
6818 let mut head = selection.head();
6819 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6820 if head.column() == display_map.line_len(head.row()) {
6821 transpose_offset = display_map
6822 .buffer_snapshot
6823 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6824 }
6825
6826 if transpose_offset == 0 {
6827 return;
6828 }
6829
6830 *head.column_mut() += 1;
6831 head = display_map.clip_point(head, Bias::Right);
6832 let goal = SelectionGoal::HorizontalPosition(
6833 display_map
6834 .x_for_display_point(head, text_layout_details)
6835 .into(),
6836 );
6837 selection.collapse_to(head, goal);
6838
6839 let transpose_start = display_map
6840 .buffer_snapshot
6841 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6842 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6843 let transpose_end = display_map
6844 .buffer_snapshot
6845 .clip_offset(transpose_offset + 1, Bias::Right);
6846 if let Some(ch) =
6847 display_map.buffer_snapshot.chars_at(transpose_start).next()
6848 {
6849 edits.push((transpose_start..transpose_offset, String::new()));
6850 edits.push((transpose_end..transpose_end, ch.to_string()));
6851 }
6852 }
6853 });
6854 edits
6855 });
6856 this.buffer
6857 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6858 let selections = this.selections.all::<usize>(cx);
6859 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6860 s.select(selections);
6861 });
6862 });
6863 }
6864
6865 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6866 self.rewrap_impl(true, cx)
6867 }
6868
6869 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6870 let buffer = self.buffer.read(cx).snapshot(cx);
6871 let selections = self.selections.all::<Point>(cx);
6872 let mut selections = selections.iter().peekable();
6873
6874 let mut edits = Vec::new();
6875 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6876
6877 while let Some(selection) = selections.next() {
6878 let mut start_row = selection.start.row;
6879 let mut end_row = selection.end.row;
6880
6881 // Skip selections that overlap with a range that has already been rewrapped.
6882 let selection_range = start_row..end_row;
6883 if rewrapped_row_ranges
6884 .iter()
6885 .any(|range| range.overlaps(&selection_range))
6886 {
6887 continue;
6888 }
6889
6890 let mut should_rewrap = !only_text;
6891
6892 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6893 match language_scope.language_name().0.as_ref() {
6894 "Markdown" | "Plain Text" => {
6895 should_rewrap = true;
6896 }
6897 _ => {}
6898 }
6899 }
6900
6901 // Since not all lines in the selection may be at the same indent
6902 // level, choose the indent size that is the most common between all
6903 // of the lines.
6904 //
6905 // If there is a tie, we use the deepest indent.
6906 let (indent_size, indent_end) = {
6907 let mut indent_size_occurrences = HashMap::default();
6908 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6909
6910 for row in start_row..=end_row {
6911 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6912 rows_by_indent_size.entry(indent).or_default().push(row);
6913 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6914 }
6915
6916 let indent_size = indent_size_occurrences
6917 .into_iter()
6918 .max_by_key(|(indent, count)| (*count, indent.len))
6919 .map(|(indent, _)| indent)
6920 .unwrap_or_default();
6921 let row = rows_by_indent_size[&indent_size][0];
6922 let indent_end = Point::new(row, indent_size.len);
6923
6924 (indent_size, indent_end)
6925 };
6926
6927 let mut line_prefix = indent_size.chars().collect::<String>();
6928
6929 if let Some(comment_prefix) =
6930 buffer
6931 .language_scope_at(selection.head())
6932 .and_then(|language| {
6933 language
6934 .line_comment_prefixes()
6935 .iter()
6936 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6937 .cloned()
6938 })
6939 {
6940 line_prefix.push_str(&comment_prefix);
6941 should_rewrap = true;
6942 }
6943
6944 if selection.is_empty() {
6945 'expand_upwards: while start_row > 0 {
6946 let prev_row = start_row - 1;
6947 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6948 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6949 {
6950 start_row = prev_row;
6951 } else {
6952 break 'expand_upwards;
6953 }
6954 }
6955
6956 'expand_downwards: while end_row < buffer.max_point().row {
6957 let next_row = end_row + 1;
6958 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6959 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6960 {
6961 end_row = next_row;
6962 } else {
6963 break 'expand_downwards;
6964 }
6965 }
6966 }
6967
6968 if !should_rewrap {
6969 continue;
6970 }
6971
6972 let start = Point::new(start_row, 0);
6973 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6974 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6975 let Some(lines_without_prefixes) = selection_text
6976 .lines()
6977 .map(|line| {
6978 line.strip_prefix(&line_prefix)
6979 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6980 .ok_or_else(|| {
6981 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6982 })
6983 })
6984 .collect::<Result<Vec<_>, _>>()
6985 .log_err()
6986 else {
6987 continue;
6988 };
6989
6990 let unwrapped_text = lines_without_prefixes.join(" ");
6991 let wrap_column = buffer
6992 .settings_at(Point::new(start_row, 0), cx)
6993 .preferred_line_length as usize;
6994 let mut wrapped_text = String::new();
6995 let mut current_line = line_prefix.clone();
6996 for word in unwrapped_text.split_whitespace() {
6997 if current_line.len() + word.len() >= wrap_column {
6998 wrapped_text.push_str(¤t_line);
6999 wrapped_text.push('\n');
7000 current_line.truncate(line_prefix.len());
7001 }
7002
7003 if current_line.len() > line_prefix.len() {
7004 current_line.push(' ');
7005 }
7006
7007 current_line.push_str(word);
7008 }
7009
7010 if !current_line.is_empty() {
7011 wrapped_text.push_str(¤t_line);
7012 }
7013
7014 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
7015 let mut offset = start.to_offset(&buffer);
7016 let mut moved_since_edit = true;
7017
7018 for change in diff.iter_all_changes() {
7019 let value = change.value();
7020 match change.tag() {
7021 ChangeTag::Equal => {
7022 offset += value.len();
7023 moved_since_edit = true;
7024 }
7025 ChangeTag::Delete => {
7026 let start = buffer.anchor_after(offset);
7027 let end = buffer.anchor_before(offset + value.len());
7028
7029 if moved_since_edit {
7030 edits.push((start..end, String::new()));
7031 } else {
7032 edits.last_mut().unwrap().0.end = end;
7033 }
7034
7035 offset += value.len();
7036 moved_since_edit = false;
7037 }
7038 ChangeTag::Insert => {
7039 if moved_since_edit {
7040 let anchor = buffer.anchor_after(offset);
7041 edits.push((anchor..anchor, value.to_string()));
7042 } else {
7043 edits.last_mut().unwrap().1.push_str(value);
7044 }
7045
7046 moved_since_edit = false;
7047 }
7048 }
7049 }
7050
7051 rewrapped_row_ranges.push(start_row..=end_row);
7052 }
7053
7054 self.buffer
7055 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7056 }
7057
7058 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7059 let mut text = String::new();
7060 let buffer = self.buffer.read(cx).snapshot(cx);
7061 let mut selections = self.selections.all::<Point>(cx);
7062 let mut clipboard_selections = Vec::with_capacity(selections.len());
7063 {
7064 let max_point = buffer.max_point();
7065 let mut is_first = true;
7066 for selection in &mut selections {
7067 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7068 if is_entire_line {
7069 selection.start = Point::new(selection.start.row, 0);
7070 if !selection.is_empty() && selection.end.column == 0 {
7071 selection.end = cmp::min(max_point, selection.end);
7072 } else {
7073 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7074 }
7075 selection.goal = SelectionGoal::None;
7076 }
7077 if is_first {
7078 is_first = false;
7079 } else {
7080 text += "\n";
7081 }
7082 let mut len = 0;
7083 for chunk in buffer.text_for_range(selection.start..selection.end) {
7084 text.push_str(chunk);
7085 len += chunk.len();
7086 }
7087 clipboard_selections.push(ClipboardSelection {
7088 len,
7089 is_entire_line,
7090 first_line_indent: buffer
7091 .indent_size_for_line(MultiBufferRow(selection.start.row))
7092 .len,
7093 });
7094 }
7095 }
7096
7097 self.transact(cx, |this, cx| {
7098 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7099 s.select(selections);
7100 });
7101 this.insert("", cx);
7102 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7103 text,
7104 clipboard_selections,
7105 ));
7106 });
7107 }
7108
7109 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7110 let selections = self.selections.all::<Point>(cx);
7111 let buffer = self.buffer.read(cx).read(cx);
7112 let mut text = String::new();
7113
7114 let mut clipboard_selections = Vec::with_capacity(selections.len());
7115 {
7116 let max_point = buffer.max_point();
7117 let mut is_first = true;
7118 for selection in selections.iter() {
7119 let mut start = selection.start;
7120 let mut end = selection.end;
7121 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7122 if is_entire_line {
7123 start = Point::new(start.row, 0);
7124 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7125 }
7126 if is_first {
7127 is_first = false;
7128 } else {
7129 text += "\n";
7130 }
7131 let mut len = 0;
7132 for chunk in buffer.text_for_range(start..end) {
7133 text.push_str(chunk);
7134 len += chunk.len();
7135 }
7136 clipboard_selections.push(ClipboardSelection {
7137 len,
7138 is_entire_line,
7139 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7140 });
7141 }
7142 }
7143
7144 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7145 text,
7146 clipboard_selections,
7147 ));
7148 }
7149
7150 pub fn do_paste(
7151 &mut self,
7152 text: &String,
7153 clipboard_selections: Option<Vec<ClipboardSelection>>,
7154 handle_entire_lines: bool,
7155 cx: &mut ViewContext<Self>,
7156 ) {
7157 if self.read_only(cx) {
7158 return;
7159 }
7160
7161 let clipboard_text = Cow::Borrowed(text);
7162
7163 self.transact(cx, |this, cx| {
7164 if let Some(mut clipboard_selections) = clipboard_selections {
7165 let old_selections = this.selections.all::<usize>(cx);
7166 let all_selections_were_entire_line =
7167 clipboard_selections.iter().all(|s| s.is_entire_line);
7168 let first_selection_indent_column =
7169 clipboard_selections.first().map(|s| s.first_line_indent);
7170 if clipboard_selections.len() != old_selections.len() {
7171 clipboard_selections.drain(..);
7172 }
7173
7174 this.buffer.update(cx, |buffer, cx| {
7175 let snapshot = buffer.read(cx);
7176 let mut start_offset = 0;
7177 let mut edits = Vec::new();
7178 let mut original_indent_columns = Vec::new();
7179 for (ix, selection) in old_selections.iter().enumerate() {
7180 let to_insert;
7181 let entire_line;
7182 let original_indent_column;
7183 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7184 let end_offset = start_offset + clipboard_selection.len;
7185 to_insert = &clipboard_text[start_offset..end_offset];
7186 entire_line = clipboard_selection.is_entire_line;
7187 start_offset = end_offset + 1;
7188 original_indent_column = Some(clipboard_selection.first_line_indent);
7189 } else {
7190 to_insert = clipboard_text.as_str();
7191 entire_line = all_selections_were_entire_line;
7192 original_indent_column = first_selection_indent_column
7193 }
7194
7195 // If the corresponding selection was empty when this slice of the
7196 // clipboard text was written, then the entire line containing the
7197 // selection was copied. If this selection is also currently empty,
7198 // then paste the line before the current line of the buffer.
7199 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7200 let column = selection.start.to_point(&snapshot).column as usize;
7201 let line_start = selection.start - column;
7202 line_start..line_start
7203 } else {
7204 selection.range()
7205 };
7206
7207 edits.push((range, to_insert));
7208 original_indent_columns.extend(original_indent_column);
7209 }
7210 drop(snapshot);
7211
7212 buffer.edit(
7213 edits,
7214 Some(AutoindentMode::Block {
7215 original_indent_columns,
7216 }),
7217 cx,
7218 );
7219 });
7220
7221 let selections = this.selections.all::<usize>(cx);
7222 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7223 } else {
7224 this.insert(&clipboard_text, cx);
7225 }
7226 });
7227 }
7228
7229 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7230 if let Some(item) = cx.read_from_clipboard() {
7231 let entries = item.entries();
7232
7233 match entries.first() {
7234 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7235 // of all the pasted entries.
7236 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7237 .do_paste(
7238 clipboard_string.text(),
7239 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7240 true,
7241 cx,
7242 ),
7243 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7244 }
7245 }
7246 }
7247
7248 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7249 if self.read_only(cx) {
7250 return;
7251 }
7252
7253 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7254 if let Some((selections, _)) =
7255 self.selection_history.transaction(transaction_id).cloned()
7256 {
7257 self.change_selections(None, cx, |s| {
7258 s.select_anchors(selections.to_vec());
7259 });
7260 }
7261 self.request_autoscroll(Autoscroll::fit(), cx);
7262 self.unmark_text(cx);
7263 self.refresh_inline_completion(true, false, cx);
7264 cx.emit(EditorEvent::Edited { transaction_id });
7265 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7266 }
7267 }
7268
7269 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7270 if self.read_only(cx) {
7271 return;
7272 }
7273
7274 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7275 if let Some((_, Some(selections))) =
7276 self.selection_history.transaction(transaction_id).cloned()
7277 {
7278 self.change_selections(None, cx, |s| {
7279 s.select_anchors(selections.to_vec());
7280 });
7281 }
7282 self.request_autoscroll(Autoscroll::fit(), cx);
7283 self.unmark_text(cx);
7284 self.refresh_inline_completion(true, false, cx);
7285 cx.emit(EditorEvent::Edited { transaction_id });
7286 }
7287 }
7288
7289 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7290 self.buffer
7291 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7292 }
7293
7294 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7295 self.buffer
7296 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7297 }
7298
7299 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7300 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7301 let line_mode = s.line_mode;
7302 s.move_with(|map, selection| {
7303 let cursor = if selection.is_empty() && !line_mode {
7304 movement::left(map, selection.start)
7305 } else {
7306 selection.start
7307 };
7308 selection.collapse_to(cursor, SelectionGoal::None);
7309 });
7310 })
7311 }
7312
7313 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7314 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7315 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7316 })
7317 }
7318
7319 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7320 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7321 let line_mode = s.line_mode;
7322 s.move_with(|map, selection| {
7323 let cursor = if selection.is_empty() && !line_mode {
7324 movement::right(map, selection.end)
7325 } else {
7326 selection.end
7327 };
7328 selection.collapse_to(cursor, SelectionGoal::None)
7329 });
7330 })
7331 }
7332
7333 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7334 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7335 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7336 })
7337 }
7338
7339 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7340 if self.take_rename(true, cx).is_some() {
7341 return;
7342 }
7343
7344 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7345 cx.propagate();
7346 return;
7347 }
7348
7349 let text_layout_details = &self.text_layout_details(cx);
7350 let selection_count = self.selections.count();
7351 let first_selection = self.selections.first_anchor();
7352
7353 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7354 let line_mode = s.line_mode;
7355 s.move_with(|map, selection| {
7356 if !selection.is_empty() && !line_mode {
7357 selection.goal = SelectionGoal::None;
7358 }
7359 let (cursor, goal) = movement::up(
7360 map,
7361 selection.start,
7362 selection.goal,
7363 false,
7364 text_layout_details,
7365 );
7366 selection.collapse_to(cursor, goal);
7367 });
7368 });
7369
7370 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7371 {
7372 cx.propagate();
7373 }
7374 }
7375
7376 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7377 if self.take_rename(true, cx).is_some() {
7378 return;
7379 }
7380
7381 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7382 cx.propagate();
7383 return;
7384 }
7385
7386 let text_layout_details = &self.text_layout_details(cx);
7387
7388 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7389 let line_mode = s.line_mode;
7390 s.move_with(|map, selection| {
7391 if !selection.is_empty() && !line_mode {
7392 selection.goal = SelectionGoal::None;
7393 }
7394 let (cursor, goal) = movement::up_by_rows(
7395 map,
7396 selection.start,
7397 action.lines,
7398 selection.goal,
7399 false,
7400 text_layout_details,
7401 );
7402 selection.collapse_to(cursor, goal);
7403 });
7404 })
7405 }
7406
7407 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7408 if self.take_rename(true, cx).is_some() {
7409 return;
7410 }
7411
7412 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7413 cx.propagate();
7414 return;
7415 }
7416
7417 let text_layout_details = &self.text_layout_details(cx);
7418
7419 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7420 let line_mode = s.line_mode;
7421 s.move_with(|map, selection| {
7422 if !selection.is_empty() && !line_mode {
7423 selection.goal = SelectionGoal::None;
7424 }
7425 let (cursor, goal) = movement::down_by_rows(
7426 map,
7427 selection.start,
7428 action.lines,
7429 selection.goal,
7430 false,
7431 text_layout_details,
7432 );
7433 selection.collapse_to(cursor, goal);
7434 });
7435 })
7436 }
7437
7438 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7439 let text_layout_details = &self.text_layout_details(cx);
7440 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7441 s.move_heads_with(|map, head, goal| {
7442 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7443 })
7444 })
7445 }
7446
7447 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7448 let text_layout_details = &self.text_layout_details(cx);
7449 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7450 s.move_heads_with(|map, head, goal| {
7451 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7452 })
7453 })
7454 }
7455
7456 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7457 let Some(row_count) = self.visible_row_count() else {
7458 return;
7459 };
7460
7461 let text_layout_details = &self.text_layout_details(cx);
7462
7463 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7464 s.move_heads_with(|map, head, goal| {
7465 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7466 })
7467 })
7468 }
7469
7470 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7471 if self.take_rename(true, cx).is_some() {
7472 return;
7473 }
7474
7475 if self
7476 .context_menu
7477 .write()
7478 .as_mut()
7479 .map(|menu| menu.select_first(self.completion_provider.as_deref(), cx))
7480 .unwrap_or(false)
7481 {
7482 return;
7483 }
7484
7485 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7486 cx.propagate();
7487 return;
7488 }
7489
7490 let Some(row_count) = self.visible_row_count() else {
7491 return;
7492 };
7493
7494 let autoscroll = if action.center_cursor {
7495 Autoscroll::center()
7496 } else {
7497 Autoscroll::fit()
7498 };
7499
7500 let text_layout_details = &self.text_layout_details(cx);
7501
7502 self.change_selections(Some(autoscroll), cx, |s| {
7503 let line_mode = s.line_mode;
7504 s.move_with(|map, selection| {
7505 if !selection.is_empty() && !line_mode {
7506 selection.goal = SelectionGoal::None;
7507 }
7508 let (cursor, goal) = movement::up_by_rows(
7509 map,
7510 selection.end,
7511 row_count,
7512 selection.goal,
7513 false,
7514 text_layout_details,
7515 );
7516 selection.collapse_to(cursor, goal);
7517 });
7518 });
7519 }
7520
7521 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7522 let text_layout_details = &self.text_layout_details(cx);
7523 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7524 s.move_heads_with(|map, head, goal| {
7525 movement::up(map, head, goal, false, text_layout_details)
7526 })
7527 })
7528 }
7529
7530 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7531 self.take_rename(true, cx);
7532
7533 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7534 cx.propagate();
7535 return;
7536 }
7537
7538 let text_layout_details = &self.text_layout_details(cx);
7539 let selection_count = self.selections.count();
7540 let first_selection = self.selections.first_anchor();
7541
7542 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7543 let line_mode = s.line_mode;
7544 s.move_with(|map, selection| {
7545 if !selection.is_empty() && !line_mode {
7546 selection.goal = SelectionGoal::None;
7547 }
7548 let (cursor, goal) = movement::down(
7549 map,
7550 selection.end,
7551 selection.goal,
7552 false,
7553 text_layout_details,
7554 );
7555 selection.collapse_to(cursor, goal);
7556 });
7557 });
7558
7559 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7560 {
7561 cx.propagate();
7562 }
7563 }
7564
7565 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7566 let Some(row_count) = self.visible_row_count() else {
7567 return;
7568 };
7569
7570 let text_layout_details = &self.text_layout_details(cx);
7571
7572 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7573 s.move_heads_with(|map, head, goal| {
7574 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7575 })
7576 })
7577 }
7578
7579 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7580 if self.take_rename(true, cx).is_some() {
7581 return;
7582 }
7583
7584 if self
7585 .context_menu
7586 .write()
7587 .as_mut()
7588 .map(|menu| menu.select_last(self.completion_provider.as_deref(), cx))
7589 .unwrap_or(false)
7590 {
7591 return;
7592 }
7593
7594 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7595 cx.propagate();
7596 return;
7597 }
7598
7599 let Some(row_count) = self.visible_row_count() else {
7600 return;
7601 };
7602
7603 let autoscroll = if action.center_cursor {
7604 Autoscroll::center()
7605 } else {
7606 Autoscroll::fit()
7607 };
7608
7609 let text_layout_details = &self.text_layout_details(cx);
7610 self.change_selections(Some(autoscroll), cx, |s| {
7611 let line_mode = s.line_mode;
7612 s.move_with(|map, selection| {
7613 if !selection.is_empty() && !line_mode {
7614 selection.goal = SelectionGoal::None;
7615 }
7616 let (cursor, goal) = movement::down_by_rows(
7617 map,
7618 selection.end,
7619 row_count,
7620 selection.goal,
7621 false,
7622 text_layout_details,
7623 );
7624 selection.collapse_to(cursor, goal);
7625 });
7626 });
7627 }
7628
7629 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7630 let text_layout_details = &self.text_layout_details(cx);
7631 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7632 s.move_heads_with(|map, head, goal| {
7633 movement::down(map, head, goal, false, text_layout_details)
7634 })
7635 });
7636 }
7637
7638 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7639 if let Some(context_menu) = self.context_menu.write().as_mut() {
7640 context_menu.select_first(self.completion_provider.as_deref(), cx);
7641 }
7642 }
7643
7644 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7645 if let Some(context_menu) = self.context_menu.write().as_mut() {
7646 context_menu.select_prev(self.completion_provider.as_deref(), cx);
7647 }
7648 }
7649
7650 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7651 if let Some(context_menu) = self.context_menu.write().as_mut() {
7652 context_menu.select_next(self.completion_provider.as_deref(), cx);
7653 }
7654 }
7655
7656 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7657 if let Some(context_menu) = self.context_menu.write().as_mut() {
7658 context_menu.select_last(self.completion_provider.as_deref(), cx);
7659 }
7660 }
7661
7662 pub fn move_to_previous_word_start(
7663 &mut self,
7664 _: &MoveToPreviousWordStart,
7665 cx: &mut ViewContext<Self>,
7666 ) {
7667 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7668 s.move_cursors_with(|map, head, _| {
7669 (
7670 movement::previous_word_start(map, head),
7671 SelectionGoal::None,
7672 )
7673 });
7674 })
7675 }
7676
7677 pub fn move_to_previous_subword_start(
7678 &mut self,
7679 _: &MoveToPreviousSubwordStart,
7680 cx: &mut ViewContext<Self>,
7681 ) {
7682 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7683 s.move_cursors_with(|map, head, _| {
7684 (
7685 movement::previous_subword_start(map, head),
7686 SelectionGoal::None,
7687 )
7688 });
7689 })
7690 }
7691
7692 pub fn select_to_previous_word_start(
7693 &mut self,
7694 _: &SelectToPreviousWordStart,
7695 cx: &mut ViewContext<Self>,
7696 ) {
7697 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7698 s.move_heads_with(|map, head, _| {
7699 (
7700 movement::previous_word_start(map, head),
7701 SelectionGoal::None,
7702 )
7703 });
7704 })
7705 }
7706
7707 pub fn select_to_previous_subword_start(
7708 &mut self,
7709 _: &SelectToPreviousSubwordStart,
7710 cx: &mut ViewContext<Self>,
7711 ) {
7712 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7713 s.move_heads_with(|map, head, _| {
7714 (
7715 movement::previous_subword_start(map, head),
7716 SelectionGoal::None,
7717 )
7718 });
7719 })
7720 }
7721
7722 pub fn delete_to_previous_word_start(
7723 &mut self,
7724 action: &DeleteToPreviousWordStart,
7725 cx: &mut ViewContext<Self>,
7726 ) {
7727 self.transact(cx, |this, cx| {
7728 this.select_autoclose_pair(cx);
7729 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7730 let line_mode = s.line_mode;
7731 s.move_with(|map, selection| {
7732 if selection.is_empty() && !line_mode {
7733 let cursor = if action.ignore_newlines {
7734 movement::previous_word_start(map, selection.head())
7735 } else {
7736 movement::previous_word_start_or_newline(map, selection.head())
7737 };
7738 selection.set_head(cursor, SelectionGoal::None);
7739 }
7740 });
7741 });
7742 this.insert("", cx);
7743 });
7744 }
7745
7746 pub fn delete_to_previous_subword_start(
7747 &mut self,
7748 _: &DeleteToPreviousSubwordStart,
7749 cx: &mut ViewContext<Self>,
7750 ) {
7751 self.transact(cx, |this, cx| {
7752 this.select_autoclose_pair(cx);
7753 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7754 let line_mode = s.line_mode;
7755 s.move_with(|map, selection| {
7756 if selection.is_empty() && !line_mode {
7757 let cursor = movement::previous_subword_start(map, selection.head());
7758 selection.set_head(cursor, SelectionGoal::None);
7759 }
7760 });
7761 });
7762 this.insert("", cx);
7763 });
7764 }
7765
7766 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7767 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7768 s.move_cursors_with(|map, head, _| {
7769 (movement::next_word_end(map, head), SelectionGoal::None)
7770 });
7771 })
7772 }
7773
7774 pub fn move_to_next_subword_end(
7775 &mut self,
7776 _: &MoveToNextSubwordEnd,
7777 cx: &mut ViewContext<Self>,
7778 ) {
7779 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7780 s.move_cursors_with(|map, head, _| {
7781 (movement::next_subword_end(map, head), SelectionGoal::None)
7782 });
7783 })
7784 }
7785
7786 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7787 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7788 s.move_heads_with(|map, head, _| {
7789 (movement::next_word_end(map, head), SelectionGoal::None)
7790 });
7791 })
7792 }
7793
7794 pub fn select_to_next_subword_end(
7795 &mut self,
7796 _: &SelectToNextSubwordEnd,
7797 cx: &mut ViewContext<Self>,
7798 ) {
7799 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7800 s.move_heads_with(|map, head, _| {
7801 (movement::next_subword_end(map, head), SelectionGoal::None)
7802 });
7803 })
7804 }
7805
7806 pub fn delete_to_next_word_end(
7807 &mut self,
7808 action: &DeleteToNextWordEnd,
7809 cx: &mut ViewContext<Self>,
7810 ) {
7811 self.transact(cx, |this, cx| {
7812 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7813 let line_mode = s.line_mode;
7814 s.move_with(|map, selection| {
7815 if selection.is_empty() && !line_mode {
7816 let cursor = if action.ignore_newlines {
7817 movement::next_word_end(map, selection.head())
7818 } else {
7819 movement::next_word_end_or_newline(map, selection.head())
7820 };
7821 selection.set_head(cursor, SelectionGoal::None);
7822 }
7823 });
7824 });
7825 this.insert("", cx);
7826 });
7827 }
7828
7829 pub fn delete_to_next_subword_end(
7830 &mut self,
7831 _: &DeleteToNextSubwordEnd,
7832 cx: &mut ViewContext<Self>,
7833 ) {
7834 self.transact(cx, |this, cx| {
7835 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7836 s.move_with(|map, selection| {
7837 if selection.is_empty() {
7838 let cursor = movement::next_subword_end(map, selection.head());
7839 selection.set_head(cursor, SelectionGoal::None);
7840 }
7841 });
7842 });
7843 this.insert("", cx);
7844 });
7845 }
7846
7847 pub fn move_to_beginning_of_line(
7848 &mut self,
7849 action: &MoveToBeginningOfLine,
7850 cx: &mut ViewContext<Self>,
7851 ) {
7852 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7853 s.move_cursors_with(|map, head, _| {
7854 (
7855 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7856 SelectionGoal::None,
7857 )
7858 });
7859 })
7860 }
7861
7862 pub fn select_to_beginning_of_line(
7863 &mut self,
7864 action: &SelectToBeginningOfLine,
7865 cx: &mut ViewContext<Self>,
7866 ) {
7867 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7868 s.move_heads_with(|map, head, _| {
7869 (
7870 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7871 SelectionGoal::None,
7872 )
7873 });
7874 });
7875 }
7876
7877 pub fn delete_to_beginning_of_line(
7878 &mut self,
7879 _: &DeleteToBeginningOfLine,
7880 cx: &mut ViewContext<Self>,
7881 ) {
7882 self.transact(cx, |this, cx| {
7883 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7884 s.move_with(|_, selection| {
7885 selection.reversed = true;
7886 });
7887 });
7888
7889 this.select_to_beginning_of_line(
7890 &SelectToBeginningOfLine {
7891 stop_at_soft_wraps: false,
7892 },
7893 cx,
7894 );
7895 this.backspace(&Backspace, cx);
7896 });
7897 }
7898
7899 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7900 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7901 s.move_cursors_with(|map, head, _| {
7902 (
7903 movement::line_end(map, head, action.stop_at_soft_wraps),
7904 SelectionGoal::None,
7905 )
7906 });
7907 })
7908 }
7909
7910 pub fn select_to_end_of_line(
7911 &mut self,
7912 action: &SelectToEndOfLine,
7913 cx: &mut ViewContext<Self>,
7914 ) {
7915 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7916 s.move_heads_with(|map, head, _| {
7917 (
7918 movement::line_end(map, head, action.stop_at_soft_wraps),
7919 SelectionGoal::None,
7920 )
7921 });
7922 })
7923 }
7924
7925 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7926 self.transact(cx, |this, cx| {
7927 this.select_to_end_of_line(
7928 &SelectToEndOfLine {
7929 stop_at_soft_wraps: false,
7930 },
7931 cx,
7932 );
7933 this.delete(&Delete, cx);
7934 });
7935 }
7936
7937 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7938 self.transact(cx, |this, cx| {
7939 this.select_to_end_of_line(
7940 &SelectToEndOfLine {
7941 stop_at_soft_wraps: false,
7942 },
7943 cx,
7944 );
7945 this.cut(&Cut, cx);
7946 });
7947 }
7948
7949 pub fn move_to_start_of_paragraph(
7950 &mut self,
7951 _: &MoveToStartOfParagraph,
7952 cx: &mut ViewContext<Self>,
7953 ) {
7954 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7955 cx.propagate();
7956 return;
7957 }
7958
7959 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7960 s.move_with(|map, selection| {
7961 selection.collapse_to(
7962 movement::start_of_paragraph(map, selection.head(), 1),
7963 SelectionGoal::None,
7964 )
7965 });
7966 })
7967 }
7968
7969 pub fn move_to_end_of_paragraph(
7970 &mut self,
7971 _: &MoveToEndOfParagraph,
7972 cx: &mut ViewContext<Self>,
7973 ) {
7974 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7975 cx.propagate();
7976 return;
7977 }
7978
7979 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7980 s.move_with(|map, selection| {
7981 selection.collapse_to(
7982 movement::end_of_paragraph(map, selection.head(), 1),
7983 SelectionGoal::None,
7984 )
7985 });
7986 })
7987 }
7988
7989 pub fn select_to_start_of_paragraph(
7990 &mut self,
7991 _: &SelectToStartOfParagraph,
7992 cx: &mut ViewContext<Self>,
7993 ) {
7994 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7995 cx.propagate();
7996 return;
7997 }
7998
7999 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8000 s.move_heads_with(|map, head, _| {
8001 (
8002 movement::start_of_paragraph(map, head, 1),
8003 SelectionGoal::None,
8004 )
8005 });
8006 })
8007 }
8008
8009 pub fn select_to_end_of_paragraph(
8010 &mut self,
8011 _: &SelectToEndOfParagraph,
8012 cx: &mut ViewContext<Self>,
8013 ) {
8014 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8015 cx.propagate();
8016 return;
8017 }
8018
8019 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8020 s.move_heads_with(|map, head, _| {
8021 (
8022 movement::end_of_paragraph(map, head, 1),
8023 SelectionGoal::None,
8024 )
8025 });
8026 })
8027 }
8028
8029 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8030 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8031 cx.propagate();
8032 return;
8033 }
8034
8035 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8036 s.select_ranges(vec![0..0]);
8037 });
8038 }
8039
8040 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8041 let mut selection = self.selections.last::<Point>(cx);
8042 selection.set_head(Point::zero(), SelectionGoal::None);
8043
8044 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8045 s.select(vec![selection]);
8046 });
8047 }
8048
8049 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8050 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8051 cx.propagate();
8052 return;
8053 }
8054
8055 let cursor = self.buffer.read(cx).read(cx).len();
8056 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8057 s.select_ranges(vec![cursor..cursor])
8058 });
8059 }
8060
8061 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8062 self.nav_history = nav_history;
8063 }
8064
8065 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8066 self.nav_history.as_ref()
8067 }
8068
8069 fn push_to_nav_history(
8070 &mut self,
8071 cursor_anchor: Anchor,
8072 new_position: Option<Point>,
8073 cx: &mut ViewContext<Self>,
8074 ) {
8075 if let Some(nav_history) = self.nav_history.as_mut() {
8076 let buffer = self.buffer.read(cx).read(cx);
8077 let cursor_position = cursor_anchor.to_point(&buffer);
8078 let scroll_state = self.scroll_manager.anchor();
8079 let scroll_top_row = scroll_state.top_row(&buffer);
8080 drop(buffer);
8081
8082 if let Some(new_position) = new_position {
8083 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8084 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8085 return;
8086 }
8087 }
8088
8089 nav_history.push(
8090 Some(NavigationData {
8091 cursor_anchor,
8092 cursor_position,
8093 scroll_anchor: scroll_state,
8094 scroll_top_row,
8095 }),
8096 cx,
8097 );
8098 }
8099 }
8100
8101 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8102 let buffer = self.buffer.read(cx).snapshot(cx);
8103 let mut selection = self.selections.first::<usize>(cx);
8104 selection.set_head(buffer.len(), SelectionGoal::None);
8105 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8106 s.select(vec![selection]);
8107 });
8108 }
8109
8110 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8111 let end = self.buffer.read(cx).read(cx).len();
8112 self.change_selections(None, cx, |s| {
8113 s.select_ranges(vec![0..end]);
8114 });
8115 }
8116
8117 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8118 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8119 let mut selections = self.selections.all::<Point>(cx);
8120 let max_point = display_map.buffer_snapshot.max_point();
8121 for selection in &mut selections {
8122 let rows = selection.spanned_rows(true, &display_map);
8123 selection.start = Point::new(rows.start.0, 0);
8124 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8125 selection.reversed = false;
8126 }
8127 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8128 s.select(selections);
8129 });
8130 }
8131
8132 pub fn split_selection_into_lines(
8133 &mut self,
8134 _: &SplitSelectionIntoLines,
8135 cx: &mut ViewContext<Self>,
8136 ) {
8137 let mut to_unfold = Vec::new();
8138 let mut new_selection_ranges = Vec::new();
8139 {
8140 let selections = self.selections.all::<Point>(cx);
8141 let buffer = self.buffer.read(cx).read(cx);
8142 for selection in selections {
8143 for row in selection.start.row..selection.end.row {
8144 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8145 new_selection_ranges.push(cursor..cursor);
8146 }
8147 new_selection_ranges.push(selection.end..selection.end);
8148 to_unfold.push(selection.start..selection.end);
8149 }
8150 }
8151 self.unfold_ranges(to_unfold, true, true, cx);
8152 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8153 s.select_ranges(new_selection_ranges);
8154 });
8155 }
8156
8157 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8158 self.add_selection(true, cx);
8159 }
8160
8161 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8162 self.add_selection(false, cx);
8163 }
8164
8165 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8166 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8167 let mut selections = self.selections.all::<Point>(cx);
8168 let text_layout_details = self.text_layout_details(cx);
8169 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8170 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8171 let range = oldest_selection.display_range(&display_map).sorted();
8172
8173 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8174 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8175 let positions = start_x.min(end_x)..start_x.max(end_x);
8176
8177 selections.clear();
8178 let mut stack = Vec::new();
8179 for row in range.start.row().0..=range.end.row().0 {
8180 if let Some(selection) = self.selections.build_columnar_selection(
8181 &display_map,
8182 DisplayRow(row),
8183 &positions,
8184 oldest_selection.reversed,
8185 &text_layout_details,
8186 ) {
8187 stack.push(selection.id);
8188 selections.push(selection);
8189 }
8190 }
8191
8192 if above {
8193 stack.reverse();
8194 }
8195
8196 AddSelectionsState { above, stack }
8197 });
8198
8199 let last_added_selection = *state.stack.last().unwrap();
8200 let mut new_selections = Vec::new();
8201 if above == state.above {
8202 let end_row = if above {
8203 DisplayRow(0)
8204 } else {
8205 display_map.max_point().row()
8206 };
8207
8208 'outer: for selection in selections {
8209 if selection.id == last_added_selection {
8210 let range = selection.display_range(&display_map).sorted();
8211 debug_assert_eq!(range.start.row(), range.end.row());
8212 let mut row = range.start.row();
8213 let positions =
8214 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8215 px(start)..px(end)
8216 } else {
8217 let start_x =
8218 display_map.x_for_display_point(range.start, &text_layout_details);
8219 let end_x =
8220 display_map.x_for_display_point(range.end, &text_layout_details);
8221 start_x.min(end_x)..start_x.max(end_x)
8222 };
8223
8224 while row != end_row {
8225 if above {
8226 row.0 -= 1;
8227 } else {
8228 row.0 += 1;
8229 }
8230
8231 if let Some(new_selection) = self.selections.build_columnar_selection(
8232 &display_map,
8233 row,
8234 &positions,
8235 selection.reversed,
8236 &text_layout_details,
8237 ) {
8238 state.stack.push(new_selection.id);
8239 if above {
8240 new_selections.push(new_selection);
8241 new_selections.push(selection);
8242 } else {
8243 new_selections.push(selection);
8244 new_selections.push(new_selection);
8245 }
8246
8247 continue 'outer;
8248 }
8249 }
8250 }
8251
8252 new_selections.push(selection);
8253 }
8254 } else {
8255 new_selections = selections;
8256 new_selections.retain(|s| s.id != last_added_selection);
8257 state.stack.pop();
8258 }
8259
8260 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8261 s.select(new_selections);
8262 });
8263 if state.stack.len() > 1 {
8264 self.add_selections_state = Some(state);
8265 }
8266 }
8267
8268 pub fn select_next_match_internal(
8269 &mut self,
8270 display_map: &DisplaySnapshot,
8271 replace_newest: bool,
8272 autoscroll: Option<Autoscroll>,
8273 cx: &mut ViewContext<Self>,
8274 ) -> Result<()> {
8275 fn select_next_match_ranges(
8276 this: &mut Editor,
8277 range: Range<usize>,
8278 replace_newest: bool,
8279 auto_scroll: Option<Autoscroll>,
8280 cx: &mut ViewContext<Editor>,
8281 ) {
8282 this.unfold_ranges([range.clone()], false, true, cx);
8283 this.change_selections(auto_scroll, cx, |s| {
8284 if replace_newest {
8285 s.delete(s.newest_anchor().id);
8286 }
8287 s.insert_range(range.clone());
8288 });
8289 }
8290
8291 let buffer = &display_map.buffer_snapshot;
8292 let mut selections = self.selections.all::<usize>(cx);
8293 if let Some(mut select_next_state) = self.select_next_state.take() {
8294 let query = &select_next_state.query;
8295 if !select_next_state.done {
8296 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8297 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8298 let mut next_selected_range = None;
8299
8300 let bytes_after_last_selection =
8301 buffer.bytes_in_range(last_selection.end..buffer.len());
8302 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8303 let query_matches = query
8304 .stream_find_iter(bytes_after_last_selection)
8305 .map(|result| (last_selection.end, result))
8306 .chain(
8307 query
8308 .stream_find_iter(bytes_before_first_selection)
8309 .map(|result| (0, result)),
8310 );
8311
8312 for (start_offset, query_match) in query_matches {
8313 let query_match = query_match.unwrap(); // can only fail due to I/O
8314 let offset_range =
8315 start_offset + query_match.start()..start_offset + query_match.end();
8316 let display_range = offset_range.start.to_display_point(display_map)
8317 ..offset_range.end.to_display_point(display_map);
8318
8319 if !select_next_state.wordwise
8320 || (!movement::is_inside_word(display_map, display_range.start)
8321 && !movement::is_inside_word(display_map, display_range.end))
8322 {
8323 // TODO: This is n^2, because we might check all the selections
8324 if !selections
8325 .iter()
8326 .any(|selection| selection.range().overlaps(&offset_range))
8327 {
8328 next_selected_range = Some(offset_range);
8329 break;
8330 }
8331 }
8332 }
8333
8334 if let Some(next_selected_range) = next_selected_range {
8335 select_next_match_ranges(
8336 self,
8337 next_selected_range,
8338 replace_newest,
8339 autoscroll,
8340 cx,
8341 );
8342 } else {
8343 select_next_state.done = true;
8344 }
8345 }
8346
8347 self.select_next_state = Some(select_next_state);
8348 } else {
8349 let mut only_carets = true;
8350 let mut same_text_selected = true;
8351 let mut selected_text = None;
8352
8353 let mut selections_iter = selections.iter().peekable();
8354 while let Some(selection) = selections_iter.next() {
8355 if selection.start != selection.end {
8356 only_carets = false;
8357 }
8358
8359 if same_text_selected {
8360 if selected_text.is_none() {
8361 selected_text =
8362 Some(buffer.text_for_range(selection.range()).collect::<String>());
8363 }
8364
8365 if let Some(next_selection) = selections_iter.peek() {
8366 if next_selection.range().len() == selection.range().len() {
8367 let next_selected_text = buffer
8368 .text_for_range(next_selection.range())
8369 .collect::<String>();
8370 if Some(next_selected_text) != selected_text {
8371 same_text_selected = false;
8372 selected_text = None;
8373 }
8374 } else {
8375 same_text_selected = false;
8376 selected_text = None;
8377 }
8378 }
8379 }
8380 }
8381
8382 if only_carets {
8383 for selection in &mut selections {
8384 let word_range = movement::surrounding_word(
8385 display_map,
8386 selection.start.to_display_point(display_map),
8387 );
8388 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8389 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8390 selection.goal = SelectionGoal::None;
8391 selection.reversed = false;
8392 select_next_match_ranges(
8393 self,
8394 selection.start..selection.end,
8395 replace_newest,
8396 autoscroll,
8397 cx,
8398 );
8399 }
8400
8401 if selections.len() == 1 {
8402 let selection = selections
8403 .last()
8404 .expect("ensured that there's only one selection");
8405 let query = buffer
8406 .text_for_range(selection.start..selection.end)
8407 .collect::<String>();
8408 let is_empty = query.is_empty();
8409 let select_state = SelectNextState {
8410 query: AhoCorasick::new(&[query])?,
8411 wordwise: true,
8412 done: is_empty,
8413 };
8414 self.select_next_state = Some(select_state);
8415 } else {
8416 self.select_next_state = None;
8417 }
8418 } else if let Some(selected_text) = selected_text {
8419 self.select_next_state = Some(SelectNextState {
8420 query: AhoCorasick::new(&[selected_text])?,
8421 wordwise: false,
8422 done: false,
8423 });
8424 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8425 }
8426 }
8427 Ok(())
8428 }
8429
8430 pub fn select_all_matches(
8431 &mut self,
8432 _action: &SelectAllMatches,
8433 cx: &mut ViewContext<Self>,
8434 ) -> Result<()> {
8435 self.push_to_selection_history();
8436 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8437
8438 self.select_next_match_internal(&display_map, false, None, cx)?;
8439 let Some(select_next_state) = self.select_next_state.as_mut() else {
8440 return Ok(());
8441 };
8442 if select_next_state.done {
8443 return Ok(());
8444 }
8445
8446 let mut new_selections = self.selections.all::<usize>(cx);
8447
8448 let buffer = &display_map.buffer_snapshot;
8449 let query_matches = select_next_state
8450 .query
8451 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8452
8453 for query_match in query_matches {
8454 let query_match = query_match.unwrap(); // can only fail due to I/O
8455 let offset_range = query_match.start()..query_match.end();
8456 let display_range = offset_range.start.to_display_point(&display_map)
8457 ..offset_range.end.to_display_point(&display_map);
8458
8459 if !select_next_state.wordwise
8460 || (!movement::is_inside_word(&display_map, display_range.start)
8461 && !movement::is_inside_word(&display_map, display_range.end))
8462 {
8463 self.selections.change_with(cx, |selections| {
8464 new_selections.push(Selection {
8465 id: selections.new_selection_id(),
8466 start: offset_range.start,
8467 end: offset_range.end,
8468 reversed: false,
8469 goal: SelectionGoal::None,
8470 });
8471 });
8472 }
8473 }
8474
8475 new_selections.sort_by_key(|selection| selection.start);
8476 let mut ix = 0;
8477 while ix + 1 < new_selections.len() {
8478 let current_selection = &new_selections[ix];
8479 let next_selection = &new_selections[ix + 1];
8480 if current_selection.range().overlaps(&next_selection.range()) {
8481 if current_selection.id < next_selection.id {
8482 new_selections.remove(ix + 1);
8483 } else {
8484 new_selections.remove(ix);
8485 }
8486 } else {
8487 ix += 1;
8488 }
8489 }
8490
8491 select_next_state.done = true;
8492 self.unfold_ranges(
8493 new_selections.iter().map(|selection| selection.range()),
8494 false,
8495 false,
8496 cx,
8497 );
8498 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8499 selections.select(new_selections)
8500 });
8501
8502 Ok(())
8503 }
8504
8505 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8506 self.push_to_selection_history();
8507 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8508 self.select_next_match_internal(
8509 &display_map,
8510 action.replace_newest,
8511 Some(Autoscroll::newest()),
8512 cx,
8513 )?;
8514 Ok(())
8515 }
8516
8517 pub fn select_previous(
8518 &mut self,
8519 action: &SelectPrevious,
8520 cx: &mut ViewContext<Self>,
8521 ) -> Result<()> {
8522 self.push_to_selection_history();
8523 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8524 let buffer = &display_map.buffer_snapshot;
8525 let mut selections = self.selections.all::<usize>(cx);
8526 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8527 let query = &select_prev_state.query;
8528 if !select_prev_state.done {
8529 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8530 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8531 let mut next_selected_range = None;
8532 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8533 let bytes_before_last_selection =
8534 buffer.reversed_bytes_in_range(0..last_selection.start);
8535 let bytes_after_first_selection =
8536 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8537 let query_matches = query
8538 .stream_find_iter(bytes_before_last_selection)
8539 .map(|result| (last_selection.start, result))
8540 .chain(
8541 query
8542 .stream_find_iter(bytes_after_first_selection)
8543 .map(|result| (buffer.len(), result)),
8544 );
8545 for (end_offset, query_match) in query_matches {
8546 let query_match = query_match.unwrap(); // can only fail due to I/O
8547 let offset_range =
8548 end_offset - query_match.end()..end_offset - query_match.start();
8549 let display_range = offset_range.start.to_display_point(&display_map)
8550 ..offset_range.end.to_display_point(&display_map);
8551
8552 if !select_prev_state.wordwise
8553 || (!movement::is_inside_word(&display_map, display_range.start)
8554 && !movement::is_inside_word(&display_map, display_range.end))
8555 {
8556 next_selected_range = Some(offset_range);
8557 break;
8558 }
8559 }
8560
8561 if let Some(next_selected_range) = next_selected_range {
8562 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8563 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8564 if action.replace_newest {
8565 s.delete(s.newest_anchor().id);
8566 }
8567 s.insert_range(next_selected_range);
8568 });
8569 } else {
8570 select_prev_state.done = true;
8571 }
8572 }
8573
8574 self.select_prev_state = Some(select_prev_state);
8575 } else {
8576 let mut only_carets = true;
8577 let mut same_text_selected = true;
8578 let mut selected_text = None;
8579
8580 let mut selections_iter = selections.iter().peekable();
8581 while let Some(selection) = selections_iter.next() {
8582 if selection.start != selection.end {
8583 only_carets = false;
8584 }
8585
8586 if same_text_selected {
8587 if selected_text.is_none() {
8588 selected_text =
8589 Some(buffer.text_for_range(selection.range()).collect::<String>());
8590 }
8591
8592 if let Some(next_selection) = selections_iter.peek() {
8593 if next_selection.range().len() == selection.range().len() {
8594 let next_selected_text = buffer
8595 .text_for_range(next_selection.range())
8596 .collect::<String>();
8597 if Some(next_selected_text) != selected_text {
8598 same_text_selected = false;
8599 selected_text = None;
8600 }
8601 } else {
8602 same_text_selected = false;
8603 selected_text = None;
8604 }
8605 }
8606 }
8607 }
8608
8609 if only_carets {
8610 for selection in &mut selections {
8611 let word_range = movement::surrounding_word(
8612 &display_map,
8613 selection.start.to_display_point(&display_map),
8614 );
8615 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8616 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8617 selection.goal = SelectionGoal::None;
8618 selection.reversed = false;
8619 }
8620 if selections.len() == 1 {
8621 let selection = selections
8622 .last()
8623 .expect("ensured that there's only one selection");
8624 let query = buffer
8625 .text_for_range(selection.start..selection.end)
8626 .collect::<String>();
8627 let is_empty = query.is_empty();
8628 let select_state = SelectNextState {
8629 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8630 wordwise: true,
8631 done: is_empty,
8632 };
8633 self.select_prev_state = Some(select_state);
8634 } else {
8635 self.select_prev_state = None;
8636 }
8637
8638 self.unfold_ranges(
8639 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8640 false,
8641 true,
8642 cx,
8643 );
8644 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8645 s.select(selections);
8646 });
8647 } else if let Some(selected_text) = selected_text {
8648 self.select_prev_state = Some(SelectNextState {
8649 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8650 wordwise: false,
8651 done: false,
8652 });
8653 self.select_previous(action, cx)?;
8654 }
8655 }
8656 Ok(())
8657 }
8658
8659 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8660 let text_layout_details = &self.text_layout_details(cx);
8661 self.transact(cx, |this, cx| {
8662 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8663 let mut edits = Vec::new();
8664 let mut selection_edit_ranges = Vec::new();
8665 let mut last_toggled_row = None;
8666 let snapshot = this.buffer.read(cx).read(cx);
8667 let empty_str: Arc<str> = Arc::default();
8668 let mut suffixes_inserted = Vec::new();
8669
8670 fn comment_prefix_range(
8671 snapshot: &MultiBufferSnapshot,
8672 row: MultiBufferRow,
8673 comment_prefix: &str,
8674 comment_prefix_whitespace: &str,
8675 ) -> Range<Point> {
8676 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8677
8678 let mut line_bytes = snapshot
8679 .bytes_in_range(start..snapshot.max_point())
8680 .flatten()
8681 .copied();
8682
8683 // If this line currently begins with the line comment prefix, then record
8684 // the range containing the prefix.
8685 if line_bytes
8686 .by_ref()
8687 .take(comment_prefix.len())
8688 .eq(comment_prefix.bytes())
8689 {
8690 // Include any whitespace that matches the comment prefix.
8691 let matching_whitespace_len = line_bytes
8692 .zip(comment_prefix_whitespace.bytes())
8693 .take_while(|(a, b)| a == b)
8694 .count() as u32;
8695 let end = Point::new(
8696 start.row,
8697 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8698 );
8699 start..end
8700 } else {
8701 start..start
8702 }
8703 }
8704
8705 fn comment_suffix_range(
8706 snapshot: &MultiBufferSnapshot,
8707 row: MultiBufferRow,
8708 comment_suffix: &str,
8709 comment_suffix_has_leading_space: bool,
8710 ) -> Range<Point> {
8711 let end = Point::new(row.0, snapshot.line_len(row));
8712 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8713
8714 let mut line_end_bytes = snapshot
8715 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8716 .flatten()
8717 .copied();
8718
8719 let leading_space_len = if suffix_start_column > 0
8720 && line_end_bytes.next() == Some(b' ')
8721 && comment_suffix_has_leading_space
8722 {
8723 1
8724 } else {
8725 0
8726 };
8727
8728 // If this line currently begins with the line comment prefix, then record
8729 // the range containing the prefix.
8730 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8731 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8732 start..end
8733 } else {
8734 end..end
8735 }
8736 }
8737
8738 // TODO: Handle selections that cross excerpts
8739 for selection in &mut selections {
8740 let start_column = snapshot
8741 .indent_size_for_line(MultiBufferRow(selection.start.row))
8742 .len;
8743 let language = if let Some(language) =
8744 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8745 {
8746 language
8747 } else {
8748 continue;
8749 };
8750
8751 selection_edit_ranges.clear();
8752
8753 // If multiple selections contain a given row, avoid processing that
8754 // row more than once.
8755 let mut start_row = MultiBufferRow(selection.start.row);
8756 if last_toggled_row == Some(start_row) {
8757 start_row = start_row.next_row();
8758 }
8759 let end_row =
8760 if selection.end.row > selection.start.row && selection.end.column == 0 {
8761 MultiBufferRow(selection.end.row - 1)
8762 } else {
8763 MultiBufferRow(selection.end.row)
8764 };
8765 last_toggled_row = Some(end_row);
8766
8767 if start_row > end_row {
8768 continue;
8769 }
8770
8771 // If the language has line comments, toggle those.
8772 let full_comment_prefixes = language.line_comment_prefixes();
8773 if !full_comment_prefixes.is_empty() {
8774 let first_prefix = full_comment_prefixes
8775 .first()
8776 .expect("prefixes is non-empty");
8777 let prefix_trimmed_lengths = full_comment_prefixes
8778 .iter()
8779 .map(|p| p.trim_end_matches(' ').len())
8780 .collect::<SmallVec<[usize; 4]>>();
8781
8782 let mut all_selection_lines_are_comments = true;
8783
8784 for row in start_row.0..=end_row.0 {
8785 let row = MultiBufferRow(row);
8786 if start_row < end_row && snapshot.is_line_blank(row) {
8787 continue;
8788 }
8789
8790 let prefix_range = full_comment_prefixes
8791 .iter()
8792 .zip(prefix_trimmed_lengths.iter().copied())
8793 .map(|(prefix, trimmed_prefix_len)| {
8794 comment_prefix_range(
8795 snapshot.deref(),
8796 row,
8797 &prefix[..trimmed_prefix_len],
8798 &prefix[trimmed_prefix_len..],
8799 )
8800 })
8801 .max_by_key(|range| range.end.column - range.start.column)
8802 .expect("prefixes is non-empty");
8803
8804 if prefix_range.is_empty() {
8805 all_selection_lines_are_comments = false;
8806 }
8807
8808 selection_edit_ranges.push(prefix_range);
8809 }
8810
8811 if all_selection_lines_are_comments {
8812 edits.extend(
8813 selection_edit_ranges
8814 .iter()
8815 .cloned()
8816 .map(|range| (range, empty_str.clone())),
8817 );
8818 } else {
8819 let min_column = selection_edit_ranges
8820 .iter()
8821 .map(|range| range.start.column)
8822 .min()
8823 .unwrap_or(0);
8824 edits.extend(selection_edit_ranges.iter().map(|range| {
8825 let position = Point::new(range.start.row, min_column);
8826 (position..position, first_prefix.clone())
8827 }));
8828 }
8829 } else if let Some((full_comment_prefix, comment_suffix)) =
8830 language.block_comment_delimiters()
8831 {
8832 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8833 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8834 let prefix_range = comment_prefix_range(
8835 snapshot.deref(),
8836 start_row,
8837 comment_prefix,
8838 comment_prefix_whitespace,
8839 );
8840 let suffix_range = comment_suffix_range(
8841 snapshot.deref(),
8842 end_row,
8843 comment_suffix.trim_start_matches(' '),
8844 comment_suffix.starts_with(' '),
8845 );
8846
8847 if prefix_range.is_empty() || suffix_range.is_empty() {
8848 edits.push((
8849 prefix_range.start..prefix_range.start,
8850 full_comment_prefix.clone(),
8851 ));
8852 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8853 suffixes_inserted.push((end_row, comment_suffix.len()));
8854 } else {
8855 edits.push((prefix_range, empty_str.clone()));
8856 edits.push((suffix_range, empty_str.clone()));
8857 }
8858 } else {
8859 continue;
8860 }
8861 }
8862
8863 drop(snapshot);
8864 this.buffer.update(cx, |buffer, cx| {
8865 buffer.edit(edits, None, cx);
8866 });
8867
8868 // Adjust selections so that they end before any comment suffixes that
8869 // were inserted.
8870 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8871 let mut selections = this.selections.all::<Point>(cx);
8872 let snapshot = this.buffer.read(cx).read(cx);
8873 for selection in &mut selections {
8874 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8875 match row.cmp(&MultiBufferRow(selection.end.row)) {
8876 Ordering::Less => {
8877 suffixes_inserted.next();
8878 continue;
8879 }
8880 Ordering::Greater => break,
8881 Ordering::Equal => {
8882 if selection.end.column == snapshot.line_len(row) {
8883 if selection.is_empty() {
8884 selection.start.column -= suffix_len as u32;
8885 }
8886 selection.end.column -= suffix_len as u32;
8887 }
8888 break;
8889 }
8890 }
8891 }
8892 }
8893
8894 drop(snapshot);
8895 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8896
8897 let selections = this.selections.all::<Point>(cx);
8898 let selections_on_single_row = selections.windows(2).all(|selections| {
8899 selections[0].start.row == selections[1].start.row
8900 && selections[0].end.row == selections[1].end.row
8901 && selections[0].start.row == selections[0].end.row
8902 });
8903 let selections_selecting = selections
8904 .iter()
8905 .any(|selection| selection.start != selection.end);
8906 let advance_downwards = action.advance_downwards
8907 && selections_on_single_row
8908 && !selections_selecting
8909 && !matches!(this.mode, EditorMode::SingleLine { .. });
8910
8911 if advance_downwards {
8912 let snapshot = this.buffer.read(cx).snapshot(cx);
8913
8914 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8915 s.move_cursors_with(|display_snapshot, display_point, _| {
8916 let mut point = display_point.to_point(display_snapshot);
8917 point.row += 1;
8918 point = snapshot.clip_point(point, Bias::Left);
8919 let display_point = point.to_display_point(display_snapshot);
8920 let goal = SelectionGoal::HorizontalPosition(
8921 display_snapshot
8922 .x_for_display_point(display_point, text_layout_details)
8923 .into(),
8924 );
8925 (display_point, goal)
8926 })
8927 });
8928 }
8929 });
8930 }
8931
8932 pub fn select_enclosing_symbol(
8933 &mut self,
8934 _: &SelectEnclosingSymbol,
8935 cx: &mut ViewContext<Self>,
8936 ) {
8937 let buffer = self.buffer.read(cx).snapshot(cx);
8938 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8939
8940 fn update_selection(
8941 selection: &Selection<usize>,
8942 buffer_snap: &MultiBufferSnapshot,
8943 ) -> Option<Selection<usize>> {
8944 let cursor = selection.head();
8945 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8946 for symbol in symbols.iter().rev() {
8947 let start = symbol.range.start.to_offset(buffer_snap);
8948 let end = symbol.range.end.to_offset(buffer_snap);
8949 let new_range = start..end;
8950 if start < selection.start || end > selection.end {
8951 return Some(Selection {
8952 id: selection.id,
8953 start: new_range.start,
8954 end: new_range.end,
8955 goal: SelectionGoal::None,
8956 reversed: selection.reversed,
8957 });
8958 }
8959 }
8960 None
8961 }
8962
8963 let mut selected_larger_symbol = false;
8964 let new_selections = old_selections
8965 .iter()
8966 .map(|selection| match update_selection(selection, &buffer) {
8967 Some(new_selection) => {
8968 if new_selection.range() != selection.range() {
8969 selected_larger_symbol = true;
8970 }
8971 new_selection
8972 }
8973 None => selection.clone(),
8974 })
8975 .collect::<Vec<_>>();
8976
8977 if selected_larger_symbol {
8978 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8979 s.select(new_selections);
8980 });
8981 }
8982 }
8983
8984 pub fn select_larger_syntax_node(
8985 &mut self,
8986 _: &SelectLargerSyntaxNode,
8987 cx: &mut ViewContext<Self>,
8988 ) {
8989 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8990 let buffer = self.buffer.read(cx).snapshot(cx);
8991 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8992
8993 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8994 let mut selected_larger_node = false;
8995 let new_selections = old_selections
8996 .iter()
8997 .map(|selection| {
8998 let old_range = selection.start..selection.end;
8999 let mut new_range = old_range.clone();
9000 while let Some(containing_range) =
9001 buffer.range_for_syntax_ancestor(new_range.clone())
9002 {
9003 new_range = containing_range;
9004 if !display_map.intersects_fold(new_range.start)
9005 && !display_map.intersects_fold(new_range.end)
9006 {
9007 break;
9008 }
9009 }
9010
9011 selected_larger_node |= new_range != old_range;
9012 Selection {
9013 id: selection.id,
9014 start: new_range.start,
9015 end: new_range.end,
9016 goal: SelectionGoal::None,
9017 reversed: selection.reversed,
9018 }
9019 })
9020 .collect::<Vec<_>>();
9021
9022 if selected_larger_node {
9023 stack.push(old_selections);
9024 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9025 s.select(new_selections);
9026 });
9027 }
9028 self.select_larger_syntax_node_stack = stack;
9029 }
9030
9031 pub fn select_smaller_syntax_node(
9032 &mut self,
9033 _: &SelectSmallerSyntaxNode,
9034 cx: &mut ViewContext<Self>,
9035 ) {
9036 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9037 if let Some(selections) = stack.pop() {
9038 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9039 s.select(selections.to_vec());
9040 });
9041 }
9042 self.select_larger_syntax_node_stack = stack;
9043 }
9044
9045 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9046 if !EditorSettings::get_global(cx).gutter.runnables {
9047 self.clear_tasks();
9048 return Task::ready(());
9049 }
9050 let project = self.project.clone();
9051 cx.spawn(|this, mut cx| async move {
9052 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9053 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9054 }) else {
9055 return;
9056 };
9057
9058 let Some(project) = project else {
9059 return;
9060 };
9061
9062 let hide_runnables = project
9063 .update(&mut cx, |project, cx| {
9064 // Do not display any test indicators in non-dev server remote projects.
9065 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9066 })
9067 .unwrap_or(true);
9068 if hide_runnables {
9069 return;
9070 }
9071 let new_rows =
9072 cx.background_executor()
9073 .spawn({
9074 let snapshot = display_snapshot.clone();
9075 async move {
9076 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9077 }
9078 })
9079 .await;
9080 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9081
9082 this.update(&mut cx, |this, _| {
9083 this.clear_tasks();
9084 for (key, value) in rows {
9085 this.insert_tasks(key, value);
9086 }
9087 })
9088 .ok();
9089 })
9090 }
9091 fn fetch_runnable_ranges(
9092 snapshot: &DisplaySnapshot,
9093 range: Range<Anchor>,
9094 ) -> Vec<language::RunnableRange> {
9095 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9096 }
9097
9098 fn runnable_rows(
9099 project: Model<Project>,
9100 snapshot: DisplaySnapshot,
9101 runnable_ranges: Vec<RunnableRange>,
9102 mut cx: AsyncWindowContext,
9103 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9104 runnable_ranges
9105 .into_iter()
9106 .filter_map(|mut runnable| {
9107 let tasks = cx
9108 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9109 .ok()?;
9110 if tasks.is_empty() {
9111 return None;
9112 }
9113
9114 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9115
9116 let row = snapshot
9117 .buffer_snapshot
9118 .buffer_line_for_row(MultiBufferRow(point.row))?
9119 .1
9120 .start
9121 .row;
9122
9123 let context_range =
9124 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9125 Some((
9126 (runnable.buffer_id, row),
9127 RunnableTasks {
9128 templates: tasks,
9129 offset: MultiBufferOffset(runnable.run_range.start),
9130 context_range,
9131 column: point.column,
9132 extra_variables: runnable.extra_captures,
9133 },
9134 ))
9135 })
9136 .collect()
9137 }
9138
9139 fn templates_with_tags(
9140 project: &Model<Project>,
9141 runnable: &mut Runnable,
9142 cx: &WindowContext<'_>,
9143 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9144 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9145 let (worktree_id, file) = project
9146 .buffer_for_id(runnable.buffer, cx)
9147 .and_then(|buffer| buffer.read(cx).file())
9148 .map(|file| (file.worktree_id(cx), file.clone()))
9149 .unzip();
9150
9151 (
9152 project.task_store().read(cx).task_inventory().cloned(),
9153 worktree_id,
9154 file,
9155 )
9156 });
9157
9158 let tags = mem::take(&mut runnable.tags);
9159 let mut tags: Vec<_> = tags
9160 .into_iter()
9161 .flat_map(|tag| {
9162 let tag = tag.0.clone();
9163 inventory
9164 .as_ref()
9165 .into_iter()
9166 .flat_map(|inventory| {
9167 inventory.read(cx).list_tasks(
9168 file.clone(),
9169 Some(runnable.language.clone()),
9170 worktree_id,
9171 cx,
9172 )
9173 })
9174 .filter(move |(_, template)| {
9175 template.tags.iter().any(|source_tag| source_tag == &tag)
9176 })
9177 })
9178 .sorted_by_key(|(kind, _)| kind.to_owned())
9179 .collect();
9180 if let Some((leading_tag_source, _)) = tags.first() {
9181 // Strongest source wins; if we have worktree tag binding, prefer that to
9182 // global and language bindings;
9183 // if we have a global binding, prefer that to language binding.
9184 let first_mismatch = tags
9185 .iter()
9186 .position(|(tag_source, _)| tag_source != leading_tag_source);
9187 if let Some(index) = first_mismatch {
9188 tags.truncate(index);
9189 }
9190 }
9191
9192 tags
9193 }
9194
9195 pub fn move_to_enclosing_bracket(
9196 &mut self,
9197 _: &MoveToEnclosingBracket,
9198 cx: &mut ViewContext<Self>,
9199 ) {
9200 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9201 s.move_offsets_with(|snapshot, selection| {
9202 let Some(enclosing_bracket_ranges) =
9203 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9204 else {
9205 return;
9206 };
9207
9208 let mut best_length = usize::MAX;
9209 let mut best_inside = false;
9210 let mut best_in_bracket_range = false;
9211 let mut best_destination = None;
9212 for (open, close) in enclosing_bracket_ranges {
9213 let close = close.to_inclusive();
9214 let length = close.end() - open.start;
9215 let inside = selection.start >= open.end && selection.end <= *close.start();
9216 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9217 || close.contains(&selection.head());
9218
9219 // If best is next to a bracket and current isn't, skip
9220 if !in_bracket_range && best_in_bracket_range {
9221 continue;
9222 }
9223
9224 // Prefer smaller lengths unless best is inside and current isn't
9225 if length > best_length && (best_inside || !inside) {
9226 continue;
9227 }
9228
9229 best_length = length;
9230 best_inside = inside;
9231 best_in_bracket_range = in_bracket_range;
9232 best_destination = Some(
9233 if close.contains(&selection.start) && close.contains(&selection.end) {
9234 if inside {
9235 open.end
9236 } else {
9237 open.start
9238 }
9239 } else if inside {
9240 *close.start()
9241 } else {
9242 *close.end()
9243 },
9244 );
9245 }
9246
9247 if let Some(destination) = best_destination {
9248 selection.collapse_to(destination, SelectionGoal::None);
9249 }
9250 })
9251 });
9252 }
9253
9254 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9255 self.end_selection(cx);
9256 self.selection_history.mode = SelectionHistoryMode::Undoing;
9257 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9258 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9259 self.select_next_state = entry.select_next_state;
9260 self.select_prev_state = entry.select_prev_state;
9261 self.add_selections_state = entry.add_selections_state;
9262 self.request_autoscroll(Autoscroll::newest(), cx);
9263 }
9264 self.selection_history.mode = SelectionHistoryMode::Normal;
9265 }
9266
9267 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9268 self.end_selection(cx);
9269 self.selection_history.mode = SelectionHistoryMode::Redoing;
9270 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9271 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9272 self.select_next_state = entry.select_next_state;
9273 self.select_prev_state = entry.select_prev_state;
9274 self.add_selections_state = entry.add_selections_state;
9275 self.request_autoscroll(Autoscroll::newest(), cx);
9276 }
9277 self.selection_history.mode = SelectionHistoryMode::Normal;
9278 }
9279
9280 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9281 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9282 }
9283
9284 pub fn expand_excerpts_down(
9285 &mut self,
9286 action: &ExpandExcerptsDown,
9287 cx: &mut ViewContext<Self>,
9288 ) {
9289 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9290 }
9291
9292 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9293 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9294 }
9295
9296 pub fn expand_excerpts_for_direction(
9297 &mut self,
9298 lines: u32,
9299 direction: ExpandExcerptDirection,
9300 cx: &mut ViewContext<Self>,
9301 ) {
9302 let selections = self.selections.disjoint_anchors();
9303
9304 let lines = if lines == 0 {
9305 EditorSettings::get_global(cx).expand_excerpt_lines
9306 } else {
9307 lines
9308 };
9309
9310 self.buffer.update(cx, |buffer, cx| {
9311 buffer.expand_excerpts(
9312 selections
9313 .iter()
9314 .map(|selection| selection.head().excerpt_id)
9315 .dedup(),
9316 lines,
9317 direction,
9318 cx,
9319 )
9320 })
9321 }
9322
9323 pub fn expand_excerpt(
9324 &mut self,
9325 excerpt: ExcerptId,
9326 direction: ExpandExcerptDirection,
9327 cx: &mut ViewContext<Self>,
9328 ) {
9329 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9330 self.buffer.update(cx, |buffer, cx| {
9331 buffer.expand_excerpts([excerpt], lines, direction, cx)
9332 })
9333 }
9334
9335 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9336 self.go_to_diagnostic_impl(Direction::Next, cx)
9337 }
9338
9339 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9340 self.go_to_diagnostic_impl(Direction::Prev, cx)
9341 }
9342
9343 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9344 let buffer = self.buffer.read(cx).snapshot(cx);
9345 let selection = self.selections.newest::<usize>(cx);
9346
9347 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9348 if direction == Direction::Next {
9349 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9350 let (group_id, jump_to) = popover.activation_info();
9351 if self.activate_diagnostics(group_id, cx) {
9352 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9353 let mut new_selection = s.newest_anchor().clone();
9354 new_selection.collapse_to(jump_to, SelectionGoal::None);
9355 s.select_anchors(vec![new_selection.clone()]);
9356 });
9357 }
9358 return;
9359 }
9360 }
9361
9362 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9363 active_diagnostics
9364 .primary_range
9365 .to_offset(&buffer)
9366 .to_inclusive()
9367 });
9368 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9369 if active_primary_range.contains(&selection.head()) {
9370 *active_primary_range.start()
9371 } else {
9372 selection.head()
9373 }
9374 } else {
9375 selection.head()
9376 };
9377 let snapshot = self.snapshot(cx);
9378 loop {
9379 let diagnostics = if direction == Direction::Prev {
9380 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9381 } else {
9382 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9383 }
9384 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9385 let group = diagnostics
9386 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9387 // be sorted in a stable way
9388 // skip until we are at current active diagnostic, if it exists
9389 .skip_while(|entry| {
9390 (match direction {
9391 Direction::Prev => entry.range.start >= search_start,
9392 Direction::Next => entry.range.start <= search_start,
9393 }) && self
9394 .active_diagnostics
9395 .as_ref()
9396 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9397 })
9398 .find_map(|entry| {
9399 if entry.diagnostic.is_primary
9400 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9401 && !entry.range.is_empty()
9402 // if we match with the active diagnostic, skip it
9403 && Some(entry.diagnostic.group_id)
9404 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9405 {
9406 Some((entry.range, entry.diagnostic.group_id))
9407 } else {
9408 None
9409 }
9410 });
9411
9412 if let Some((primary_range, group_id)) = group {
9413 if self.activate_diagnostics(group_id, cx) {
9414 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9415 s.select(vec![Selection {
9416 id: selection.id,
9417 start: primary_range.start,
9418 end: primary_range.start,
9419 reversed: false,
9420 goal: SelectionGoal::None,
9421 }]);
9422 });
9423 }
9424 break;
9425 } else {
9426 // Cycle around to the start of the buffer, potentially moving back to the start of
9427 // the currently active diagnostic.
9428 active_primary_range.take();
9429 if direction == Direction::Prev {
9430 if search_start == buffer.len() {
9431 break;
9432 } else {
9433 search_start = buffer.len();
9434 }
9435 } else if search_start == 0 {
9436 break;
9437 } else {
9438 search_start = 0;
9439 }
9440 }
9441 }
9442 }
9443
9444 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9445 let snapshot = self
9446 .display_map
9447 .update(cx, |display_map, cx| display_map.snapshot(cx));
9448 let selection = self.selections.newest::<Point>(cx);
9449 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9450 }
9451
9452 fn go_to_hunk_after_position(
9453 &mut self,
9454 snapshot: &DisplaySnapshot,
9455 position: Point,
9456 cx: &mut ViewContext<'_, Editor>,
9457 ) -> Option<MultiBufferDiffHunk> {
9458 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9459 snapshot,
9460 position,
9461 false,
9462 snapshot
9463 .buffer_snapshot
9464 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9465 cx,
9466 ) {
9467 return Some(hunk);
9468 }
9469
9470 let wrapped_point = Point::zero();
9471 self.go_to_next_hunk_in_direction(
9472 snapshot,
9473 wrapped_point,
9474 true,
9475 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9476 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9477 ),
9478 cx,
9479 )
9480 }
9481
9482 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9483 let snapshot = self
9484 .display_map
9485 .update(cx, |display_map, cx| display_map.snapshot(cx));
9486 let selection = self.selections.newest::<Point>(cx);
9487
9488 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9489 }
9490
9491 fn go_to_hunk_before_position(
9492 &mut self,
9493 snapshot: &DisplaySnapshot,
9494 position: Point,
9495 cx: &mut ViewContext<'_, Editor>,
9496 ) -> Option<MultiBufferDiffHunk> {
9497 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9498 snapshot,
9499 position,
9500 false,
9501 snapshot
9502 .buffer_snapshot
9503 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9504 cx,
9505 ) {
9506 return Some(hunk);
9507 }
9508
9509 let wrapped_point = snapshot.buffer_snapshot.max_point();
9510 self.go_to_next_hunk_in_direction(
9511 snapshot,
9512 wrapped_point,
9513 true,
9514 snapshot
9515 .buffer_snapshot
9516 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9517 cx,
9518 )
9519 }
9520
9521 fn go_to_next_hunk_in_direction(
9522 &mut self,
9523 snapshot: &DisplaySnapshot,
9524 initial_point: Point,
9525 is_wrapped: bool,
9526 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9527 cx: &mut ViewContext<Editor>,
9528 ) -> Option<MultiBufferDiffHunk> {
9529 let display_point = initial_point.to_display_point(snapshot);
9530 let mut hunks = hunks
9531 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9532 .filter(|(display_hunk, _)| {
9533 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9534 })
9535 .dedup();
9536
9537 if let Some((display_hunk, hunk)) = hunks.next() {
9538 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9539 let row = display_hunk.start_display_row();
9540 let point = DisplayPoint::new(row, 0);
9541 s.select_display_ranges([point..point]);
9542 });
9543
9544 Some(hunk)
9545 } else {
9546 None
9547 }
9548 }
9549
9550 pub fn go_to_definition(
9551 &mut self,
9552 _: &GoToDefinition,
9553 cx: &mut ViewContext<Self>,
9554 ) -> Task<Result<Navigated>> {
9555 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9556 cx.spawn(|editor, mut cx| async move {
9557 if definition.await? == Navigated::Yes {
9558 return Ok(Navigated::Yes);
9559 }
9560 match editor.update(&mut cx, |editor, cx| {
9561 editor.find_all_references(&FindAllReferences, cx)
9562 })? {
9563 Some(references) => references.await,
9564 None => Ok(Navigated::No),
9565 }
9566 })
9567 }
9568
9569 pub fn go_to_declaration(
9570 &mut self,
9571 _: &GoToDeclaration,
9572 cx: &mut ViewContext<Self>,
9573 ) -> Task<Result<Navigated>> {
9574 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9575 }
9576
9577 pub fn go_to_declaration_split(
9578 &mut self,
9579 _: &GoToDeclaration,
9580 cx: &mut ViewContext<Self>,
9581 ) -> Task<Result<Navigated>> {
9582 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9583 }
9584
9585 pub fn go_to_implementation(
9586 &mut self,
9587 _: &GoToImplementation,
9588 cx: &mut ViewContext<Self>,
9589 ) -> Task<Result<Navigated>> {
9590 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9591 }
9592
9593 pub fn go_to_implementation_split(
9594 &mut self,
9595 _: &GoToImplementationSplit,
9596 cx: &mut ViewContext<Self>,
9597 ) -> Task<Result<Navigated>> {
9598 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9599 }
9600
9601 pub fn go_to_type_definition(
9602 &mut self,
9603 _: &GoToTypeDefinition,
9604 cx: &mut ViewContext<Self>,
9605 ) -> Task<Result<Navigated>> {
9606 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9607 }
9608
9609 pub fn go_to_definition_split(
9610 &mut self,
9611 _: &GoToDefinitionSplit,
9612 cx: &mut ViewContext<Self>,
9613 ) -> Task<Result<Navigated>> {
9614 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9615 }
9616
9617 pub fn go_to_type_definition_split(
9618 &mut self,
9619 _: &GoToTypeDefinitionSplit,
9620 cx: &mut ViewContext<Self>,
9621 ) -> Task<Result<Navigated>> {
9622 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9623 }
9624
9625 fn go_to_definition_of_kind(
9626 &mut self,
9627 kind: GotoDefinitionKind,
9628 split: bool,
9629 cx: &mut ViewContext<Self>,
9630 ) -> Task<Result<Navigated>> {
9631 let Some(provider) = self.semantics_provider.clone() else {
9632 return Task::ready(Ok(Navigated::No));
9633 };
9634 let buffer = self.buffer.read(cx);
9635 let head = self.selections.newest::<usize>(cx).head();
9636 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9637 text_anchor
9638 } else {
9639 return Task::ready(Ok(Navigated::No));
9640 };
9641
9642 let Some(definitions) = provider.definitions(&buffer, head, kind, cx) else {
9643 return Task::ready(Ok(Navigated::No));
9644 };
9645
9646 cx.spawn(|editor, mut cx| async move {
9647 let definitions = definitions.await?;
9648 let navigated = editor
9649 .update(&mut cx, |editor, cx| {
9650 editor.navigate_to_hover_links(
9651 Some(kind),
9652 definitions
9653 .into_iter()
9654 .filter(|location| {
9655 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9656 })
9657 .map(HoverLink::Text)
9658 .collect::<Vec<_>>(),
9659 split,
9660 cx,
9661 )
9662 })?
9663 .await?;
9664 anyhow::Ok(navigated)
9665 })
9666 }
9667
9668 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9669 let position = self.selections.newest_anchor().head();
9670 let Some((buffer, buffer_position)) =
9671 self.buffer.read(cx).text_anchor_for_position(position, cx)
9672 else {
9673 return;
9674 };
9675
9676 cx.spawn(|editor, mut cx| async move {
9677 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9678 editor.update(&mut cx, |_, cx| {
9679 cx.open_url(&url);
9680 })
9681 } else {
9682 Ok(())
9683 }
9684 })
9685 .detach();
9686 }
9687
9688 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9689 let Some(workspace) = self.workspace() else {
9690 return;
9691 };
9692
9693 let position = self.selections.newest_anchor().head();
9694
9695 let Some((buffer, buffer_position)) =
9696 self.buffer.read(cx).text_anchor_for_position(position, cx)
9697 else {
9698 return;
9699 };
9700
9701 let project = self.project.clone();
9702
9703 cx.spawn(|_, mut cx| async move {
9704 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9705
9706 if let Some((_, path)) = result {
9707 workspace
9708 .update(&mut cx, |workspace, cx| {
9709 workspace.open_resolved_path(path, cx)
9710 })?
9711 .await?;
9712 }
9713 anyhow::Ok(())
9714 })
9715 .detach();
9716 }
9717
9718 pub(crate) fn navigate_to_hover_links(
9719 &mut self,
9720 kind: Option<GotoDefinitionKind>,
9721 mut definitions: Vec<HoverLink>,
9722 split: bool,
9723 cx: &mut ViewContext<Editor>,
9724 ) -> Task<Result<Navigated>> {
9725 // If there is one definition, just open it directly
9726 if definitions.len() == 1 {
9727 let definition = definitions.pop().unwrap();
9728
9729 enum TargetTaskResult {
9730 Location(Option<Location>),
9731 AlreadyNavigated,
9732 }
9733
9734 let target_task = match definition {
9735 HoverLink::Text(link) => {
9736 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9737 }
9738 HoverLink::InlayHint(lsp_location, server_id) => {
9739 let computation = self.compute_target_location(lsp_location, server_id, cx);
9740 cx.background_executor().spawn(async move {
9741 let location = computation.await?;
9742 Ok(TargetTaskResult::Location(location))
9743 })
9744 }
9745 HoverLink::Url(url) => {
9746 cx.open_url(&url);
9747 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9748 }
9749 HoverLink::File(path) => {
9750 if let Some(workspace) = self.workspace() {
9751 cx.spawn(|_, mut cx| async move {
9752 workspace
9753 .update(&mut cx, |workspace, cx| {
9754 workspace.open_resolved_path(path, cx)
9755 })?
9756 .await
9757 .map(|_| TargetTaskResult::AlreadyNavigated)
9758 })
9759 } else {
9760 Task::ready(Ok(TargetTaskResult::Location(None)))
9761 }
9762 }
9763 };
9764 cx.spawn(|editor, mut cx| async move {
9765 let target = match target_task.await.context("target resolution task")? {
9766 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9767 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9768 TargetTaskResult::Location(Some(target)) => target,
9769 };
9770
9771 editor.update(&mut cx, |editor, cx| {
9772 let Some(workspace) = editor.workspace() else {
9773 return Navigated::No;
9774 };
9775 let pane = workspace.read(cx).active_pane().clone();
9776
9777 let range = target.range.to_offset(target.buffer.read(cx));
9778 let range = editor.range_for_match(&range);
9779
9780 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9781 let buffer = target.buffer.read(cx);
9782 let range = check_multiline_range(buffer, range);
9783 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9784 s.select_ranges([range]);
9785 });
9786 } else {
9787 cx.window_context().defer(move |cx| {
9788 let target_editor: View<Self> =
9789 workspace.update(cx, |workspace, cx| {
9790 let pane = if split {
9791 workspace.adjacent_pane(cx)
9792 } else {
9793 workspace.active_pane().clone()
9794 };
9795
9796 workspace.open_project_item(
9797 pane,
9798 target.buffer.clone(),
9799 true,
9800 true,
9801 cx,
9802 )
9803 });
9804 target_editor.update(cx, |target_editor, cx| {
9805 // When selecting a definition in a different buffer, disable the nav history
9806 // to avoid creating a history entry at the previous cursor location.
9807 pane.update(cx, |pane, _| pane.disable_history());
9808 let buffer = target.buffer.read(cx);
9809 let range = check_multiline_range(buffer, range);
9810 target_editor.change_selections(
9811 Some(Autoscroll::focused()),
9812 cx,
9813 |s| {
9814 s.select_ranges([range]);
9815 },
9816 );
9817 pane.update(cx, |pane, _| pane.enable_history());
9818 });
9819 });
9820 }
9821 Navigated::Yes
9822 })
9823 })
9824 } else if !definitions.is_empty() {
9825 cx.spawn(|editor, mut cx| async move {
9826 let (title, location_tasks, workspace) = editor
9827 .update(&mut cx, |editor, cx| {
9828 let tab_kind = match kind {
9829 Some(GotoDefinitionKind::Implementation) => "Implementations",
9830 _ => "Definitions",
9831 };
9832 let title = definitions
9833 .iter()
9834 .find_map(|definition| match definition {
9835 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9836 let buffer = origin.buffer.read(cx);
9837 format!(
9838 "{} for {}",
9839 tab_kind,
9840 buffer
9841 .text_for_range(origin.range.clone())
9842 .collect::<String>()
9843 )
9844 }),
9845 HoverLink::InlayHint(_, _) => None,
9846 HoverLink::Url(_) => None,
9847 HoverLink::File(_) => None,
9848 })
9849 .unwrap_or(tab_kind.to_string());
9850 let location_tasks = definitions
9851 .into_iter()
9852 .map(|definition| match definition {
9853 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9854 HoverLink::InlayHint(lsp_location, server_id) => {
9855 editor.compute_target_location(lsp_location, server_id, cx)
9856 }
9857 HoverLink::Url(_) => Task::ready(Ok(None)),
9858 HoverLink::File(_) => Task::ready(Ok(None)),
9859 })
9860 .collect::<Vec<_>>();
9861 (title, location_tasks, editor.workspace().clone())
9862 })
9863 .context("location tasks preparation")?;
9864
9865 let locations = future::join_all(location_tasks)
9866 .await
9867 .into_iter()
9868 .filter_map(|location| location.transpose())
9869 .collect::<Result<_>>()
9870 .context("location tasks")?;
9871
9872 let Some(workspace) = workspace else {
9873 return Ok(Navigated::No);
9874 };
9875 let opened = workspace
9876 .update(&mut cx, |workspace, cx| {
9877 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9878 })
9879 .ok();
9880
9881 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9882 })
9883 } else {
9884 Task::ready(Ok(Navigated::No))
9885 }
9886 }
9887
9888 fn compute_target_location(
9889 &self,
9890 lsp_location: lsp::Location,
9891 server_id: LanguageServerId,
9892 cx: &mut ViewContext<Self>,
9893 ) -> Task<anyhow::Result<Option<Location>>> {
9894 let Some(project) = self.project.clone() else {
9895 return Task::Ready(Some(Ok(None)));
9896 };
9897
9898 cx.spawn(move |editor, mut cx| async move {
9899 let location_task = editor.update(&mut cx, |_, cx| {
9900 project.update(cx, |project, cx| {
9901 let language_server_name = project
9902 .language_server_statuses(cx)
9903 .find(|(id, _)| server_id == *id)
9904 .map(|(_, status)| LanguageServerName::from(status.name.as_str()));
9905 language_server_name.map(|language_server_name| {
9906 project.open_local_buffer_via_lsp(
9907 lsp_location.uri.clone(),
9908 server_id,
9909 language_server_name,
9910 cx,
9911 )
9912 })
9913 })
9914 })?;
9915 let location = match location_task {
9916 Some(task) => Some({
9917 let target_buffer_handle = task.await.context("open local buffer")?;
9918 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9919 let target_start = target_buffer
9920 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9921 let target_end = target_buffer
9922 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9923 target_buffer.anchor_after(target_start)
9924 ..target_buffer.anchor_before(target_end)
9925 })?;
9926 Location {
9927 buffer: target_buffer_handle,
9928 range,
9929 }
9930 }),
9931 None => None,
9932 };
9933 Ok(location)
9934 })
9935 }
9936
9937 pub fn find_all_references(
9938 &mut self,
9939 _: &FindAllReferences,
9940 cx: &mut ViewContext<Self>,
9941 ) -> Option<Task<Result<Navigated>>> {
9942 let multi_buffer = self.buffer.read(cx);
9943 let selection = self.selections.newest::<usize>(cx);
9944 let head = selection.head();
9945
9946 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9947 let head_anchor = multi_buffer_snapshot.anchor_at(
9948 head,
9949 if head < selection.tail() {
9950 Bias::Right
9951 } else {
9952 Bias::Left
9953 },
9954 );
9955
9956 match self
9957 .find_all_references_task_sources
9958 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9959 {
9960 Ok(_) => {
9961 log::info!(
9962 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9963 );
9964 return None;
9965 }
9966 Err(i) => {
9967 self.find_all_references_task_sources.insert(i, head_anchor);
9968 }
9969 }
9970
9971 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9972 let workspace = self.workspace()?;
9973 let project = workspace.read(cx).project().clone();
9974 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9975 Some(cx.spawn(|editor, mut cx| async move {
9976 let _cleanup = defer({
9977 let mut cx = cx.clone();
9978 move || {
9979 let _ = editor.update(&mut cx, |editor, _| {
9980 if let Ok(i) =
9981 editor
9982 .find_all_references_task_sources
9983 .binary_search_by(|anchor| {
9984 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9985 })
9986 {
9987 editor.find_all_references_task_sources.remove(i);
9988 }
9989 });
9990 }
9991 });
9992
9993 let locations = references.await?;
9994 if locations.is_empty() {
9995 return anyhow::Ok(Navigated::No);
9996 }
9997
9998 workspace.update(&mut cx, |workspace, cx| {
9999 let title = locations
10000 .first()
10001 .as_ref()
10002 .map(|location| {
10003 let buffer = location.buffer.read(cx);
10004 format!(
10005 "References to `{}`",
10006 buffer
10007 .text_for_range(location.range.clone())
10008 .collect::<String>()
10009 )
10010 })
10011 .unwrap();
10012 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10013 Navigated::Yes
10014 })
10015 }))
10016 }
10017
10018 /// Opens a multibuffer with the given project locations in it
10019 pub fn open_locations_in_multibuffer(
10020 workspace: &mut Workspace,
10021 mut locations: Vec<Location>,
10022 title: String,
10023 split: bool,
10024 cx: &mut ViewContext<Workspace>,
10025 ) {
10026 // If there are multiple definitions, open them in a multibuffer
10027 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10028 let mut locations = locations.into_iter().peekable();
10029 let mut ranges_to_highlight = Vec::new();
10030 let capability = workspace.project().read(cx).capability();
10031
10032 let excerpt_buffer = cx.new_model(|cx| {
10033 let mut multibuffer = MultiBuffer::new(capability);
10034 while let Some(location) = locations.next() {
10035 let buffer = location.buffer.read(cx);
10036 let mut ranges_for_buffer = Vec::new();
10037 let range = location.range.to_offset(buffer);
10038 ranges_for_buffer.push(range.clone());
10039
10040 while let Some(next_location) = locations.peek() {
10041 if next_location.buffer == location.buffer {
10042 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10043 locations.next();
10044 } else {
10045 break;
10046 }
10047 }
10048
10049 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10050 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10051 location.buffer.clone(),
10052 ranges_for_buffer,
10053 DEFAULT_MULTIBUFFER_CONTEXT,
10054 cx,
10055 ))
10056 }
10057
10058 multibuffer.with_title(title)
10059 });
10060
10061 let editor = cx.new_view(|cx| {
10062 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10063 });
10064 editor.update(cx, |editor, cx| {
10065 if let Some(first_range) = ranges_to_highlight.first() {
10066 editor.change_selections(None, cx, |selections| {
10067 selections.clear_disjoint();
10068 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10069 });
10070 }
10071 editor.highlight_background::<Self>(
10072 &ranges_to_highlight,
10073 |theme| theme.editor_highlighted_line_background,
10074 cx,
10075 );
10076 });
10077
10078 let item = Box::new(editor);
10079 let item_id = item.item_id();
10080
10081 if split {
10082 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10083 } else {
10084 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10085 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10086 pane.close_current_preview_item(cx)
10087 } else {
10088 None
10089 }
10090 });
10091 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10092 }
10093 workspace.active_pane().update(cx, |pane, cx| {
10094 pane.set_preview_item_id(Some(item_id), cx);
10095 });
10096 }
10097
10098 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10099 use language::ToOffset as _;
10100
10101 let provider = self.semantics_provider.clone()?;
10102 let selection = self.selections.newest_anchor().clone();
10103 let (cursor_buffer, cursor_buffer_position) = self
10104 .buffer
10105 .read(cx)
10106 .text_anchor_for_position(selection.head(), cx)?;
10107 let (tail_buffer, cursor_buffer_position_end) = self
10108 .buffer
10109 .read(cx)
10110 .text_anchor_for_position(selection.tail(), cx)?;
10111 if tail_buffer != cursor_buffer {
10112 return None;
10113 }
10114
10115 let snapshot = cursor_buffer.read(cx).snapshot();
10116 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10117 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10118 let prepare_rename = provider
10119 .range_for_rename(&cursor_buffer, cursor_buffer_position, cx)
10120 .unwrap_or_else(|| Task::ready(Ok(None)));
10121 drop(snapshot);
10122
10123 Some(cx.spawn(|this, mut cx| async move {
10124 let rename_range = if let Some(range) = prepare_rename.await? {
10125 Some(range)
10126 } else {
10127 this.update(&mut cx, |this, cx| {
10128 let buffer = this.buffer.read(cx).snapshot(cx);
10129 let mut buffer_highlights = this
10130 .document_highlights_for_position(selection.head(), &buffer)
10131 .filter(|highlight| {
10132 highlight.start.excerpt_id == selection.head().excerpt_id
10133 && highlight.end.excerpt_id == selection.head().excerpt_id
10134 });
10135 buffer_highlights
10136 .next()
10137 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10138 })?
10139 };
10140 if let Some(rename_range) = rename_range {
10141 this.update(&mut cx, |this, cx| {
10142 let snapshot = cursor_buffer.read(cx).snapshot();
10143 let rename_buffer_range = rename_range.to_offset(&snapshot);
10144 let cursor_offset_in_rename_range =
10145 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10146 let cursor_offset_in_rename_range_end =
10147 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10148
10149 this.take_rename(false, cx);
10150 let buffer = this.buffer.read(cx).read(cx);
10151 let cursor_offset = selection.head().to_offset(&buffer);
10152 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10153 let rename_end = rename_start + rename_buffer_range.len();
10154 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10155 let mut old_highlight_id = None;
10156 let old_name: Arc<str> = buffer
10157 .chunks(rename_start..rename_end, true)
10158 .map(|chunk| {
10159 if old_highlight_id.is_none() {
10160 old_highlight_id = chunk.syntax_highlight_id;
10161 }
10162 chunk.text
10163 })
10164 .collect::<String>()
10165 .into();
10166
10167 drop(buffer);
10168
10169 // Position the selection in the rename editor so that it matches the current selection.
10170 this.show_local_selections = false;
10171 let rename_editor = cx.new_view(|cx| {
10172 let mut editor = Editor::single_line(cx);
10173 editor.buffer.update(cx, |buffer, cx| {
10174 buffer.edit([(0..0, old_name.clone())], None, cx)
10175 });
10176 let rename_selection_range = match cursor_offset_in_rename_range
10177 .cmp(&cursor_offset_in_rename_range_end)
10178 {
10179 Ordering::Equal => {
10180 editor.select_all(&SelectAll, cx);
10181 return editor;
10182 }
10183 Ordering::Less => {
10184 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10185 }
10186 Ordering::Greater => {
10187 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10188 }
10189 };
10190 if rename_selection_range.end > old_name.len() {
10191 editor.select_all(&SelectAll, cx);
10192 } else {
10193 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10194 s.select_ranges([rename_selection_range]);
10195 });
10196 }
10197 editor
10198 });
10199 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10200 if e == &EditorEvent::Focused {
10201 cx.emit(EditorEvent::FocusedIn)
10202 }
10203 })
10204 .detach();
10205
10206 let write_highlights =
10207 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10208 let read_highlights =
10209 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10210 let ranges = write_highlights
10211 .iter()
10212 .flat_map(|(_, ranges)| ranges.iter())
10213 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10214 .cloned()
10215 .collect();
10216
10217 this.highlight_text::<Rename>(
10218 ranges,
10219 HighlightStyle {
10220 fade_out: Some(0.6),
10221 ..Default::default()
10222 },
10223 cx,
10224 );
10225 let rename_focus_handle = rename_editor.focus_handle(cx);
10226 cx.focus(&rename_focus_handle);
10227 let block_id = this.insert_blocks(
10228 [BlockProperties {
10229 style: BlockStyle::Flex,
10230 position: range.start,
10231 height: 1,
10232 render: Box::new({
10233 let rename_editor = rename_editor.clone();
10234 move |cx: &mut BlockContext| {
10235 let mut text_style = cx.editor_style.text.clone();
10236 if let Some(highlight_style) = old_highlight_id
10237 .and_then(|h| h.style(&cx.editor_style.syntax))
10238 {
10239 text_style = text_style.highlight(highlight_style);
10240 }
10241 div()
10242 .pl(cx.anchor_x)
10243 .child(EditorElement::new(
10244 &rename_editor,
10245 EditorStyle {
10246 background: cx.theme().system().transparent,
10247 local_player: cx.editor_style.local_player,
10248 text: text_style,
10249 scrollbar_width: cx.editor_style.scrollbar_width,
10250 syntax: cx.editor_style.syntax.clone(),
10251 status: cx.editor_style.status.clone(),
10252 inlay_hints_style: HighlightStyle {
10253 font_weight: Some(FontWeight::BOLD),
10254 ..make_inlay_hints_style(cx)
10255 },
10256 suggestions_style: HighlightStyle {
10257 color: Some(cx.theme().status().predictive),
10258 ..HighlightStyle::default()
10259 },
10260 ..EditorStyle::default()
10261 },
10262 ))
10263 .into_any_element()
10264 }
10265 }),
10266 disposition: BlockDisposition::Below,
10267 priority: 0,
10268 }],
10269 Some(Autoscroll::fit()),
10270 cx,
10271 )[0];
10272 this.pending_rename = Some(RenameState {
10273 range,
10274 old_name,
10275 editor: rename_editor,
10276 block_id,
10277 });
10278 })?;
10279 }
10280
10281 Ok(())
10282 }))
10283 }
10284
10285 pub fn confirm_rename(
10286 &mut self,
10287 _: &ConfirmRename,
10288 cx: &mut ViewContext<Self>,
10289 ) -> Option<Task<Result<()>>> {
10290 let rename = self.take_rename(false, cx)?;
10291 let workspace = self.workspace()?.downgrade();
10292 let (buffer, start) = self
10293 .buffer
10294 .read(cx)
10295 .text_anchor_for_position(rename.range.start, cx)?;
10296 let (end_buffer, _) = self
10297 .buffer
10298 .read(cx)
10299 .text_anchor_for_position(rename.range.end, cx)?;
10300 if buffer != end_buffer {
10301 return None;
10302 }
10303
10304 let old_name = rename.old_name;
10305 let new_name = rename.editor.read(cx).text(cx);
10306
10307 let rename = self.semantics_provider.as_ref()?.perform_rename(
10308 &buffer,
10309 start,
10310 new_name.clone(),
10311 cx,
10312 )?;
10313
10314 Some(cx.spawn(|editor, mut cx| async move {
10315 let project_transaction = rename.await?;
10316 Self::open_project_transaction(
10317 &editor,
10318 workspace,
10319 project_transaction,
10320 format!("Rename: {} → {}", old_name, new_name),
10321 cx.clone(),
10322 )
10323 .await?;
10324
10325 editor.update(&mut cx, |editor, cx| {
10326 editor.refresh_document_highlights(cx);
10327 })?;
10328 Ok(())
10329 }))
10330 }
10331
10332 fn take_rename(
10333 &mut self,
10334 moving_cursor: bool,
10335 cx: &mut ViewContext<Self>,
10336 ) -> Option<RenameState> {
10337 let rename = self.pending_rename.take()?;
10338 if rename.editor.focus_handle(cx).is_focused(cx) {
10339 cx.focus(&self.focus_handle);
10340 }
10341
10342 self.remove_blocks(
10343 [rename.block_id].into_iter().collect(),
10344 Some(Autoscroll::fit()),
10345 cx,
10346 );
10347 self.clear_highlights::<Rename>(cx);
10348 self.show_local_selections = true;
10349
10350 if moving_cursor {
10351 let rename_editor = rename.editor.read(cx);
10352 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10353
10354 // Update the selection to match the position of the selection inside
10355 // the rename editor.
10356 let snapshot = self.buffer.read(cx).read(cx);
10357 let rename_range = rename.range.to_offset(&snapshot);
10358 let cursor_in_editor = snapshot
10359 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10360 .min(rename_range.end);
10361 drop(snapshot);
10362
10363 self.change_selections(None, cx, |s| {
10364 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10365 });
10366 } else {
10367 self.refresh_document_highlights(cx);
10368 }
10369
10370 Some(rename)
10371 }
10372
10373 pub fn pending_rename(&self) -> Option<&RenameState> {
10374 self.pending_rename.as_ref()
10375 }
10376
10377 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10378 let project = match &self.project {
10379 Some(project) => project.clone(),
10380 None => return None,
10381 };
10382
10383 Some(self.perform_format(project, FormatTrigger::Manual, FormatTarget::Buffer, cx))
10384 }
10385
10386 fn format_selections(
10387 &mut self,
10388 _: &FormatSelections,
10389 cx: &mut ViewContext<Self>,
10390 ) -> Option<Task<Result<()>>> {
10391 let project = match &self.project {
10392 Some(project) => project.clone(),
10393 None => return None,
10394 };
10395
10396 let selections = self
10397 .selections
10398 .all_adjusted(cx)
10399 .into_iter()
10400 .filter(|s| !s.is_empty())
10401 .collect_vec();
10402
10403 Some(self.perform_format(
10404 project,
10405 FormatTrigger::Manual,
10406 FormatTarget::Ranges(selections),
10407 cx,
10408 ))
10409 }
10410
10411 fn perform_format(
10412 &mut self,
10413 project: Model<Project>,
10414 trigger: FormatTrigger,
10415 target: FormatTarget,
10416 cx: &mut ViewContext<Self>,
10417 ) -> Task<Result<()>> {
10418 let buffer = self.buffer().clone();
10419 let mut buffers = buffer.read(cx).all_buffers();
10420 if trigger == FormatTrigger::Save {
10421 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10422 }
10423
10424 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10425 let format = project.update(cx, |project, cx| {
10426 project.format(buffers, true, trigger, target, cx)
10427 });
10428
10429 cx.spawn(|_, mut cx| async move {
10430 let transaction = futures::select_biased! {
10431 () = timeout => {
10432 log::warn!("timed out waiting for formatting");
10433 None
10434 }
10435 transaction = format.log_err().fuse() => transaction,
10436 };
10437
10438 buffer
10439 .update(&mut cx, |buffer, cx| {
10440 if let Some(transaction) = transaction {
10441 if !buffer.is_singleton() {
10442 buffer.push_transaction(&transaction.0, cx);
10443 }
10444 }
10445
10446 cx.notify();
10447 })
10448 .ok();
10449
10450 Ok(())
10451 })
10452 }
10453
10454 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10455 if let Some(project) = self.project.clone() {
10456 self.buffer.update(cx, |multi_buffer, cx| {
10457 project.update(cx, |project, cx| {
10458 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10459 });
10460 })
10461 }
10462 }
10463
10464 fn cancel_language_server_work(
10465 &mut self,
10466 _: &CancelLanguageServerWork,
10467 cx: &mut ViewContext<Self>,
10468 ) {
10469 if let Some(project) = self.project.clone() {
10470 self.buffer.update(cx, |multi_buffer, cx| {
10471 project.update(cx, |project, cx| {
10472 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10473 });
10474 })
10475 }
10476 }
10477
10478 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10479 cx.show_character_palette();
10480 }
10481
10482 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10483 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10484 let buffer = self.buffer.read(cx).snapshot(cx);
10485 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10486 let is_valid = buffer
10487 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10488 .any(|entry| {
10489 entry.diagnostic.is_primary
10490 && !entry.range.is_empty()
10491 && entry.range.start == primary_range_start
10492 && entry.diagnostic.message == active_diagnostics.primary_message
10493 });
10494
10495 if is_valid != active_diagnostics.is_valid {
10496 active_diagnostics.is_valid = is_valid;
10497 let mut new_styles = HashMap::default();
10498 for (block_id, diagnostic) in &active_diagnostics.blocks {
10499 new_styles.insert(
10500 *block_id,
10501 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10502 );
10503 }
10504 self.display_map.update(cx, |display_map, _cx| {
10505 display_map.replace_blocks(new_styles)
10506 });
10507 }
10508 }
10509 }
10510
10511 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10512 self.dismiss_diagnostics(cx);
10513 let snapshot = self.snapshot(cx);
10514 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10515 let buffer = self.buffer.read(cx).snapshot(cx);
10516
10517 let mut primary_range = None;
10518 let mut primary_message = None;
10519 let mut group_end = Point::zero();
10520 let diagnostic_group = buffer
10521 .diagnostic_group::<MultiBufferPoint>(group_id)
10522 .filter_map(|entry| {
10523 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10524 && (entry.range.start.row == entry.range.end.row
10525 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10526 {
10527 return None;
10528 }
10529 if entry.range.end > group_end {
10530 group_end = entry.range.end;
10531 }
10532 if entry.diagnostic.is_primary {
10533 primary_range = Some(entry.range.clone());
10534 primary_message = Some(entry.diagnostic.message.clone());
10535 }
10536 Some(entry)
10537 })
10538 .collect::<Vec<_>>();
10539 let primary_range = primary_range?;
10540 let primary_message = primary_message?;
10541 let primary_range =
10542 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10543
10544 let blocks = display_map
10545 .insert_blocks(
10546 diagnostic_group.iter().map(|entry| {
10547 let diagnostic = entry.diagnostic.clone();
10548 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10549 BlockProperties {
10550 style: BlockStyle::Fixed,
10551 position: buffer.anchor_after(entry.range.start),
10552 height: message_height,
10553 render: diagnostic_block_renderer(diagnostic, None, true, true),
10554 disposition: BlockDisposition::Below,
10555 priority: 0,
10556 }
10557 }),
10558 cx,
10559 )
10560 .into_iter()
10561 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10562 .collect();
10563
10564 Some(ActiveDiagnosticGroup {
10565 primary_range,
10566 primary_message,
10567 group_id,
10568 blocks,
10569 is_valid: true,
10570 })
10571 });
10572 self.active_diagnostics.is_some()
10573 }
10574
10575 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10576 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10577 self.display_map.update(cx, |display_map, cx| {
10578 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10579 });
10580 cx.notify();
10581 }
10582 }
10583
10584 pub fn set_selections_from_remote(
10585 &mut self,
10586 selections: Vec<Selection<Anchor>>,
10587 pending_selection: Option<Selection<Anchor>>,
10588 cx: &mut ViewContext<Self>,
10589 ) {
10590 let old_cursor_position = self.selections.newest_anchor().head();
10591 self.selections.change_with(cx, |s| {
10592 s.select_anchors(selections);
10593 if let Some(pending_selection) = pending_selection {
10594 s.set_pending(pending_selection, SelectMode::Character);
10595 } else {
10596 s.clear_pending();
10597 }
10598 });
10599 self.selections_did_change(false, &old_cursor_position, true, cx);
10600 }
10601
10602 fn push_to_selection_history(&mut self) {
10603 self.selection_history.push(SelectionHistoryEntry {
10604 selections: self.selections.disjoint_anchors(),
10605 select_next_state: self.select_next_state.clone(),
10606 select_prev_state: self.select_prev_state.clone(),
10607 add_selections_state: self.add_selections_state.clone(),
10608 });
10609 }
10610
10611 pub fn transact(
10612 &mut self,
10613 cx: &mut ViewContext<Self>,
10614 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10615 ) -> Option<TransactionId> {
10616 self.start_transaction_at(Instant::now(), cx);
10617 update(self, cx);
10618 self.end_transaction_at(Instant::now(), cx)
10619 }
10620
10621 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10622 self.end_selection(cx);
10623 if let Some(tx_id) = self
10624 .buffer
10625 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10626 {
10627 self.selection_history
10628 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10629 cx.emit(EditorEvent::TransactionBegun {
10630 transaction_id: tx_id,
10631 })
10632 }
10633 }
10634
10635 fn end_transaction_at(
10636 &mut self,
10637 now: Instant,
10638 cx: &mut ViewContext<Self>,
10639 ) -> Option<TransactionId> {
10640 if let Some(transaction_id) = self
10641 .buffer
10642 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10643 {
10644 if let Some((_, end_selections)) =
10645 self.selection_history.transaction_mut(transaction_id)
10646 {
10647 *end_selections = Some(self.selections.disjoint_anchors());
10648 } else {
10649 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10650 }
10651
10652 cx.emit(EditorEvent::Edited { transaction_id });
10653 Some(transaction_id)
10654 } else {
10655 None
10656 }
10657 }
10658
10659 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10660 let selection = self.selections.newest::<Point>(cx);
10661
10662 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10663 let range = if selection.is_empty() {
10664 let point = selection.head().to_display_point(&display_map);
10665 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10666 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10667 .to_point(&display_map);
10668 start..end
10669 } else {
10670 selection.range()
10671 };
10672 if display_map.folds_in_range(range).next().is_some() {
10673 self.unfold_lines(&Default::default(), cx)
10674 } else {
10675 self.fold(&Default::default(), cx)
10676 }
10677 }
10678
10679 pub fn toggle_fold_recursive(
10680 &mut self,
10681 _: &actions::ToggleFoldRecursive,
10682 cx: &mut ViewContext<Self>,
10683 ) {
10684 let selection = self.selections.newest::<Point>(cx);
10685
10686 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10687 let range = if selection.is_empty() {
10688 let point = selection.head().to_display_point(&display_map);
10689 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10690 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10691 .to_point(&display_map);
10692 start..end
10693 } else {
10694 selection.range()
10695 };
10696 if display_map.folds_in_range(range).next().is_some() {
10697 self.unfold_recursive(&Default::default(), cx)
10698 } else {
10699 self.fold_recursive(&Default::default(), cx)
10700 }
10701 }
10702
10703 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10704 let mut fold_ranges = Vec::new();
10705 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10706 let selections = self.selections.all_adjusted(cx);
10707
10708 for selection in selections {
10709 let range = selection.range().sorted();
10710 let buffer_start_row = range.start.row;
10711
10712 if range.start.row != range.end.row {
10713 let mut found = false;
10714 let mut row = range.start.row;
10715 while row <= range.end.row {
10716 if let Some((foldable_range, fold_text)) =
10717 { display_map.foldable_range(MultiBufferRow(row)) }
10718 {
10719 found = true;
10720 row = foldable_range.end.row + 1;
10721 fold_ranges.push((foldable_range, fold_text));
10722 } else {
10723 row += 1
10724 }
10725 }
10726 if found {
10727 continue;
10728 }
10729 }
10730
10731 for row in (0..=range.start.row).rev() {
10732 if let Some((foldable_range, fold_text)) =
10733 display_map.foldable_range(MultiBufferRow(row))
10734 {
10735 if foldable_range.end.row >= buffer_start_row {
10736 fold_ranges.push((foldable_range, fold_text));
10737 if row <= range.start.row {
10738 break;
10739 }
10740 }
10741 }
10742 }
10743 }
10744
10745 self.fold_ranges(fold_ranges, true, cx);
10746 }
10747
10748 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10749 let mut fold_ranges = Vec::new();
10750 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10751
10752 for row in 0..display_map.max_buffer_row().0 {
10753 if let Some((foldable_range, fold_text)) =
10754 display_map.foldable_range(MultiBufferRow(row))
10755 {
10756 fold_ranges.push((foldable_range, fold_text));
10757 }
10758 }
10759
10760 self.fold_ranges(fold_ranges, true, cx);
10761 }
10762
10763 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10764 let mut fold_ranges = Vec::new();
10765 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10766 let selections = self.selections.all_adjusted(cx);
10767
10768 for selection in selections {
10769 let range = selection.range().sorted();
10770 let buffer_start_row = range.start.row;
10771
10772 if range.start.row != range.end.row {
10773 let mut found = false;
10774 for row in range.start.row..=range.end.row {
10775 if let Some((foldable_range, fold_text)) =
10776 { display_map.foldable_range(MultiBufferRow(row)) }
10777 {
10778 found = true;
10779 fold_ranges.push((foldable_range, fold_text));
10780 }
10781 }
10782 if found {
10783 continue;
10784 }
10785 }
10786
10787 for row in (0..=range.start.row).rev() {
10788 if let Some((foldable_range, fold_text)) =
10789 display_map.foldable_range(MultiBufferRow(row))
10790 {
10791 if foldable_range.end.row >= buffer_start_row {
10792 fold_ranges.push((foldable_range, fold_text));
10793 } else {
10794 break;
10795 }
10796 }
10797 }
10798 }
10799
10800 self.fold_ranges(fold_ranges, true, cx);
10801 }
10802
10803 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10804 let buffer_row = fold_at.buffer_row;
10805 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10806
10807 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10808 let autoscroll = self
10809 .selections
10810 .all::<Point>(cx)
10811 .iter()
10812 .any(|selection| fold_range.overlaps(&selection.range()));
10813
10814 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10815 }
10816 }
10817
10818 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10819 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10820 let buffer = &display_map.buffer_snapshot;
10821 let selections = self.selections.all::<Point>(cx);
10822 let ranges = selections
10823 .iter()
10824 .map(|s| {
10825 let range = s.display_range(&display_map).sorted();
10826 let mut start = range.start.to_point(&display_map);
10827 let mut end = range.end.to_point(&display_map);
10828 start.column = 0;
10829 end.column = buffer.line_len(MultiBufferRow(end.row));
10830 start..end
10831 })
10832 .collect::<Vec<_>>();
10833
10834 self.unfold_ranges(ranges, true, true, cx);
10835 }
10836
10837 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10838 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10839 let selections = self.selections.all::<Point>(cx);
10840 let ranges = selections
10841 .iter()
10842 .map(|s| {
10843 let mut range = s.display_range(&display_map).sorted();
10844 *range.start.column_mut() = 0;
10845 *range.end.column_mut() = display_map.line_len(range.end.row());
10846 let start = range.start.to_point(&display_map);
10847 let end = range.end.to_point(&display_map);
10848 start..end
10849 })
10850 .collect::<Vec<_>>();
10851
10852 self.unfold_ranges(ranges, true, true, cx);
10853 }
10854
10855 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10856 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10857
10858 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10859 ..Point::new(
10860 unfold_at.buffer_row.0,
10861 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10862 );
10863
10864 let autoscroll = self
10865 .selections
10866 .all::<Point>(cx)
10867 .iter()
10868 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10869
10870 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10871 }
10872
10873 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10874 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10875 self.unfold_ranges(
10876 [Point::zero()..display_map.max_point().to_point(&display_map)],
10877 true,
10878 true,
10879 cx,
10880 );
10881 }
10882
10883 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10884 let selections = self.selections.all::<Point>(cx);
10885 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10886 let line_mode = self.selections.line_mode;
10887 let ranges = selections.into_iter().map(|s| {
10888 if line_mode {
10889 let start = Point::new(s.start.row, 0);
10890 let end = Point::new(
10891 s.end.row,
10892 display_map
10893 .buffer_snapshot
10894 .line_len(MultiBufferRow(s.end.row)),
10895 );
10896 (start..end, display_map.fold_placeholder.clone())
10897 } else {
10898 (s.start..s.end, display_map.fold_placeholder.clone())
10899 }
10900 });
10901 self.fold_ranges(ranges, true, cx);
10902 }
10903
10904 pub fn fold_ranges<T: ToOffset + Clone>(
10905 &mut self,
10906 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10907 auto_scroll: bool,
10908 cx: &mut ViewContext<Self>,
10909 ) {
10910 let mut fold_ranges = Vec::new();
10911 let mut buffers_affected = HashMap::default();
10912 let multi_buffer = self.buffer().read(cx);
10913 for (fold_range, fold_text) in ranges {
10914 if let Some((_, buffer, _)) =
10915 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10916 {
10917 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10918 };
10919 fold_ranges.push((fold_range, fold_text));
10920 }
10921
10922 let mut ranges = fold_ranges.into_iter().peekable();
10923 if ranges.peek().is_some() {
10924 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10925
10926 if auto_scroll {
10927 self.request_autoscroll(Autoscroll::fit(), cx);
10928 }
10929
10930 for buffer in buffers_affected.into_values() {
10931 self.sync_expanded_diff_hunks(buffer, cx);
10932 }
10933
10934 cx.notify();
10935
10936 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10937 // Clear diagnostics block when folding a range that contains it.
10938 let snapshot = self.snapshot(cx);
10939 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10940 drop(snapshot);
10941 self.active_diagnostics = Some(active_diagnostics);
10942 self.dismiss_diagnostics(cx);
10943 } else {
10944 self.active_diagnostics = Some(active_diagnostics);
10945 }
10946 }
10947
10948 self.scrollbar_marker_state.dirty = true;
10949 }
10950 }
10951
10952 pub fn unfold_ranges<T: ToOffset + Clone>(
10953 &mut self,
10954 ranges: impl IntoIterator<Item = Range<T>>,
10955 inclusive: bool,
10956 auto_scroll: bool,
10957 cx: &mut ViewContext<Self>,
10958 ) {
10959 let mut unfold_ranges = Vec::new();
10960 let mut buffers_affected = HashMap::default();
10961 let multi_buffer = self.buffer().read(cx);
10962 for range in ranges {
10963 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10964 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10965 };
10966 unfold_ranges.push(range);
10967 }
10968
10969 let mut ranges = unfold_ranges.into_iter().peekable();
10970 if ranges.peek().is_some() {
10971 self.display_map
10972 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10973 if auto_scroll {
10974 self.request_autoscroll(Autoscroll::fit(), cx);
10975 }
10976
10977 for buffer in buffers_affected.into_values() {
10978 self.sync_expanded_diff_hunks(buffer, cx);
10979 }
10980
10981 cx.notify();
10982 self.scrollbar_marker_state.dirty = true;
10983 self.active_indent_guides_state.dirty = true;
10984 }
10985 }
10986
10987 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10988 self.display_map.read(cx).fold_placeholder.clone()
10989 }
10990
10991 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10992 if hovered != self.gutter_hovered {
10993 self.gutter_hovered = hovered;
10994 cx.notify();
10995 }
10996 }
10997
10998 pub fn insert_blocks(
10999 &mut self,
11000 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
11001 autoscroll: Option<Autoscroll>,
11002 cx: &mut ViewContext<Self>,
11003 ) -> Vec<CustomBlockId> {
11004 let blocks = self
11005 .display_map
11006 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
11007 if let Some(autoscroll) = autoscroll {
11008 self.request_autoscroll(autoscroll, cx);
11009 }
11010 cx.notify();
11011 blocks
11012 }
11013
11014 pub fn resize_blocks(
11015 &mut self,
11016 heights: HashMap<CustomBlockId, u32>,
11017 autoscroll: Option<Autoscroll>,
11018 cx: &mut ViewContext<Self>,
11019 ) {
11020 self.display_map
11021 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11022 if let Some(autoscroll) = autoscroll {
11023 self.request_autoscroll(autoscroll, cx);
11024 }
11025 cx.notify();
11026 }
11027
11028 pub fn replace_blocks(
11029 &mut self,
11030 renderers: HashMap<CustomBlockId, RenderBlock>,
11031 autoscroll: Option<Autoscroll>,
11032 cx: &mut ViewContext<Self>,
11033 ) {
11034 self.display_map
11035 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11036 if let Some(autoscroll) = autoscroll {
11037 self.request_autoscroll(autoscroll, cx);
11038 }
11039 cx.notify();
11040 }
11041
11042 pub fn remove_blocks(
11043 &mut self,
11044 block_ids: HashSet<CustomBlockId>,
11045 autoscroll: Option<Autoscroll>,
11046 cx: &mut ViewContext<Self>,
11047 ) {
11048 self.display_map.update(cx, |display_map, cx| {
11049 display_map.remove_blocks(block_ids, cx)
11050 });
11051 if let Some(autoscroll) = autoscroll {
11052 self.request_autoscroll(autoscroll, cx);
11053 }
11054 cx.notify();
11055 }
11056
11057 pub fn row_for_block(
11058 &self,
11059 block_id: CustomBlockId,
11060 cx: &mut ViewContext<Self>,
11061 ) -> Option<DisplayRow> {
11062 self.display_map
11063 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11064 }
11065
11066 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11067 self.focused_block = Some(focused_block);
11068 }
11069
11070 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11071 self.focused_block.take()
11072 }
11073
11074 pub fn insert_creases(
11075 &mut self,
11076 creases: impl IntoIterator<Item = Crease>,
11077 cx: &mut ViewContext<Self>,
11078 ) -> Vec<CreaseId> {
11079 self.display_map
11080 .update(cx, |map, cx| map.insert_creases(creases, cx))
11081 }
11082
11083 pub fn remove_creases(
11084 &mut self,
11085 ids: impl IntoIterator<Item = CreaseId>,
11086 cx: &mut ViewContext<Self>,
11087 ) {
11088 self.display_map
11089 .update(cx, |map, cx| map.remove_creases(ids, cx));
11090 }
11091
11092 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11093 self.display_map
11094 .update(cx, |map, cx| map.snapshot(cx))
11095 .longest_row()
11096 }
11097
11098 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11099 self.display_map
11100 .update(cx, |map, cx| map.snapshot(cx))
11101 .max_point()
11102 }
11103
11104 pub fn text(&self, cx: &AppContext) -> String {
11105 self.buffer.read(cx).read(cx).text()
11106 }
11107
11108 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11109 let text = self.text(cx);
11110 let text = text.trim();
11111
11112 if text.is_empty() {
11113 return None;
11114 }
11115
11116 Some(text.to_string())
11117 }
11118
11119 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11120 self.transact(cx, |this, cx| {
11121 this.buffer
11122 .read(cx)
11123 .as_singleton()
11124 .expect("you can only call set_text on editors for singleton buffers")
11125 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11126 });
11127 }
11128
11129 pub fn display_text(&self, cx: &mut AppContext) -> String {
11130 self.display_map
11131 .update(cx, |map, cx| map.snapshot(cx))
11132 .text()
11133 }
11134
11135 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11136 let mut wrap_guides = smallvec::smallvec![];
11137
11138 if self.show_wrap_guides == Some(false) {
11139 return wrap_guides;
11140 }
11141
11142 let settings = self.buffer.read(cx).settings_at(0, cx);
11143 if settings.show_wrap_guides {
11144 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11145 wrap_guides.push((soft_wrap as usize, true));
11146 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11147 wrap_guides.push((soft_wrap as usize, true));
11148 }
11149 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11150 }
11151
11152 wrap_guides
11153 }
11154
11155 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11156 let settings = self.buffer.read(cx).settings_at(0, cx);
11157 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11158 match mode {
11159 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11160 SoftWrap::None
11161 }
11162 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11163 language_settings::SoftWrap::PreferredLineLength => {
11164 SoftWrap::Column(settings.preferred_line_length)
11165 }
11166 language_settings::SoftWrap::Bounded => {
11167 SoftWrap::Bounded(settings.preferred_line_length)
11168 }
11169 }
11170 }
11171
11172 pub fn set_soft_wrap_mode(
11173 &mut self,
11174 mode: language_settings::SoftWrap,
11175 cx: &mut ViewContext<Self>,
11176 ) {
11177 self.soft_wrap_mode_override = Some(mode);
11178 cx.notify();
11179 }
11180
11181 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11182 let rem_size = cx.rem_size();
11183 self.display_map.update(cx, |map, cx| {
11184 map.set_font(
11185 style.text.font(),
11186 style.text.font_size.to_pixels(rem_size),
11187 cx,
11188 )
11189 });
11190 self.style = Some(style);
11191 }
11192
11193 pub fn style(&self) -> Option<&EditorStyle> {
11194 self.style.as_ref()
11195 }
11196
11197 // Called by the element. This method is not designed to be called outside of the editor
11198 // element's layout code because it does not notify when rewrapping is computed synchronously.
11199 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11200 self.display_map
11201 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11202 }
11203
11204 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11205 if self.soft_wrap_mode_override.is_some() {
11206 self.soft_wrap_mode_override.take();
11207 } else {
11208 let soft_wrap = match self.soft_wrap_mode(cx) {
11209 SoftWrap::GitDiff => return,
11210 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11211 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11212 language_settings::SoftWrap::None
11213 }
11214 };
11215 self.soft_wrap_mode_override = Some(soft_wrap);
11216 }
11217 cx.notify();
11218 }
11219
11220 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11221 let Some(workspace) = self.workspace() else {
11222 return;
11223 };
11224 let fs = workspace.read(cx).app_state().fs.clone();
11225 let current_show = TabBarSettings::get_global(cx).show;
11226 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11227 setting.show = Some(!current_show);
11228 });
11229 }
11230
11231 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11232 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11233 self.buffer
11234 .read(cx)
11235 .settings_at(0, cx)
11236 .indent_guides
11237 .enabled
11238 });
11239 self.show_indent_guides = Some(!currently_enabled);
11240 cx.notify();
11241 }
11242
11243 fn should_show_indent_guides(&self) -> Option<bool> {
11244 self.show_indent_guides
11245 }
11246
11247 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11248 let mut editor_settings = EditorSettings::get_global(cx).clone();
11249 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11250 EditorSettings::override_global(editor_settings, cx);
11251 }
11252
11253 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11254 self.use_relative_line_numbers
11255 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11256 }
11257
11258 pub fn toggle_relative_line_numbers(
11259 &mut self,
11260 _: &ToggleRelativeLineNumbers,
11261 cx: &mut ViewContext<Self>,
11262 ) {
11263 let is_relative = self.should_use_relative_line_numbers(cx);
11264 self.set_relative_line_number(Some(!is_relative), cx)
11265 }
11266
11267 pub fn set_relative_line_number(
11268 &mut self,
11269 is_relative: Option<bool>,
11270 cx: &mut ViewContext<Self>,
11271 ) {
11272 self.use_relative_line_numbers = is_relative;
11273 cx.notify();
11274 }
11275
11276 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11277 self.show_gutter = show_gutter;
11278 cx.notify();
11279 }
11280
11281 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11282 self.show_line_numbers = Some(show_line_numbers);
11283 cx.notify();
11284 }
11285
11286 pub fn set_show_git_diff_gutter(
11287 &mut self,
11288 show_git_diff_gutter: bool,
11289 cx: &mut ViewContext<Self>,
11290 ) {
11291 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11292 cx.notify();
11293 }
11294
11295 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11296 self.show_code_actions = Some(show_code_actions);
11297 cx.notify();
11298 }
11299
11300 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11301 self.show_runnables = Some(show_runnables);
11302 cx.notify();
11303 }
11304
11305 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11306 if self.display_map.read(cx).masked != masked {
11307 self.display_map.update(cx, |map, _| map.masked = masked);
11308 }
11309 cx.notify()
11310 }
11311
11312 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11313 self.show_wrap_guides = Some(show_wrap_guides);
11314 cx.notify();
11315 }
11316
11317 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11318 self.show_indent_guides = Some(show_indent_guides);
11319 cx.notify();
11320 }
11321
11322 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11323 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11324 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11325 if let Some(dir) = file.abs_path(cx).parent() {
11326 return Some(dir.to_owned());
11327 }
11328 }
11329
11330 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11331 return Some(project_path.path.to_path_buf());
11332 }
11333 }
11334
11335 None
11336 }
11337
11338 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11339 self.active_excerpt(cx)?
11340 .1
11341 .read(cx)
11342 .file()
11343 .and_then(|f| f.as_local())
11344 }
11345
11346 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11347 if let Some(target) = self.target_file(cx) {
11348 cx.reveal_path(&target.abs_path(cx));
11349 }
11350 }
11351
11352 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11353 if let Some(file) = self.target_file(cx) {
11354 if let Some(path) = file.abs_path(cx).to_str() {
11355 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11356 }
11357 }
11358 }
11359
11360 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11361 if let Some(file) = self.target_file(cx) {
11362 if let Some(path) = file.path().to_str() {
11363 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11364 }
11365 }
11366 }
11367
11368 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11369 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11370
11371 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11372 self.start_git_blame(true, cx);
11373 }
11374
11375 cx.notify();
11376 }
11377
11378 pub fn toggle_git_blame_inline(
11379 &mut self,
11380 _: &ToggleGitBlameInline,
11381 cx: &mut ViewContext<Self>,
11382 ) {
11383 self.toggle_git_blame_inline_internal(true, cx);
11384 cx.notify();
11385 }
11386
11387 pub fn git_blame_inline_enabled(&self) -> bool {
11388 self.git_blame_inline_enabled
11389 }
11390
11391 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11392 self.show_selection_menu = self
11393 .show_selection_menu
11394 .map(|show_selections_menu| !show_selections_menu)
11395 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11396
11397 cx.notify();
11398 }
11399
11400 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11401 self.show_selection_menu
11402 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11403 }
11404
11405 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11406 if let Some(project) = self.project.as_ref() {
11407 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11408 return;
11409 };
11410
11411 if buffer.read(cx).file().is_none() {
11412 return;
11413 }
11414
11415 let focused = self.focus_handle(cx).contains_focused(cx);
11416
11417 let project = project.clone();
11418 let blame =
11419 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11420 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11421 self.blame = Some(blame);
11422 }
11423 }
11424
11425 fn toggle_git_blame_inline_internal(
11426 &mut self,
11427 user_triggered: bool,
11428 cx: &mut ViewContext<Self>,
11429 ) {
11430 if self.git_blame_inline_enabled {
11431 self.git_blame_inline_enabled = false;
11432 self.show_git_blame_inline = false;
11433 self.show_git_blame_inline_delay_task.take();
11434 } else {
11435 self.git_blame_inline_enabled = true;
11436 self.start_git_blame_inline(user_triggered, cx);
11437 }
11438
11439 cx.notify();
11440 }
11441
11442 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11443 self.start_git_blame(user_triggered, cx);
11444
11445 if ProjectSettings::get_global(cx)
11446 .git
11447 .inline_blame_delay()
11448 .is_some()
11449 {
11450 self.start_inline_blame_timer(cx);
11451 } else {
11452 self.show_git_blame_inline = true
11453 }
11454 }
11455
11456 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11457 self.blame.as_ref()
11458 }
11459
11460 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11461 self.show_git_blame_gutter && self.has_blame_entries(cx)
11462 }
11463
11464 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11465 self.show_git_blame_inline
11466 && self.focus_handle.is_focused(cx)
11467 && !self.newest_selection_head_on_empty_line(cx)
11468 && self.has_blame_entries(cx)
11469 }
11470
11471 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11472 self.blame()
11473 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11474 }
11475
11476 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11477 let cursor_anchor = self.selections.newest_anchor().head();
11478
11479 let snapshot = self.buffer.read(cx).snapshot(cx);
11480 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11481
11482 snapshot.line_len(buffer_row) == 0
11483 }
11484
11485 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<url::Url>> {
11486 let buffer_and_selection = maybe!({
11487 let selection = self.selections.newest::<Point>(cx);
11488 let selection_range = selection.range();
11489
11490 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11491 (buffer, selection_range.start.row..selection_range.end.row)
11492 } else {
11493 let buffer_ranges = self
11494 .buffer()
11495 .read(cx)
11496 .range_to_buffer_ranges(selection_range, cx);
11497
11498 let (buffer, range, _) = if selection.reversed {
11499 buffer_ranges.first()
11500 } else {
11501 buffer_ranges.last()
11502 }?;
11503
11504 let snapshot = buffer.read(cx).snapshot();
11505 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11506 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11507 (buffer.clone(), selection)
11508 };
11509
11510 Some((buffer, selection))
11511 });
11512
11513 let Some((buffer, selection)) = buffer_and_selection else {
11514 return Task::ready(Err(anyhow!("failed to determine buffer and selection")));
11515 };
11516
11517 let Some(project) = self.project.as_ref() else {
11518 return Task::ready(Err(anyhow!("editor does not have project")));
11519 };
11520
11521 project.update(cx, |project, cx| {
11522 project.get_permalink_to_line(&buffer, selection, cx)
11523 })
11524 }
11525
11526 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11527 let permalink_task = self.get_permalink_to_line(cx);
11528 let workspace = self.workspace();
11529
11530 cx.spawn(|_, mut cx| async move {
11531 match permalink_task.await {
11532 Ok(permalink) => {
11533 cx.update(|cx| {
11534 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11535 })
11536 .ok();
11537 }
11538 Err(err) => {
11539 let message = format!("Failed to copy permalink: {err}");
11540
11541 Err::<(), anyhow::Error>(err).log_err();
11542
11543 if let Some(workspace) = workspace {
11544 workspace
11545 .update(&mut cx, |workspace, cx| {
11546 struct CopyPermalinkToLine;
11547
11548 workspace.show_toast(
11549 Toast::new(
11550 NotificationId::unique::<CopyPermalinkToLine>(),
11551 message,
11552 ),
11553 cx,
11554 )
11555 })
11556 .ok();
11557 }
11558 }
11559 }
11560 })
11561 .detach();
11562 }
11563
11564 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11565 if let Some(file) = self.target_file(cx) {
11566 if let Some(path) = file.path().to_str() {
11567 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11568 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11569 }
11570 }
11571 }
11572
11573 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11574 let permalink_task = self.get_permalink_to_line(cx);
11575 let workspace = self.workspace();
11576
11577 cx.spawn(|_, mut cx| async move {
11578 match permalink_task.await {
11579 Ok(permalink) => {
11580 cx.update(|cx| {
11581 cx.open_url(permalink.as_ref());
11582 })
11583 .ok();
11584 }
11585 Err(err) => {
11586 let message = format!("Failed to open permalink: {err}");
11587
11588 Err::<(), anyhow::Error>(err).log_err();
11589
11590 if let Some(workspace) = workspace {
11591 workspace
11592 .update(&mut cx, |workspace, cx| {
11593 struct OpenPermalinkToLine;
11594
11595 workspace.show_toast(
11596 Toast::new(
11597 NotificationId::unique::<OpenPermalinkToLine>(),
11598 message,
11599 ),
11600 cx,
11601 )
11602 })
11603 .ok();
11604 }
11605 }
11606 }
11607 })
11608 .detach();
11609 }
11610
11611 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11612 /// last highlight added will be used.
11613 ///
11614 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11615 pub fn highlight_rows<T: 'static>(
11616 &mut self,
11617 range: Range<Anchor>,
11618 color: Hsla,
11619 should_autoscroll: bool,
11620 cx: &mut ViewContext<Self>,
11621 ) {
11622 let snapshot = self.buffer().read(cx).snapshot(cx);
11623 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11624 let ix = row_highlights.binary_search_by(|highlight| {
11625 Ordering::Equal
11626 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11627 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11628 });
11629
11630 if let Err(mut ix) = ix {
11631 let index = post_inc(&mut self.highlight_order);
11632
11633 // If this range intersects with the preceding highlight, then merge it with
11634 // the preceding highlight. Otherwise insert a new highlight.
11635 let mut merged = false;
11636 if ix > 0 {
11637 let prev_highlight = &mut row_highlights[ix - 1];
11638 if prev_highlight
11639 .range
11640 .end
11641 .cmp(&range.start, &snapshot)
11642 .is_ge()
11643 {
11644 ix -= 1;
11645 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11646 prev_highlight.range.end = range.end;
11647 }
11648 merged = true;
11649 prev_highlight.index = index;
11650 prev_highlight.color = color;
11651 prev_highlight.should_autoscroll = should_autoscroll;
11652 }
11653 }
11654
11655 if !merged {
11656 row_highlights.insert(
11657 ix,
11658 RowHighlight {
11659 range: range.clone(),
11660 index,
11661 color,
11662 should_autoscroll,
11663 },
11664 );
11665 }
11666
11667 // If any of the following highlights intersect with this one, merge them.
11668 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11669 let highlight = &row_highlights[ix];
11670 if next_highlight
11671 .range
11672 .start
11673 .cmp(&highlight.range.end, &snapshot)
11674 .is_le()
11675 {
11676 if next_highlight
11677 .range
11678 .end
11679 .cmp(&highlight.range.end, &snapshot)
11680 .is_gt()
11681 {
11682 row_highlights[ix].range.end = next_highlight.range.end;
11683 }
11684 row_highlights.remove(ix + 1);
11685 } else {
11686 break;
11687 }
11688 }
11689 }
11690 }
11691
11692 /// Remove any highlighted row ranges of the given type that intersect the
11693 /// given ranges.
11694 pub fn remove_highlighted_rows<T: 'static>(
11695 &mut self,
11696 ranges_to_remove: Vec<Range<Anchor>>,
11697 cx: &mut ViewContext<Self>,
11698 ) {
11699 let snapshot = self.buffer().read(cx).snapshot(cx);
11700 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11701 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11702 row_highlights.retain(|highlight| {
11703 while let Some(range_to_remove) = ranges_to_remove.peek() {
11704 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11705 Ordering::Less | Ordering::Equal => {
11706 ranges_to_remove.next();
11707 }
11708 Ordering::Greater => {
11709 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11710 Ordering::Less | Ordering::Equal => {
11711 return false;
11712 }
11713 Ordering::Greater => break,
11714 }
11715 }
11716 }
11717 }
11718
11719 true
11720 })
11721 }
11722
11723 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11724 pub fn clear_row_highlights<T: 'static>(&mut self) {
11725 self.highlighted_rows.remove(&TypeId::of::<T>());
11726 }
11727
11728 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11729 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11730 self.highlighted_rows
11731 .get(&TypeId::of::<T>())
11732 .map_or(&[] as &[_], |vec| vec.as_slice())
11733 .iter()
11734 .map(|highlight| (highlight.range.clone(), highlight.color))
11735 }
11736
11737 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11738 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11739 /// Allows to ignore certain kinds of highlights.
11740 pub fn highlighted_display_rows(
11741 &mut self,
11742 cx: &mut WindowContext,
11743 ) -> BTreeMap<DisplayRow, Hsla> {
11744 let snapshot = self.snapshot(cx);
11745 let mut used_highlight_orders = HashMap::default();
11746 self.highlighted_rows
11747 .iter()
11748 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11749 .fold(
11750 BTreeMap::<DisplayRow, Hsla>::new(),
11751 |mut unique_rows, highlight| {
11752 let start = highlight.range.start.to_display_point(&snapshot);
11753 let end = highlight.range.end.to_display_point(&snapshot);
11754 let start_row = start.row().0;
11755 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11756 && end.column() == 0
11757 {
11758 end.row().0.saturating_sub(1)
11759 } else {
11760 end.row().0
11761 };
11762 for row in start_row..=end_row {
11763 let used_index =
11764 used_highlight_orders.entry(row).or_insert(highlight.index);
11765 if highlight.index >= *used_index {
11766 *used_index = highlight.index;
11767 unique_rows.insert(DisplayRow(row), highlight.color);
11768 }
11769 }
11770 unique_rows
11771 },
11772 )
11773 }
11774
11775 pub fn highlighted_display_row_for_autoscroll(
11776 &self,
11777 snapshot: &DisplaySnapshot,
11778 ) -> Option<DisplayRow> {
11779 self.highlighted_rows
11780 .values()
11781 .flat_map(|highlighted_rows| highlighted_rows.iter())
11782 .filter_map(|highlight| {
11783 if highlight.should_autoscroll {
11784 Some(highlight.range.start.to_display_point(snapshot).row())
11785 } else {
11786 None
11787 }
11788 })
11789 .min()
11790 }
11791
11792 pub fn set_search_within_ranges(
11793 &mut self,
11794 ranges: &[Range<Anchor>],
11795 cx: &mut ViewContext<Self>,
11796 ) {
11797 self.highlight_background::<SearchWithinRange>(
11798 ranges,
11799 |colors| colors.editor_document_highlight_read_background,
11800 cx,
11801 )
11802 }
11803
11804 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11805 self.breadcrumb_header = Some(new_header);
11806 }
11807
11808 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11809 self.clear_background_highlights::<SearchWithinRange>(cx);
11810 }
11811
11812 pub fn highlight_background<T: 'static>(
11813 &mut self,
11814 ranges: &[Range<Anchor>],
11815 color_fetcher: fn(&ThemeColors) -> Hsla,
11816 cx: &mut ViewContext<Self>,
11817 ) {
11818 self.background_highlights
11819 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11820 self.scrollbar_marker_state.dirty = true;
11821 cx.notify();
11822 }
11823
11824 pub fn clear_background_highlights<T: 'static>(
11825 &mut self,
11826 cx: &mut ViewContext<Self>,
11827 ) -> Option<BackgroundHighlight> {
11828 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11829 if !text_highlights.1.is_empty() {
11830 self.scrollbar_marker_state.dirty = true;
11831 cx.notify();
11832 }
11833 Some(text_highlights)
11834 }
11835
11836 pub fn highlight_gutter<T: 'static>(
11837 &mut self,
11838 ranges: &[Range<Anchor>],
11839 color_fetcher: fn(&AppContext) -> Hsla,
11840 cx: &mut ViewContext<Self>,
11841 ) {
11842 self.gutter_highlights
11843 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11844 cx.notify();
11845 }
11846
11847 pub fn clear_gutter_highlights<T: 'static>(
11848 &mut self,
11849 cx: &mut ViewContext<Self>,
11850 ) -> Option<GutterHighlight> {
11851 cx.notify();
11852 self.gutter_highlights.remove(&TypeId::of::<T>())
11853 }
11854
11855 #[cfg(feature = "test-support")]
11856 pub fn all_text_background_highlights(
11857 &mut self,
11858 cx: &mut ViewContext<Self>,
11859 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11860 let snapshot = self.snapshot(cx);
11861 let buffer = &snapshot.buffer_snapshot;
11862 let start = buffer.anchor_before(0);
11863 let end = buffer.anchor_after(buffer.len());
11864 let theme = cx.theme().colors();
11865 self.background_highlights_in_range(start..end, &snapshot, theme)
11866 }
11867
11868 #[cfg(feature = "test-support")]
11869 pub fn search_background_highlights(
11870 &mut self,
11871 cx: &mut ViewContext<Self>,
11872 ) -> Vec<Range<Point>> {
11873 let snapshot = self.buffer().read(cx).snapshot(cx);
11874
11875 let highlights = self
11876 .background_highlights
11877 .get(&TypeId::of::<items::BufferSearchHighlights>());
11878
11879 if let Some((_color, ranges)) = highlights {
11880 ranges
11881 .iter()
11882 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11883 .collect_vec()
11884 } else {
11885 vec![]
11886 }
11887 }
11888
11889 fn document_highlights_for_position<'a>(
11890 &'a self,
11891 position: Anchor,
11892 buffer: &'a MultiBufferSnapshot,
11893 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11894 let read_highlights = self
11895 .background_highlights
11896 .get(&TypeId::of::<DocumentHighlightRead>())
11897 .map(|h| &h.1);
11898 let write_highlights = self
11899 .background_highlights
11900 .get(&TypeId::of::<DocumentHighlightWrite>())
11901 .map(|h| &h.1);
11902 let left_position = position.bias_left(buffer);
11903 let right_position = position.bias_right(buffer);
11904 read_highlights
11905 .into_iter()
11906 .chain(write_highlights)
11907 .flat_map(move |ranges| {
11908 let start_ix = match ranges.binary_search_by(|probe| {
11909 let cmp = probe.end.cmp(&left_position, buffer);
11910 if cmp.is_ge() {
11911 Ordering::Greater
11912 } else {
11913 Ordering::Less
11914 }
11915 }) {
11916 Ok(i) | Err(i) => i,
11917 };
11918
11919 ranges[start_ix..]
11920 .iter()
11921 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11922 })
11923 }
11924
11925 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11926 self.background_highlights
11927 .get(&TypeId::of::<T>())
11928 .map_or(false, |(_, highlights)| !highlights.is_empty())
11929 }
11930
11931 pub fn background_highlights_in_range(
11932 &self,
11933 search_range: Range<Anchor>,
11934 display_snapshot: &DisplaySnapshot,
11935 theme: &ThemeColors,
11936 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11937 let mut results = Vec::new();
11938 for (color_fetcher, ranges) in self.background_highlights.values() {
11939 let color = color_fetcher(theme);
11940 let start_ix = match ranges.binary_search_by(|probe| {
11941 let cmp = probe
11942 .end
11943 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11944 if cmp.is_gt() {
11945 Ordering::Greater
11946 } else {
11947 Ordering::Less
11948 }
11949 }) {
11950 Ok(i) | Err(i) => i,
11951 };
11952 for range in &ranges[start_ix..] {
11953 if range
11954 .start
11955 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11956 .is_ge()
11957 {
11958 break;
11959 }
11960
11961 let start = range.start.to_display_point(display_snapshot);
11962 let end = range.end.to_display_point(display_snapshot);
11963 results.push((start..end, color))
11964 }
11965 }
11966 results
11967 }
11968
11969 pub fn background_highlight_row_ranges<T: 'static>(
11970 &self,
11971 search_range: Range<Anchor>,
11972 display_snapshot: &DisplaySnapshot,
11973 count: usize,
11974 ) -> Vec<RangeInclusive<DisplayPoint>> {
11975 let mut results = Vec::new();
11976 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11977 return vec![];
11978 };
11979
11980 let start_ix = match ranges.binary_search_by(|probe| {
11981 let cmp = probe
11982 .end
11983 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11984 if cmp.is_gt() {
11985 Ordering::Greater
11986 } else {
11987 Ordering::Less
11988 }
11989 }) {
11990 Ok(i) | Err(i) => i,
11991 };
11992 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11993 if let (Some(start_display), Some(end_display)) = (start, end) {
11994 results.push(
11995 start_display.to_display_point(display_snapshot)
11996 ..=end_display.to_display_point(display_snapshot),
11997 );
11998 }
11999 };
12000 let mut start_row: Option<Point> = None;
12001 let mut end_row: Option<Point> = None;
12002 if ranges.len() > count {
12003 return Vec::new();
12004 }
12005 for range in &ranges[start_ix..] {
12006 if range
12007 .start
12008 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12009 .is_ge()
12010 {
12011 break;
12012 }
12013 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
12014 if let Some(current_row) = &end_row {
12015 if end.row == current_row.row {
12016 continue;
12017 }
12018 }
12019 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
12020 if start_row.is_none() {
12021 assert_eq!(end_row, None);
12022 start_row = Some(start);
12023 end_row = Some(end);
12024 continue;
12025 }
12026 if let Some(current_end) = end_row.as_mut() {
12027 if start.row > current_end.row + 1 {
12028 push_region(start_row, end_row);
12029 start_row = Some(start);
12030 end_row = Some(end);
12031 } else {
12032 // Merge two hunks.
12033 *current_end = end;
12034 }
12035 } else {
12036 unreachable!();
12037 }
12038 }
12039 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12040 push_region(start_row, end_row);
12041 results
12042 }
12043
12044 pub fn gutter_highlights_in_range(
12045 &self,
12046 search_range: Range<Anchor>,
12047 display_snapshot: &DisplaySnapshot,
12048 cx: &AppContext,
12049 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12050 let mut results = Vec::new();
12051 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12052 let color = color_fetcher(cx);
12053 let start_ix = match ranges.binary_search_by(|probe| {
12054 let cmp = probe
12055 .end
12056 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12057 if cmp.is_gt() {
12058 Ordering::Greater
12059 } else {
12060 Ordering::Less
12061 }
12062 }) {
12063 Ok(i) | Err(i) => i,
12064 };
12065 for range in &ranges[start_ix..] {
12066 if range
12067 .start
12068 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12069 .is_ge()
12070 {
12071 break;
12072 }
12073
12074 let start = range.start.to_display_point(display_snapshot);
12075 let end = range.end.to_display_point(display_snapshot);
12076 results.push((start..end, color))
12077 }
12078 }
12079 results
12080 }
12081
12082 /// Get the text ranges corresponding to the redaction query
12083 pub fn redacted_ranges(
12084 &self,
12085 search_range: Range<Anchor>,
12086 display_snapshot: &DisplaySnapshot,
12087 cx: &WindowContext,
12088 ) -> Vec<Range<DisplayPoint>> {
12089 display_snapshot
12090 .buffer_snapshot
12091 .redacted_ranges(search_range, |file| {
12092 if let Some(file) = file {
12093 file.is_private()
12094 && EditorSettings::get(
12095 Some(SettingsLocation {
12096 worktree_id: file.worktree_id(cx),
12097 path: file.path().as_ref(),
12098 }),
12099 cx,
12100 )
12101 .redact_private_values
12102 } else {
12103 false
12104 }
12105 })
12106 .map(|range| {
12107 range.start.to_display_point(display_snapshot)
12108 ..range.end.to_display_point(display_snapshot)
12109 })
12110 .collect()
12111 }
12112
12113 pub fn highlight_text<T: 'static>(
12114 &mut self,
12115 ranges: Vec<Range<Anchor>>,
12116 style: HighlightStyle,
12117 cx: &mut ViewContext<Self>,
12118 ) {
12119 self.display_map.update(cx, |map, _| {
12120 map.highlight_text(TypeId::of::<T>(), ranges, style)
12121 });
12122 cx.notify();
12123 }
12124
12125 pub(crate) fn highlight_inlays<T: 'static>(
12126 &mut self,
12127 highlights: Vec<InlayHighlight>,
12128 style: HighlightStyle,
12129 cx: &mut ViewContext<Self>,
12130 ) {
12131 self.display_map.update(cx, |map, _| {
12132 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12133 });
12134 cx.notify();
12135 }
12136
12137 pub fn text_highlights<'a, T: 'static>(
12138 &'a self,
12139 cx: &'a AppContext,
12140 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12141 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12142 }
12143
12144 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12145 let cleared = self
12146 .display_map
12147 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12148 if cleared {
12149 cx.notify();
12150 }
12151 }
12152
12153 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12154 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12155 && self.focus_handle.is_focused(cx)
12156 }
12157
12158 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12159 self.show_cursor_when_unfocused = is_enabled;
12160 cx.notify();
12161 }
12162
12163 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12164 cx.notify();
12165 }
12166
12167 fn on_buffer_event(
12168 &mut self,
12169 multibuffer: Model<MultiBuffer>,
12170 event: &multi_buffer::Event,
12171 cx: &mut ViewContext<Self>,
12172 ) {
12173 match event {
12174 multi_buffer::Event::Edited {
12175 singleton_buffer_edited,
12176 } => {
12177 self.scrollbar_marker_state.dirty = true;
12178 self.active_indent_guides_state.dirty = true;
12179 self.refresh_active_diagnostics(cx);
12180 self.refresh_code_actions(cx);
12181 if self.has_active_inline_completion(cx) {
12182 self.update_visible_inline_completion(cx);
12183 }
12184 cx.emit(EditorEvent::BufferEdited);
12185 cx.emit(SearchEvent::MatchesInvalidated);
12186 if *singleton_buffer_edited {
12187 if let Some(project) = &self.project {
12188 let project = project.read(cx);
12189 #[allow(clippy::mutable_key_type)]
12190 let languages_affected = multibuffer
12191 .read(cx)
12192 .all_buffers()
12193 .into_iter()
12194 .filter_map(|buffer| {
12195 let buffer = buffer.read(cx);
12196 let language = buffer.language()?;
12197 if project.is_local()
12198 && project.language_servers_for_buffer(buffer, cx).count() == 0
12199 {
12200 None
12201 } else {
12202 Some(language)
12203 }
12204 })
12205 .cloned()
12206 .collect::<HashSet<_>>();
12207 if !languages_affected.is_empty() {
12208 self.refresh_inlay_hints(
12209 InlayHintRefreshReason::BufferEdited(languages_affected),
12210 cx,
12211 );
12212 }
12213 }
12214 }
12215
12216 let Some(project) = &self.project else { return };
12217 let (telemetry, is_via_ssh) = {
12218 let project = project.read(cx);
12219 let telemetry = project.client().telemetry().clone();
12220 let is_via_ssh = project.is_via_ssh();
12221 (telemetry, is_via_ssh)
12222 };
12223 refresh_linked_ranges(self, cx);
12224 telemetry.log_edit_event("editor", is_via_ssh);
12225 }
12226 multi_buffer::Event::ExcerptsAdded {
12227 buffer,
12228 predecessor,
12229 excerpts,
12230 } => {
12231 self.tasks_update_task = Some(self.refresh_runnables(cx));
12232 cx.emit(EditorEvent::ExcerptsAdded {
12233 buffer: buffer.clone(),
12234 predecessor: *predecessor,
12235 excerpts: excerpts.clone(),
12236 });
12237 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12238 }
12239 multi_buffer::Event::ExcerptsRemoved { ids } => {
12240 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12241 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12242 }
12243 multi_buffer::Event::ExcerptsEdited { ids } => {
12244 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12245 }
12246 multi_buffer::Event::ExcerptsExpanded { ids } => {
12247 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12248 }
12249 multi_buffer::Event::Reparsed(buffer_id) => {
12250 self.tasks_update_task = Some(self.refresh_runnables(cx));
12251
12252 cx.emit(EditorEvent::Reparsed(*buffer_id));
12253 }
12254 multi_buffer::Event::LanguageChanged(buffer_id) => {
12255 linked_editing_ranges::refresh_linked_ranges(self, cx);
12256 cx.emit(EditorEvent::Reparsed(*buffer_id));
12257 cx.notify();
12258 }
12259 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12260 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12261 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12262 cx.emit(EditorEvent::TitleChanged)
12263 }
12264 multi_buffer::Event::DiffBaseChanged => {
12265 self.scrollbar_marker_state.dirty = true;
12266 cx.emit(EditorEvent::DiffBaseChanged);
12267 cx.notify();
12268 }
12269 multi_buffer::Event::DiffUpdated { buffer } => {
12270 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12271 cx.notify();
12272 }
12273 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12274 multi_buffer::Event::DiagnosticsUpdated => {
12275 self.refresh_active_diagnostics(cx);
12276 self.scrollbar_marker_state.dirty = true;
12277 cx.notify();
12278 }
12279 _ => {}
12280 };
12281 }
12282
12283 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12284 cx.notify();
12285 }
12286
12287 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12288 self.tasks_update_task = Some(self.refresh_runnables(cx));
12289 self.refresh_inline_completion(true, false, cx);
12290 self.refresh_inlay_hints(
12291 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12292 self.selections.newest_anchor().head(),
12293 &self.buffer.read(cx).snapshot(cx),
12294 cx,
12295 )),
12296 cx,
12297 );
12298
12299 let old_cursor_shape = self.cursor_shape;
12300
12301 {
12302 let editor_settings = EditorSettings::get_global(cx);
12303 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12304 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12305 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12306 }
12307
12308 if old_cursor_shape != self.cursor_shape {
12309 cx.emit(EditorEvent::CursorShapeChanged);
12310 }
12311
12312 let project_settings = ProjectSettings::get_global(cx);
12313 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12314
12315 if self.mode == EditorMode::Full {
12316 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12317 if self.git_blame_inline_enabled != inline_blame_enabled {
12318 self.toggle_git_blame_inline_internal(false, cx);
12319 }
12320 }
12321
12322 cx.notify();
12323 }
12324
12325 pub fn set_searchable(&mut self, searchable: bool) {
12326 self.searchable = searchable;
12327 }
12328
12329 pub fn searchable(&self) -> bool {
12330 self.searchable
12331 }
12332
12333 fn open_proposed_changes_editor(
12334 &mut self,
12335 _: &OpenProposedChangesEditor,
12336 cx: &mut ViewContext<Self>,
12337 ) {
12338 let Some(workspace) = self.workspace() else {
12339 cx.propagate();
12340 return;
12341 };
12342
12343 let buffer = self.buffer.read(cx);
12344 let mut new_selections_by_buffer = HashMap::default();
12345 for selection in self.selections.all::<usize>(cx) {
12346 for (buffer, range, _) in
12347 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12348 {
12349 let mut range = range.to_point(buffer.read(cx));
12350 range.start.column = 0;
12351 range.end.column = buffer.read(cx).line_len(range.end.row);
12352 new_selections_by_buffer
12353 .entry(buffer)
12354 .or_insert(Vec::new())
12355 .push(range)
12356 }
12357 }
12358
12359 let proposed_changes_buffers = new_selections_by_buffer
12360 .into_iter()
12361 .map(|(buffer, ranges)| ProposedChangeLocation { buffer, ranges })
12362 .collect::<Vec<_>>();
12363 let proposed_changes_editor = cx.new_view(|cx| {
12364 ProposedChangesEditor::new(
12365 "Proposed changes",
12366 proposed_changes_buffers,
12367 self.project.clone(),
12368 cx,
12369 )
12370 });
12371
12372 cx.window_context().defer(move |cx| {
12373 workspace.update(cx, |workspace, cx| {
12374 workspace.active_pane().update(cx, |pane, cx| {
12375 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12376 });
12377 });
12378 });
12379 }
12380
12381 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12382 self.open_excerpts_common(true, cx)
12383 }
12384
12385 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12386 self.open_excerpts_common(false, cx)
12387 }
12388
12389 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12390 let buffer = self.buffer.read(cx);
12391 if buffer.is_singleton() {
12392 cx.propagate();
12393 return;
12394 }
12395
12396 let Some(workspace) = self.workspace() else {
12397 cx.propagate();
12398 return;
12399 };
12400
12401 let mut new_selections_by_buffer = HashMap::default();
12402 for selection in self.selections.all::<usize>(cx) {
12403 for (mut buffer_handle, mut range, _) in
12404 buffer.range_to_buffer_ranges(selection.range(), cx)
12405 {
12406 // When editing branch buffers, jump to the corresponding location
12407 // in their base buffer.
12408 let buffer = buffer_handle.read(cx);
12409 if let Some(base_buffer) = buffer.diff_base_buffer() {
12410 range = buffer.range_to_version(range, &base_buffer.read(cx).version());
12411 buffer_handle = base_buffer;
12412 }
12413
12414 if selection.reversed {
12415 mem::swap(&mut range.start, &mut range.end);
12416 }
12417 new_selections_by_buffer
12418 .entry(buffer_handle)
12419 .or_insert(Vec::new())
12420 .push(range)
12421 }
12422 }
12423
12424 // We defer the pane interaction because we ourselves are a workspace item
12425 // and activating a new item causes the pane to call a method on us reentrantly,
12426 // which panics if we're on the stack.
12427 cx.window_context().defer(move |cx| {
12428 workspace.update(cx, |workspace, cx| {
12429 let pane = if split {
12430 workspace.adjacent_pane(cx)
12431 } else {
12432 workspace.active_pane().clone()
12433 };
12434
12435 for (buffer, ranges) in new_selections_by_buffer {
12436 let editor =
12437 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12438 editor.update(cx, |editor, cx| {
12439 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12440 s.select_ranges(ranges);
12441 });
12442 });
12443 }
12444 })
12445 });
12446 }
12447
12448 fn jump(
12449 &mut self,
12450 path: ProjectPath,
12451 position: Point,
12452 anchor: language::Anchor,
12453 offset_from_top: u32,
12454 cx: &mut ViewContext<Self>,
12455 ) {
12456 let workspace = self.workspace();
12457 cx.spawn(|_, mut cx| async move {
12458 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12459 let editor = workspace.update(&mut cx, |workspace, cx| {
12460 // Reset the preview item id before opening the new item
12461 workspace.active_pane().update(cx, |pane, cx| {
12462 pane.set_preview_item_id(None, cx);
12463 });
12464 workspace.open_path_preview(path, None, true, true, cx)
12465 })?;
12466 let editor = editor
12467 .await?
12468 .downcast::<Editor>()
12469 .ok_or_else(|| anyhow!("opened item was not an editor"))?
12470 .downgrade();
12471 editor.update(&mut cx, |editor, cx| {
12472 let buffer = editor
12473 .buffer()
12474 .read(cx)
12475 .as_singleton()
12476 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12477 let buffer = buffer.read(cx);
12478 let cursor = if buffer.can_resolve(&anchor) {
12479 language::ToPoint::to_point(&anchor, buffer)
12480 } else {
12481 buffer.clip_point(position, Bias::Left)
12482 };
12483
12484 let nav_history = editor.nav_history.take();
12485 editor.change_selections(
12486 Some(Autoscroll::top_relative(offset_from_top as usize)),
12487 cx,
12488 |s| {
12489 s.select_ranges([cursor..cursor]);
12490 },
12491 );
12492 editor.nav_history = nav_history;
12493
12494 anyhow::Ok(())
12495 })??;
12496
12497 anyhow::Ok(())
12498 })
12499 .detach_and_log_err(cx);
12500 }
12501
12502 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12503 let snapshot = self.buffer.read(cx).read(cx);
12504 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12505 Some(
12506 ranges
12507 .iter()
12508 .map(move |range| {
12509 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12510 })
12511 .collect(),
12512 )
12513 }
12514
12515 fn selection_replacement_ranges(
12516 &self,
12517 range: Range<OffsetUtf16>,
12518 cx: &AppContext,
12519 ) -> Vec<Range<OffsetUtf16>> {
12520 let selections = self.selections.all::<OffsetUtf16>(cx);
12521 let newest_selection = selections
12522 .iter()
12523 .max_by_key(|selection| selection.id)
12524 .unwrap();
12525 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12526 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12527 let snapshot = self.buffer.read(cx).read(cx);
12528 selections
12529 .into_iter()
12530 .map(|mut selection| {
12531 selection.start.0 =
12532 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12533 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12534 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12535 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12536 })
12537 .collect()
12538 }
12539
12540 fn report_editor_event(
12541 &self,
12542 operation: &'static str,
12543 file_extension: Option<String>,
12544 cx: &AppContext,
12545 ) {
12546 if cfg!(any(test, feature = "test-support")) {
12547 return;
12548 }
12549
12550 let Some(project) = &self.project else { return };
12551
12552 // If None, we are in a file without an extension
12553 let file = self
12554 .buffer
12555 .read(cx)
12556 .as_singleton()
12557 .and_then(|b| b.read(cx).file());
12558 let file_extension = file_extension.or(file
12559 .as_ref()
12560 .and_then(|file| Path::new(file.file_name(cx)).extension())
12561 .and_then(|e| e.to_str())
12562 .map(|a| a.to_string()));
12563
12564 let vim_mode = cx
12565 .global::<SettingsStore>()
12566 .raw_user_settings()
12567 .get("vim_mode")
12568 == Some(&serde_json::Value::Bool(true));
12569
12570 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12571 == language::language_settings::InlineCompletionProvider::Copilot;
12572 let copilot_enabled_for_language = self
12573 .buffer
12574 .read(cx)
12575 .settings_at(0, cx)
12576 .show_inline_completions;
12577
12578 let project = project.read(cx);
12579 let telemetry = project.client().telemetry().clone();
12580 telemetry.report_editor_event(
12581 file_extension,
12582 vim_mode,
12583 operation,
12584 copilot_enabled,
12585 copilot_enabled_for_language,
12586 project.is_via_ssh(),
12587 )
12588 }
12589
12590 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12591 /// with each line being an array of {text, highlight} objects.
12592 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12593 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12594 return;
12595 };
12596
12597 #[derive(Serialize)]
12598 struct Chunk<'a> {
12599 text: String,
12600 highlight: Option<&'a str>,
12601 }
12602
12603 let snapshot = buffer.read(cx).snapshot();
12604 let range = self
12605 .selected_text_range(false, cx)
12606 .and_then(|selection| {
12607 if selection.range.is_empty() {
12608 None
12609 } else {
12610 Some(selection.range)
12611 }
12612 })
12613 .unwrap_or_else(|| 0..snapshot.len());
12614
12615 let chunks = snapshot.chunks(range, true);
12616 let mut lines = Vec::new();
12617 let mut line: VecDeque<Chunk> = VecDeque::new();
12618
12619 let Some(style) = self.style.as_ref() else {
12620 return;
12621 };
12622
12623 for chunk in chunks {
12624 let highlight = chunk
12625 .syntax_highlight_id
12626 .and_then(|id| id.name(&style.syntax));
12627 let mut chunk_lines = chunk.text.split('\n').peekable();
12628 while let Some(text) = chunk_lines.next() {
12629 let mut merged_with_last_token = false;
12630 if let Some(last_token) = line.back_mut() {
12631 if last_token.highlight == highlight {
12632 last_token.text.push_str(text);
12633 merged_with_last_token = true;
12634 }
12635 }
12636
12637 if !merged_with_last_token {
12638 line.push_back(Chunk {
12639 text: text.into(),
12640 highlight,
12641 });
12642 }
12643
12644 if chunk_lines.peek().is_some() {
12645 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12646 line.pop_front();
12647 }
12648 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12649 line.pop_back();
12650 }
12651
12652 lines.push(mem::take(&mut line));
12653 }
12654 }
12655 }
12656
12657 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12658 return;
12659 };
12660 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12661 }
12662
12663 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12664 &self.inlay_hint_cache
12665 }
12666
12667 pub fn replay_insert_event(
12668 &mut self,
12669 text: &str,
12670 relative_utf16_range: Option<Range<isize>>,
12671 cx: &mut ViewContext<Self>,
12672 ) {
12673 if !self.input_enabled {
12674 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12675 return;
12676 }
12677 if let Some(relative_utf16_range) = relative_utf16_range {
12678 let selections = self.selections.all::<OffsetUtf16>(cx);
12679 self.change_selections(None, cx, |s| {
12680 let new_ranges = selections.into_iter().map(|range| {
12681 let start = OffsetUtf16(
12682 range
12683 .head()
12684 .0
12685 .saturating_add_signed(relative_utf16_range.start),
12686 );
12687 let end = OffsetUtf16(
12688 range
12689 .head()
12690 .0
12691 .saturating_add_signed(relative_utf16_range.end),
12692 );
12693 start..end
12694 });
12695 s.select_ranges(new_ranges);
12696 });
12697 }
12698
12699 self.handle_input(text, cx);
12700 }
12701
12702 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12703 let Some(provider) = self.semantics_provider.as_ref() else {
12704 return false;
12705 };
12706
12707 let mut supports = false;
12708 self.buffer().read(cx).for_each_buffer(|buffer| {
12709 supports |= provider.supports_inlay_hints(buffer, cx);
12710 });
12711 supports
12712 }
12713
12714 pub fn focus(&self, cx: &mut WindowContext) {
12715 cx.focus(&self.focus_handle)
12716 }
12717
12718 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12719 self.focus_handle.is_focused(cx)
12720 }
12721
12722 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12723 cx.emit(EditorEvent::Focused);
12724
12725 if let Some(descendant) = self
12726 .last_focused_descendant
12727 .take()
12728 .and_then(|descendant| descendant.upgrade())
12729 {
12730 cx.focus(&descendant);
12731 } else {
12732 if let Some(blame) = self.blame.as_ref() {
12733 blame.update(cx, GitBlame::focus)
12734 }
12735
12736 self.blink_manager.update(cx, BlinkManager::enable);
12737 self.show_cursor_names(cx);
12738 self.buffer.update(cx, |buffer, cx| {
12739 buffer.finalize_last_transaction(cx);
12740 if self.leader_peer_id.is_none() {
12741 buffer.set_active_selections(
12742 &self.selections.disjoint_anchors(),
12743 self.selections.line_mode,
12744 self.cursor_shape,
12745 cx,
12746 );
12747 }
12748 });
12749 }
12750 }
12751
12752 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12753 cx.emit(EditorEvent::FocusedIn)
12754 }
12755
12756 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12757 if event.blurred != self.focus_handle {
12758 self.last_focused_descendant = Some(event.blurred);
12759 }
12760 }
12761
12762 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12763 self.blink_manager.update(cx, BlinkManager::disable);
12764 self.buffer
12765 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12766
12767 if let Some(blame) = self.blame.as_ref() {
12768 blame.update(cx, GitBlame::blur)
12769 }
12770 if !self.hover_state.focused(cx) {
12771 hide_hover(self, cx);
12772 }
12773
12774 self.hide_context_menu(cx);
12775 cx.emit(EditorEvent::Blurred);
12776 cx.notify();
12777 }
12778
12779 pub fn register_action<A: Action>(
12780 &mut self,
12781 listener: impl Fn(&A, &mut WindowContext) + 'static,
12782 ) -> Subscription {
12783 let id = self.next_editor_action_id.post_inc();
12784 let listener = Arc::new(listener);
12785 self.editor_actions.borrow_mut().insert(
12786 id,
12787 Box::new(move |cx| {
12788 let cx = cx.window_context();
12789 let listener = listener.clone();
12790 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12791 let action = action.downcast_ref().unwrap();
12792 if phase == DispatchPhase::Bubble {
12793 listener(action, cx)
12794 }
12795 })
12796 }),
12797 );
12798
12799 let editor_actions = self.editor_actions.clone();
12800 Subscription::new(move || {
12801 editor_actions.borrow_mut().remove(&id);
12802 })
12803 }
12804
12805 pub fn file_header_size(&self) -> u32 {
12806 FILE_HEADER_HEIGHT
12807 }
12808
12809 pub fn revert(
12810 &mut self,
12811 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12812 cx: &mut ViewContext<Self>,
12813 ) {
12814 self.buffer().update(cx, |multi_buffer, cx| {
12815 for (buffer_id, changes) in revert_changes {
12816 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12817 buffer.update(cx, |buffer, cx| {
12818 buffer.edit(
12819 changes.into_iter().map(|(range, text)| {
12820 (range, text.to_string().map(Arc::<str>::from))
12821 }),
12822 None,
12823 cx,
12824 );
12825 });
12826 }
12827 }
12828 });
12829 self.change_selections(None, cx, |selections| selections.refresh());
12830 }
12831
12832 pub fn to_pixel_point(
12833 &mut self,
12834 source: multi_buffer::Anchor,
12835 editor_snapshot: &EditorSnapshot,
12836 cx: &mut ViewContext<Self>,
12837 ) -> Option<gpui::Point<Pixels>> {
12838 let source_point = source.to_display_point(editor_snapshot);
12839 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12840 }
12841
12842 pub fn display_to_pixel_point(
12843 &mut self,
12844 source: DisplayPoint,
12845 editor_snapshot: &EditorSnapshot,
12846 cx: &mut ViewContext<Self>,
12847 ) -> Option<gpui::Point<Pixels>> {
12848 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12849 let text_layout_details = self.text_layout_details(cx);
12850 let scroll_top = text_layout_details
12851 .scroll_anchor
12852 .scroll_position(editor_snapshot)
12853 .y;
12854
12855 if source.row().as_f32() < scroll_top.floor() {
12856 return None;
12857 }
12858 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12859 let source_y = line_height * (source.row().as_f32() - scroll_top);
12860 Some(gpui::Point::new(source_x, source_y))
12861 }
12862
12863 pub fn has_active_completions_menu(&self) -> bool {
12864 self.context_menu.read().as_ref().map_or(false, |menu| {
12865 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12866 })
12867 }
12868
12869 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12870 self.addons
12871 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12872 }
12873
12874 pub fn unregister_addon<T: Addon>(&mut self) {
12875 self.addons.remove(&std::any::TypeId::of::<T>());
12876 }
12877
12878 pub fn addon<T: Addon>(&self) -> Option<&T> {
12879 let type_id = std::any::TypeId::of::<T>();
12880 self.addons
12881 .get(&type_id)
12882 .and_then(|item| item.to_any().downcast_ref::<T>())
12883 }
12884}
12885
12886fn hunks_for_selections(
12887 multi_buffer_snapshot: &MultiBufferSnapshot,
12888 selections: &[Selection<Anchor>],
12889) -> Vec<MultiBufferDiffHunk> {
12890 let buffer_rows_for_selections = selections.iter().map(|selection| {
12891 let head = selection.head();
12892 let tail = selection.tail();
12893 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12894 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12895 if start > end {
12896 end..start
12897 } else {
12898 start..end
12899 }
12900 });
12901
12902 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12903}
12904
12905pub fn hunks_for_rows(
12906 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12907 multi_buffer_snapshot: &MultiBufferSnapshot,
12908) -> Vec<MultiBufferDiffHunk> {
12909 let mut hunks = Vec::new();
12910 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12911 HashMap::default();
12912 for selected_multi_buffer_rows in rows {
12913 let query_rows =
12914 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12915 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12916 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12917 // when the caret is just above or just below the deleted hunk.
12918 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12919 let related_to_selection = if allow_adjacent {
12920 hunk.row_range.overlaps(&query_rows)
12921 || hunk.row_range.start == query_rows.end
12922 || hunk.row_range.end == query_rows.start
12923 } else {
12924 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12925 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12926 hunk.row_range.overlaps(&selected_multi_buffer_rows)
12927 || selected_multi_buffer_rows.end == hunk.row_range.start
12928 };
12929 if related_to_selection {
12930 if !processed_buffer_rows
12931 .entry(hunk.buffer_id)
12932 .or_default()
12933 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12934 {
12935 continue;
12936 }
12937 hunks.push(hunk);
12938 }
12939 }
12940 }
12941
12942 hunks
12943}
12944
12945pub trait CollaborationHub {
12946 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12947 fn user_participant_indices<'a>(
12948 &self,
12949 cx: &'a AppContext,
12950 ) -> &'a HashMap<u64, ParticipantIndex>;
12951 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12952}
12953
12954impl CollaborationHub for Model<Project> {
12955 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12956 self.read(cx).collaborators()
12957 }
12958
12959 fn user_participant_indices<'a>(
12960 &self,
12961 cx: &'a AppContext,
12962 ) -> &'a HashMap<u64, ParticipantIndex> {
12963 self.read(cx).user_store().read(cx).participant_indices()
12964 }
12965
12966 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12967 let this = self.read(cx);
12968 let user_ids = this.collaborators().values().map(|c| c.user_id);
12969 this.user_store().read_with(cx, |user_store, cx| {
12970 user_store.participant_names(user_ids, cx)
12971 })
12972 }
12973}
12974
12975pub trait SemanticsProvider {
12976 fn hover(
12977 &self,
12978 buffer: &Model<Buffer>,
12979 position: text::Anchor,
12980 cx: &mut AppContext,
12981 ) -> Option<Task<Vec<project::Hover>>>;
12982
12983 fn inlay_hints(
12984 &self,
12985 buffer_handle: Model<Buffer>,
12986 range: Range<text::Anchor>,
12987 cx: &mut AppContext,
12988 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>>;
12989
12990 fn resolve_inlay_hint(
12991 &self,
12992 hint: InlayHint,
12993 buffer_handle: Model<Buffer>,
12994 server_id: LanguageServerId,
12995 cx: &mut AppContext,
12996 ) -> Option<Task<anyhow::Result<InlayHint>>>;
12997
12998 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool;
12999
13000 fn document_highlights(
13001 &self,
13002 buffer: &Model<Buffer>,
13003 position: text::Anchor,
13004 cx: &mut AppContext,
13005 ) -> Option<Task<Result<Vec<DocumentHighlight>>>>;
13006
13007 fn definitions(
13008 &self,
13009 buffer: &Model<Buffer>,
13010 position: text::Anchor,
13011 kind: GotoDefinitionKind,
13012 cx: &mut AppContext,
13013 ) -> Option<Task<Result<Vec<LocationLink>>>>;
13014
13015 fn range_for_rename(
13016 &self,
13017 buffer: &Model<Buffer>,
13018 position: text::Anchor,
13019 cx: &mut AppContext,
13020 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>>;
13021
13022 fn perform_rename(
13023 &self,
13024 buffer: &Model<Buffer>,
13025 position: text::Anchor,
13026 new_name: String,
13027 cx: &mut AppContext,
13028 ) -> Option<Task<Result<ProjectTransaction>>>;
13029}
13030
13031pub trait CompletionProvider {
13032 fn completions(
13033 &self,
13034 buffer: &Model<Buffer>,
13035 buffer_position: text::Anchor,
13036 trigger: CompletionContext,
13037 cx: &mut ViewContext<Editor>,
13038 ) -> Task<Result<Vec<Completion>>>;
13039
13040 fn resolve_completions(
13041 &self,
13042 buffer: Model<Buffer>,
13043 completion_indices: Vec<usize>,
13044 completions: Arc<RwLock<Box<[Completion]>>>,
13045 cx: &mut ViewContext<Editor>,
13046 ) -> Task<Result<bool>>;
13047
13048 fn apply_additional_edits_for_completion(
13049 &self,
13050 buffer: Model<Buffer>,
13051 completion: Completion,
13052 push_to_history: bool,
13053 cx: &mut ViewContext<Editor>,
13054 ) -> Task<Result<Option<language::Transaction>>>;
13055
13056 fn is_completion_trigger(
13057 &self,
13058 buffer: &Model<Buffer>,
13059 position: language::Anchor,
13060 text: &str,
13061 trigger_in_words: bool,
13062 cx: &mut ViewContext<Editor>,
13063 ) -> bool;
13064
13065 fn sort_completions(&self) -> bool {
13066 true
13067 }
13068}
13069
13070pub trait CodeActionProvider {
13071 fn code_actions(
13072 &self,
13073 buffer: &Model<Buffer>,
13074 range: Range<text::Anchor>,
13075 cx: &mut WindowContext,
13076 ) -> Task<Result<Vec<CodeAction>>>;
13077
13078 fn apply_code_action(
13079 &self,
13080 buffer_handle: Model<Buffer>,
13081 action: CodeAction,
13082 excerpt_id: ExcerptId,
13083 push_to_history: bool,
13084 cx: &mut WindowContext,
13085 ) -> Task<Result<ProjectTransaction>>;
13086}
13087
13088impl CodeActionProvider for Model<Project> {
13089 fn code_actions(
13090 &self,
13091 buffer: &Model<Buffer>,
13092 range: Range<text::Anchor>,
13093 cx: &mut WindowContext,
13094 ) -> Task<Result<Vec<CodeAction>>> {
13095 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13096 }
13097
13098 fn apply_code_action(
13099 &self,
13100 buffer_handle: Model<Buffer>,
13101 action: CodeAction,
13102 _excerpt_id: ExcerptId,
13103 push_to_history: bool,
13104 cx: &mut WindowContext,
13105 ) -> Task<Result<ProjectTransaction>> {
13106 self.update(cx, |project, cx| {
13107 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13108 })
13109 }
13110}
13111
13112fn snippet_completions(
13113 project: &Project,
13114 buffer: &Model<Buffer>,
13115 buffer_position: text::Anchor,
13116 cx: &mut AppContext,
13117) -> Vec<Completion> {
13118 let language = buffer.read(cx).language_at(buffer_position);
13119 let language_name = language.as_ref().map(|language| language.lsp_id());
13120 let snippet_store = project.snippets().read(cx);
13121 let snippets = snippet_store.snippets_for(language_name, cx);
13122
13123 if snippets.is_empty() {
13124 return vec![];
13125 }
13126 let snapshot = buffer.read(cx).text_snapshot();
13127 let chars = snapshot.reversed_chars_for_range(text::Anchor::MIN..buffer_position);
13128
13129 let scope = language.map(|language| language.default_scope());
13130 let classifier = CharClassifier::new(scope).for_completion(true);
13131 let mut last_word = chars
13132 .take_while(|c| classifier.is_word(*c))
13133 .collect::<String>();
13134 last_word = last_word.chars().rev().collect();
13135 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13136 let to_lsp = |point: &text::Anchor| {
13137 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13138 point_to_lsp(end)
13139 };
13140 let lsp_end = to_lsp(&buffer_position);
13141 snippets
13142 .into_iter()
13143 .filter_map(|snippet| {
13144 let matching_prefix = snippet
13145 .prefix
13146 .iter()
13147 .find(|prefix| prefix.starts_with(&last_word))?;
13148 let start = as_offset - last_word.len();
13149 let start = snapshot.anchor_before(start);
13150 let range = start..buffer_position;
13151 let lsp_start = to_lsp(&start);
13152 let lsp_range = lsp::Range {
13153 start: lsp_start,
13154 end: lsp_end,
13155 };
13156 Some(Completion {
13157 old_range: range,
13158 new_text: snippet.body.clone(),
13159 label: CodeLabel {
13160 text: matching_prefix.clone(),
13161 runs: vec![],
13162 filter_range: 0..matching_prefix.len(),
13163 },
13164 server_id: LanguageServerId(usize::MAX),
13165 documentation: snippet.description.clone().map(Documentation::SingleLine),
13166 lsp_completion: lsp::CompletionItem {
13167 label: snippet.prefix.first().unwrap().clone(),
13168 kind: Some(CompletionItemKind::SNIPPET),
13169 label_details: snippet.description.as_ref().map(|description| {
13170 lsp::CompletionItemLabelDetails {
13171 detail: Some(description.clone()),
13172 description: None,
13173 }
13174 }),
13175 insert_text_format: Some(InsertTextFormat::SNIPPET),
13176 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13177 lsp::InsertReplaceEdit {
13178 new_text: snippet.body.clone(),
13179 insert: lsp_range,
13180 replace: lsp_range,
13181 },
13182 )),
13183 filter_text: Some(snippet.body.clone()),
13184 sort_text: Some(char::MAX.to_string()),
13185 ..Default::default()
13186 },
13187 confirm: None,
13188 })
13189 })
13190 .collect()
13191}
13192
13193impl CompletionProvider for Model<Project> {
13194 fn completions(
13195 &self,
13196 buffer: &Model<Buffer>,
13197 buffer_position: text::Anchor,
13198 options: CompletionContext,
13199 cx: &mut ViewContext<Editor>,
13200 ) -> Task<Result<Vec<Completion>>> {
13201 self.update(cx, |project, cx| {
13202 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13203 let project_completions = project.completions(buffer, buffer_position, options, cx);
13204 cx.background_executor().spawn(async move {
13205 let mut completions = project_completions.await?;
13206 //let snippets = snippets.into_iter().;
13207 completions.extend(snippets);
13208 Ok(completions)
13209 })
13210 })
13211 }
13212
13213 fn resolve_completions(
13214 &self,
13215 buffer: Model<Buffer>,
13216 completion_indices: Vec<usize>,
13217 completions: Arc<RwLock<Box<[Completion]>>>,
13218 cx: &mut ViewContext<Editor>,
13219 ) -> Task<Result<bool>> {
13220 self.update(cx, |project, cx| {
13221 project.resolve_completions(buffer, completion_indices, completions, cx)
13222 })
13223 }
13224
13225 fn apply_additional_edits_for_completion(
13226 &self,
13227 buffer: Model<Buffer>,
13228 completion: Completion,
13229 push_to_history: bool,
13230 cx: &mut ViewContext<Editor>,
13231 ) -> Task<Result<Option<language::Transaction>>> {
13232 self.update(cx, |project, cx| {
13233 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13234 })
13235 }
13236
13237 fn is_completion_trigger(
13238 &self,
13239 buffer: &Model<Buffer>,
13240 position: language::Anchor,
13241 text: &str,
13242 trigger_in_words: bool,
13243 cx: &mut ViewContext<Editor>,
13244 ) -> bool {
13245 if !EditorSettings::get_global(cx).show_completions_on_input {
13246 return false;
13247 }
13248
13249 let mut chars = text.chars();
13250 let char = if let Some(char) = chars.next() {
13251 char
13252 } else {
13253 return false;
13254 };
13255 if chars.next().is_some() {
13256 return false;
13257 }
13258
13259 let buffer = buffer.read(cx);
13260 let classifier = buffer
13261 .snapshot()
13262 .char_classifier_at(position)
13263 .for_completion(true);
13264 if trigger_in_words && classifier.is_word(char) {
13265 return true;
13266 }
13267
13268 buffer
13269 .completion_triggers()
13270 .iter()
13271 .any(|string| string == text)
13272 }
13273}
13274
13275impl SemanticsProvider for Model<Project> {
13276 fn hover(
13277 &self,
13278 buffer: &Model<Buffer>,
13279 position: text::Anchor,
13280 cx: &mut AppContext,
13281 ) -> Option<Task<Vec<project::Hover>>> {
13282 Some(self.update(cx, |project, cx| project.hover(buffer, position, cx)))
13283 }
13284
13285 fn document_highlights(
13286 &self,
13287 buffer: &Model<Buffer>,
13288 position: text::Anchor,
13289 cx: &mut AppContext,
13290 ) -> Option<Task<Result<Vec<DocumentHighlight>>>> {
13291 Some(self.update(cx, |project, cx| {
13292 project.document_highlights(buffer, position, cx)
13293 }))
13294 }
13295
13296 fn definitions(
13297 &self,
13298 buffer: &Model<Buffer>,
13299 position: text::Anchor,
13300 kind: GotoDefinitionKind,
13301 cx: &mut AppContext,
13302 ) -> Option<Task<Result<Vec<LocationLink>>>> {
13303 Some(self.update(cx, |project, cx| match kind {
13304 GotoDefinitionKind::Symbol => project.definition(&buffer, position, cx),
13305 GotoDefinitionKind::Declaration => project.declaration(&buffer, position, cx),
13306 GotoDefinitionKind::Type => project.type_definition(&buffer, position, cx),
13307 GotoDefinitionKind::Implementation => project.implementation(&buffer, position, cx),
13308 }))
13309 }
13310
13311 fn supports_inlay_hints(&self, buffer: &Model<Buffer>, cx: &AppContext) -> bool {
13312 // TODO: make this work for remote projects
13313 self.read(cx)
13314 .language_servers_for_buffer(buffer.read(cx), cx)
13315 .any(
13316 |(_, server)| match server.capabilities().inlay_hint_provider {
13317 Some(lsp::OneOf::Left(enabled)) => enabled,
13318 Some(lsp::OneOf::Right(_)) => true,
13319 None => false,
13320 },
13321 )
13322 }
13323
13324 fn inlay_hints(
13325 &self,
13326 buffer_handle: Model<Buffer>,
13327 range: Range<text::Anchor>,
13328 cx: &mut AppContext,
13329 ) -> Option<Task<anyhow::Result<Vec<InlayHint>>>> {
13330 Some(self.update(cx, |project, cx| {
13331 project.inlay_hints(buffer_handle, range, cx)
13332 }))
13333 }
13334
13335 fn resolve_inlay_hint(
13336 &self,
13337 hint: InlayHint,
13338 buffer_handle: Model<Buffer>,
13339 server_id: LanguageServerId,
13340 cx: &mut AppContext,
13341 ) -> Option<Task<anyhow::Result<InlayHint>>> {
13342 Some(self.update(cx, |project, cx| {
13343 project.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
13344 }))
13345 }
13346
13347 fn range_for_rename(
13348 &self,
13349 buffer: &Model<Buffer>,
13350 position: text::Anchor,
13351 cx: &mut AppContext,
13352 ) -> Option<Task<Result<Option<Range<text::Anchor>>>>> {
13353 Some(self.update(cx, |project, cx| {
13354 project.prepare_rename(buffer.clone(), position, cx)
13355 }))
13356 }
13357
13358 fn perform_rename(
13359 &self,
13360 buffer: &Model<Buffer>,
13361 position: text::Anchor,
13362 new_name: String,
13363 cx: &mut AppContext,
13364 ) -> Option<Task<Result<ProjectTransaction>>> {
13365 Some(self.update(cx, |project, cx| {
13366 project.perform_rename(buffer.clone(), position, new_name, cx)
13367 }))
13368 }
13369}
13370
13371fn inlay_hint_settings(
13372 location: Anchor,
13373 snapshot: &MultiBufferSnapshot,
13374 cx: &mut ViewContext<'_, Editor>,
13375) -> InlayHintSettings {
13376 let file = snapshot.file_at(location);
13377 let language = snapshot.language_at(location);
13378 let settings = all_language_settings(file, cx);
13379 settings
13380 .language(language.map(|l| l.name()).as_ref())
13381 .inlay_hints
13382}
13383
13384fn consume_contiguous_rows(
13385 contiguous_row_selections: &mut Vec<Selection<Point>>,
13386 selection: &Selection<Point>,
13387 display_map: &DisplaySnapshot,
13388 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13389) -> (MultiBufferRow, MultiBufferRow) {
13390 contiguous_row_selections.push(selection.clone());
13391 let start_row = MultiBufferRow(selection.start.row);
13392 let mut end_row = ending_row(selection, display_map);
13393
13394 while let Some(next_selection) = selections.peek() {
13395 if next_selection.start.row <= end_row.0 {
13396 end_row = ending_row(next_selection, display_map);
13397 contiguous_row_selections.push(selections.next().unwrap().clone());
13398 } else {
13399 break;
13400 }
13401 }
13402 (start_row, end_row)
13403}
13404
13405fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13406 if next_selection.end.column > 0 || next_selection.is_empty() {
13407 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13408 } else {
13409 MultiBufferRow(next_selection.end.row)
13410 }
13411}
13412
13413impl EditorSnapshot {
13414 pub fn remote_selections_in_range<'a>(
13415 &'a self,
13416 range: &'a Range<Anchor>,
13417 collaboration_hub: &dyn CollaborationHub,
13418 cx: &'a AppContext,
13419 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13420 let participant_names = collaboration_hub.user_names(cx);
13421 let participant_indices = collaboration_hub.user_participant_indices(cx);
13422 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13423 let collaborators_by_replica_id = collaborators_by_peer_id
13424 .iter()
13425 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13426 .collect::<HashMap<_, _>>();
13427 self.buffer_snapshot
13428 .selections_in_range(range, false)
13429 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13430 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13431 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13432 let user_name = participant_names.get(&collaborator.user_id).cloned();
13433 Some(RemoteSelection {
13434 replica_id,
13435 selection,
13436 cursor_shape,
13437 line_mode,
13438 participant_index,
13439 peer_id: collaborator.peer_id,
13440 user_name,
13441 })
13442 })
13443 }
13444
13445 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13446 self.display_snapshot.buffer_snapshot.language_at(position)
13447 }
13448
13449 pub fn is_focused(&self) -> bool {
13450 self.is_focused
13451 }
13452
13453 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13454 self.placeholder_text.as_ref()
13455 }
13456
13457 pub fn scroll_position(&self) -> gpui::Point<f32> {
13458 self.scroll_anchor.scroll_position(&self.display_snapshot)
13459 }
13460
13461 fn gutter_dimensions(
13462 &self,
13463 font_id: FontId,
13464 font_size: Pixels,
13465 em_width: Pixels,
13466 em_advance: Pixels,
13467 max_line_number_width: Pixels,
13468 cx: &AppContext,
13469 ) -> GutterDimensions {
13470 if !self.show_gutter {
13471 return GutterDimensions::default();
13472 }
13473 let descent = cx.text_system().descent(font_id, font_size);
13474
13475 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13476 matches!(
13477 ProjectSettings::get_global(cx).git.git_gutter,
13478 Some(GitGutterSetting::TrackedFiles)
13479 )
13480 });
13481 let gutter_settings = EditorSettings::get_global(cx).gutter;
13482 let show_line_numbers = self
13483 .show_line_numbers
13484 .unwrap_or(gutter_settings.line_numbers);
13485 let line_gutter_width = if show_line_numbers {
13486 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13487 let min_width_for_number_on_gutter = em_advance * 4.0;
13488 max_line_number_width.max(min_width_for_number_on_gutter)
13489 } else {
13490 0.0.into()
13491 };
13492
13493 let show_code_actions = self
13494 .show_code_actions
13495 .unwrap_or(gutter_settings.code_actions);
13496
13497 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13498
13499 let git_blame_entries_width =
13500 self.git_blame_gutter_max_author_length
13501 .map(|max_author_length| {
13502 // Length of the author name, but also space for the commit hash,
13503 // the spacing and the timestamp.
13504 let max_char_count = max_author_length
13505 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13506 + 7 // length of commit sha
13507 + 14 // length of max relative timestamp ("60 minutes ago")
13508 + 4; // gaps and margins
13509
13510 em_advance * max_char_count
13511 });
13512
13513 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13514 left_padding += if show_code_actions || show_runnables {
13515 em_width * 3.0
13516 } else if show_git_gutter && show_line_numbers {
13517 em_width * 2.0
13518 } else if show_git_gutter || show_line_numbers {
13519 em_width
13520 } else {
13521 px(0.)
13522 };
13523
13524 let right_padding = if gutter_settings.folds && show_line_numbers {
13525 em_width * 4.0
13526 } else if gutter_settings.folds {
13527 em_width * 3.0
13528 } else if show_line_numbers {
13529 em_width
13530 } else {
13531 px(0.)
13532 };
13533
13534 GutterDimensions {
13535 left_padding,
13536 right_padding,
13537 width: line_gutter_width + left_padding + right_padding,
13538 margin: -descent,
13539 git_blame_entries_width,
13540 }
13541 }
13542
13543 pub fn render_fold_toggle(
13544 &self,
13545 buffer_row: MultiBufferRow,
13546 row_contains_cursor: bool,
13547 editor: View<Editor>,
13548 cx: &mut WindowContext,
13549 ) -> Option<AnyElement> {
13550 let folded = self.is_line_folded(buffer_row);
13551
13552 if let Some(crease) = self
13553 .crease_snapshot
13554 .query_row(buffer_row, &self.buffer_snapshot)
13555 {
13556 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13557 if folded {
13558 editor.update(cx, |editor, cx| {
13559 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13560 });
13561 } else {
13562 editor.update(cx, |editor, cx| {
13563 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13564 });
13565 }
13566 });
13567
13568 Some((crease.render_toggle)(
13569 buffer_row,
13570 folded,
13571 toggle_callback,
13572 cx,
13573 ))
13574 } else if folded
13575 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13576 {
13577 Some(
13578 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13579 .selected(folded)
13580 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13581 if folded {
13582 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13583 } else {
13584 this.fold_at(&FoldAt { buffer_row }, cx);
13585 }
13586 }))
13587 .into_any_element(),
13588 )
13589 } else {
13590 None
13591 }
13592 }
13593
13594 pub fn render_crease_trailer(
13595 &self,
13596 buffer_row: MultiBufferRow,
13597 cx: &mut WindowContext,
13598 ) -> Option<AnyElement> {
13599 let folded = self.is_line_folded(buffer_row);
13600 let crease = self
13601 .crease_snapshot
13602 .query_row(buffer_row, &self.buffer_snapshot)?;
13603 Some((crease.render_trailer)(buffer_row, folded, cx))
13604 }
13605}
13606
13607impl Deref for EditorSnapshot {
13608 type Target = DisplaySnapshot;
13609
13610 fn deref(&self) -> &Self::Target {
13611 &self.display_snapshot
13612 }
13613}
13614
13615#[derive(Clone, Debug, PartialEq, Eq)]
13616pub enum EditorEvent {
13617 InputIgnored {
13618 text: Arc<str>,
13619 },
13620 InputHandled {
13621 utf16_range_to_replace: Option<Range<isize>>,
13622 text: Arc<str>,
13623 },
13624 ExcerptsAdded {
13625 buffer: Model<Buffer>,
13626 predecessor: ExcerptId,
13627 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13628 },
13629 ExcerptsRemoved {
13630 ids: Vec<ExcerptId>,
13631 },
13632 ExcerptsEdited {
13633 ids: Vec<ExcerptId>,
13634 },
13635 ExcerptsExpanded {
13636 ids: Vec<ExcerptId>,
13637 },
13638 BufferEdited,
13639 Edited {
13640 transaction_id: clock::Lamport,
13641 },
13642 Reparsed(BufferId),
13643 Focused,
13644 FocusedIn,
13645 Blurred,
13646 DirtyChanged,
13647 Saved,
13648 TitleChanged,
13649 DiffBaseChanged,
13650 SelectionsChanged {
13651 local: bool,
13652 },
13653 ScrollPositionChanged {
13654 local: bool,
13655 autoscroll: bool,
13656 },
13657 Closed,
13658 TransactionUndone {
13659 transaction_id: clock::Lamport,
13660 },
13661 TransactionBegun {
13662 transaction_id: clock::Lamport,
13663 },
13664 Reloaded,
13665 CursorShapeChanged,
13666}
13667
13668impl EventEmitter<EditorEvent> for Editor {}
13669
13670impl FocusableView for Editor {
13671 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13672 self.focus_handle.clone()
13673 }
13674}
13675
13676impl Render for Editor {
13677 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13678 let settings = ThemeSettings::get_global(cx);
13679
13680 let text_style = match self.mode {
13681 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13682 color: cx.theme().colors().editor_foreground,
13683 font_family: settings.ui_font.family.clone(),
13684 font_features: settings.ui_font.features.clone(),
13685 font_fallbacks: settings.ui_font.fallbacks.clone(),
13686 font_size: rems(0.875).into(),
13687 font_weight: settings.ui_font.weight,
13688 line_height: relative(settings.buffer_line_height.value()),
13689 ..Default::default()
13690 },
13691 EditorMode::Full => TextStyle {
13692 color: cx.theme().colors().editor_foreground,
13693 font_family: settings.buffer_font.family.clone(),
13694 font_features: settings.buffer_font.features.clone(),
13695 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13696 font_size: settings.buffer_font_size(cx).into(),
13697 font_weight: settings.buffer_font.weight,
13698 line_height: relative(settings.buffer_line_height.value()),
13699 ..Default::default()
13700 },
13701 };
13702
13703 let background = match self.mode {
13704 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13705 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13706 EditorMode::Full => cx.theme().colors().editor_background,
13707 };
13708
13709 EditorElement::new(
13710 cx.view(),
13711 EditorStyle {
13712 background,
13713 local_player: cx.theme().players().local(),
13714 text: text_style,
13715 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13716 syntax: cx.theme().syntax().clone(),
13717 status: cx.theme().status().clone(),
13718 inlay_hints_style: make_inlay_hints_style(cx),
13719 suggestions_style: HighlightStyle {
13720 color: Some(cx.theme().status().predictive),
13721 ..HighlightStyle::default()
13722 },
13723 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13724 },
13725 )
13726 }
13727}
13728
13729impl ViewInputHandler for Editor {
13730 fn text_for_range(
13731 &mut self,
13732 range_utf16: Range<usize>,
13733 cx: &mut ViewContext<Self>,
13734 ) -> Option<String> {
13735 Some(
13736 self.buffer
13737 .read(cx)
13738 .read(cx)
13739 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13740 .collect(),
13741 )
13742 }
13743
13744 fn selected_text_range(
13745 &mut self,
13746 ignore_disabled_input: bool,
13747 cx: &mut ViewContext<Self>,
13748 ) -> Option<UTF16Selection> {
13749 // Prevent the IME menu from appearing when holding down an alphabetic key
13750 // while input is disabled.
13751 if !ignore_disabled_input && !self.input_enabled {
13752 return None;
13753 }
13754
13755 let selection = self.selections.newest::<OffsetUtf16>(cx);
13756 let range = selection.range();
13757
13758 Some(UTF16Selection {
13759 range: range.start.0..range.end.0,
13760 reversed: selection.reversed,
13761 })
13762 }
13763
13764 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13765 let snapshot = self.buffer.read(cx).read(cx);
13766 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13767 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13768 }
13769
13770 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13771 self.clear_highlights::<InputComposition>(cx);
13772 self.ime_transaction.take();
13773 }
13774
13775 fn replace_text_in_range(
13776 &mut self,
13777 range_utf16: Option<Range<usize>>,
13778 text: &str,
13779 cx: &mut ViewContext<Self>,
13780 ) {
13781 if !self.input_enabled {
13782 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13783 return;
13784 }
13785
13786 self.transact(cx, |this, cx| {
13787 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13788 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13789 Some(this.selection_replacement_ranges(range_utf16, cx))
13790 } else {
13791 this.marked_text_ranges(cx)
13792 };
13793
13794 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13795 let newest_selection_id = this.selections.newest_anchor().id;
13796 this.selections
13797 .all::<OffsetUtf16>(cx)
13798 .iter()
13799 .zip(ranges_to_replace.iter())
13800 .find_map(|(selection, range)| {
13801 if selection.id == newest_selection_id {
13802 Some(
13803 (range.start.0 as isize - selection.head().0 as isize)
13804 ..(range.end.0 as isize - selection.head().0 as isize),
13805 )
13806 } else {
13807 None
13808 }
13809 })
13810 });
13811
13812 cx.emit(EditorEvent::InputHandled {
13813 utf16_range_to_replace: range_to_replace,
13814 text: text.into(),
13815 });
13816
13817 if let Some(new_selected_ranges) = new_selected_ranges {
13818 this.change_selections(None, cx, |selections| {
13819 selections.select_ranges(new_selected_ranges)
13820 });
13821 this.backspace(&Default::default(), cx);
13822 }
13823
13824 this.handle_input(text, cx);
13825 });
13826
13827 if let Some(transaction) = self.ime_transaction {
13828 self.buffer.update(cx, |buffer, cx| {
13829 buffer.group_until_transaction(transaction, cx);
13830 });
13831 }
13832
13833 self.unmark_text(cx);
13834 }
13835
13836 fn replace_and_mark_text_in_range(
13837 &mut self,
13838 range_utf16: Option<Range<usize>>,
13839 text: &str,
13840 new_selected_range_utf16: Option<Range<usize>>,
13841 cx: &mut ViewContext<Self>,
13842 ) {
13843 if !self.input_enabled {
13844 return;
13845 }
13846
13847 let transaction = self.transact(cx, |this, cx| {
13848 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13849 let snapshot = this.buffer.read(cx).read(cx);
13850 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13851 for marked_range in &mut marked_ranges {
13852 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13853 marked_range.start.0 += relative_range_utf16.start;
13854 marked_range.start =
13855 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13856 marked_range.end =
13857 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13858 }
13859 }
13860 Some(marked_ranges)
13861 } else if let Some(range_utf16) = range_utf16 {
13862 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13863 Some(this.selection_replacement_ranges(range_utf16, cx))
13864 } else {
13865 None
13866 };
13867
13868 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13869 let newest_selection_id = this.selections.newest_anchor().id;
13870 this.selections
13871 .all::<OffsetUtf16>(cx)
13872 .iter()
13873 .zip(ranges_to_replace.iter())
13874 .find_map(|(selection, range)| {
13875 if selection.id == newest_selection_id {
13876 Some(
13877 (range.start.0 as isize - selection.head().0 as isize)
13878 ..(range.end.0 as isize - selection.head().0 as isize),
13879 )
13880 } else {
13881 None
13882 }
13883 })
13884 });
13885
13886 cx.emit(EditorEvent::InputHandled {
13887 utf16_range_to_replace: range_to_replace,
13888 text: text.into(),
13889 });
13890
13891 if let Some(ranges) = ranges_to_replace {
13892 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13893 }
13894
13895 let marked_ranges = {
13896 let snapshot = this.buffer.read(cx).read(cx);
13897 this.selections
13898 .disjoint_anchors()
13899 .iter()
13900 .map(|selection| {
13901 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13902 })
13903 .collect::<Vec<_>>()
13904 };
13905
13906 if text.is_empty() {
13907 this.unmark_text(cx);
13908 } else {
13909 this.highlight_text::<InputComposition>(
13910 marked_ranges.clone(),
13911 HighlightStyle {
13912 underline: Some(UnderlineStyle {
13913 thickness: px(1.),
13914 color: None,
13915 wavy: false,
13916 }),
13917 ..Default::default()
13918 },
13919 cx,
13920 );
13921 }
13922
13923 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13924 let use_autoclose = this.use_autoclose;
13925 let use_auto_surround = this.use_auto_surround;
13926 this.set_use_autoclose(false);
13927 this.set_use_auto_surround(false);
13928 this.handle_input(text, cx);
13929 this.set_use_autoclose(use_autoclose);
13930 this.set_use_auto_surround(use_auto_surround);
13931
13932 if let Some(new_selected_range) = new_selected_range_utf16 {
13933 let snapshot = this.buffer.read(cx).read(cx);
13934 let new_selected_ranges = marked_ranges
13935 .into_iter()
13936 .map(|marked_range| {
13937 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13938 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13939 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13940 snapshot.clip_offset_utf16(new_start, Bias::Left)
13941 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13942 })
13943 .collect::<Vec<_>>();
13944
13945 drop(snapshot);
13946 this.change_selections(None, cx, |selections| {
13947 selections.select_ranges(new_selected_ranges)
13948 });
13949 }
13950 });
13951
13952 self.ime_transaction = self.ime_transaction.or(transaction);
13953 if let Some(transaction) = self.ime_transaction {
13954 self.buffer.update(cx, |buffer, cx| {
13955 buffer.group_until_transaction(transaction, cx);
13956 });
13957 }
13958
13959 if self.text_highlights::<InputComposition>(cx).is_none() {
13960 self.ime_transaction.take();
13961 }
13962 }
13963
13964 fn bounds_for_range(
13965 &mut self,
13966 range_utf16: Range<usize>,
13967 element_bounds: gpui::Bounds<Pixels>,
13968 cx: &mut ViewContext<Self>,
13969 ) -> Option<gpui::Bounds<Pixels>> {
13970 let text_layout_details = self.text_layout_details(cx);
13971 let style = &text_layout_details.editor_style;
13972 let font_id = cx.text_system().resolve_font(&style.text.font());
13973 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13974 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13975
13976 let em_width = cx
13977 .text_system()
13978 .typographic_bounds(font_id, font_size, 'm')
13979 .unwrap()
13980 .size
13981 .width;
13982
13983 let snapshot = self.snapshot(cx);
13984 let scroll_position = snapshot.scroll_position();
13985 let scroll_left = scroll_position.x * em_width;
13986
13987 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13988 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13989 + self.gutter_dimensions.width;
13990 let y = line_height * (start.row().as_f32() - scroll_position.y);
13991
13992 Some(Bounds {
13993 origin: element_bounds.origin + point(x, y),
13994 size: size(em_width, line_height),
13995 })
13996 }
13997}
13998
13999trait SelectionExt {
14000 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
14001 fn spanned_rows(
14002 &self,
14003 include_end_if_at_line_start: bool,
14004 map: &DisplaySnapshot,
14005 ) -> Range<MultiBufferRow>;
14006}
14007
14008impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
14009 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
14010 let start = self
14011 .start
14012 .to_point(&map.buffer_snapshot)
14013 .to_display_point(map);
14014 let end = self
14015 .end
14016 .to_point(&map.buffer_snapshot)
14017 .to_display_point(map);
14018 if self.reversed {
14019 end..start
14020 } else {
14021 start..end
14022 }
14023 }
14024
14025 fn spanned_rows(
14026 &self,
14027 include_end_if_at_line_start: bool,
14028 map: &DisplaySnapshot,
14029 ) -> Range<MultiBufferRow> {
14030 let start = self.start.to_point(&map.buffer_snapshot);
14031 let mut end = self.end.to_point(&map.buffer_snapshot);
14032 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
14033 end.row -= 1;
14034 }
14035
14036 let buffer_start = map.prev_line_boundary(start).0;
14037 let buffer_end = map.next_line_boundary(end).0;
14038 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
14039 }
14040}
14041
14042impl<T: InvalidationRegion> InvalidationStack<T> {
14043 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
14044 where
14045 S: Clone + ToOffset,
14046 {
14047 while let Some(region) = self.last() {
14048 let all_selections_inside_invalidation_ranges =
14049 if selections.len() == region.ranges().len() {
14050 selections
14051 .iter()
14052 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
14053 .all(|(selection, invalidation_range)| {
14054 let head = selection.head().to_offset(buffer);
14055 invalidation_range.start <= head && invalidation_range.end >= head
14056 })
14057 } else {
14058 false
14059 };
14060
14061 if all_selections_inside_invalidation_ranges {
14062 break;
14063 } else {
14064 self.pop();
14065 }
14066 }
14067 }
14068}
14069
14070impl<T> Default for InvalidationStack<T> {
14071 fn default() -> Self {
14072 Self(Default::default())
14073 }
14074}
14075
14076impl<T> Deref for InvalidationStack<T> {
14077 type Target = Vec<T>;
14078
14079 fn deref(&self) -> &Self::Target {
14080 &self.0
14081 }
14082}
14083
14084impl<T> DerefMut for InvalidationStack<T> {
14085 fn deref_mut(&mut self) -> &mut Self::Target {
14086 &mut self.0
14087 }
14088}
14089
14090impl InvalidationRegion for SnippetState {
14091 fn ranges(&self) -> &[Range<Anchor>] {
14092 &self.ranges[self.active_index]
14093 }
14094}
14095
14096pub fn diagnostic_block_renderer(
14097 diagnostic: Diagnostic,
14098 max_message_rows: Option<u8>,
14099 allow_closing: bool,
14100 _is_valid: bool,
14101) -> RenderBlock {
14102 let (text_without_backticks, code_ranges) =
14103 highlight_diagnostic_message(&diagnostic, max_message_rows);
14104
14105 Box::new(move |cx: &mut BlockContext| {
14106 let group_id: SharedString = cx.block_id.to_string().into();
14107
14108 let mut text_style = cx.text_style().clone();
14109 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
14110 let theme_settings = ThemeSettings::get_global(cx);
14111 text_style.font_family = theme_settings.buffer_font.family.clone();
14112 text_style.font_style = theme_settings.buffer_font.style;
14113 text_style.font_features = theme_settings.buffer_font.features.clone();
14114 text_style.font_weight = theme_settings.buffer_font.weight;
14115
14116 let multi_line_diagnostic = diagnostic.message.contains('\n');
14117
14118 let buttons = |diagnostic: &Diagnostic| {
14119 if multi_line_diagnostic {
14120 v_flex()
14121 } else {
14122 h_flex()
14123 }
14124 .when(allow_closing, |div| {
14125 div.children(diagnostic.is_primary.then(|| {
14126 IconButton::new("close-block", IconName::XCircle)
14127 .icon_color(Color::Muted)
14128 .size(ButtonSize::Compact)
14129 .style(ButtonStyle::Transparent)
14130 .visible_on_hover(group_id.clone())
14131 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
14132 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
14133 }))
14134 })
14135 .child(
14136 IconButton::new("copy-block", IconName::Copy)
14137 .icon_color(Color::Muted)
14138 .size(ButtonSize::Compact)
14139 .style(ButtonStyle::Transparent)
14140 .visible_on_hover(group_id.clone())
14141 .on_click({
14142 let message = diagnostic.message.clone();
14143 move |_click, cx| {
14144 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
14145 }
14146 })
14147 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
14148 )
14149 };
14150
14151 let icon_size = buttons(&diagnostic)
14152 .into_any_element()
14153 .layout_as_root(AvailableSpace::min_size(), cx);
14154
14155 h_flex()
14156 .id(cx.block_id)
14157 .group(group_id.clone())
14158 .relative()
14159 .size_full()
14160 .pl(cx.gutter_dimensions.width)
14161 .w(cx.max_width + cx.gutter_dimensions.width)
14162 .child(
14163 div()
14164 .flex()
14165 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
14166 .flex_shrink(),
14167 )
14168 .child(buttons(&diagnostic))
14169 .child(div().flex().flex_shrink_0().child(
14170 StyledText::new(text_without_backticks.clone()).with_highlights(
14171 &text_style,
14172 code_ranges.iter().map(|range| {
14173 (
14174 range.clone(),
14175 HighlightStyle {
14176 font_weight: Some(FontWeight::BOLD),
14177 ..Default::default()
14178 },
14179 )
14180 }),
14181 ),
14182 ))
14183 .into_any_element()
14184 })
14185}
14186
14187pub fn highlight_diagnostic_message(
14188 diagnostic: &Diagnostic,
14189 mut max_message_rows: Option<u8>,
14190) -> (SharedString, Vec<Range<usize>>) {
14191 let mut text_without_backticks = String::new();
14192 let mut code_ranges = Vec::new();
14193
14194 if let Some(source) = &diagnostic.source {
14195 text_without_backticks.push_str(source);
14196 code_ranges.push(0..source.len());
14197 text_without_backticks.push_str(": ");
14198 }
14199
14200 let mut prev_offset = 0;
14201 let mut in_code_block = false;
14202 let has_row_limit = max_message_rows.is_some();
14203 let mut newline_indices = diagnostic
14204 .message
14205 .match_indices('\n')
14206 .filter(|_| has_row_limit)
14207 .map(|(ix, _)| ix)
14208 .fuse()
14209 .peekable();
14210
14211 for (quote_ix, _) in diagnostic
14212 .message
14213 .match_indices('`')
14214 .chain([(diagnostic.message.len(), "")])
14215 {
14216 let mut first_newline_ix = None;
14217 let mut last_newline_ix = None;
14218 while let Some(newline_ix) = newline_indices.peek() {
14219 if *newline_ix < quote_ix {
14220 if first_newline_ix.is_none() {
14221 first_newline_ix = Some(*newline_ix);
14222 }
14223 last_newline_ix = Some(*newline_ix);
14224
14225 if let Some(rows_left) = &mut max_message_rows {
14226 if *rows_left == 0 {
14227 break;
14228 } else {
14229 *rows_left -= 1;
14230 }
14231 }
14232 let _ = newline_indices.next();
14233 } else {
14234 break;
14235 }
14236 }
14237 let prev_len = text_without_backticks.len();
14238 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14239 text_without_backticks.push_str(new_text);
14240 if in_code_block {
14241 code_ranges.push(prev_len..text_without_backticks.len());
14242 }
14243 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14244 in_code_block = !in_code_block;
14245 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14246 text_without_backticks.push_str("...");
14247 break;
14248 }
14249 }
14250
14251 (text_without_backticks.into(), code_ranges)
14252}
14253
14254fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14255 match severity {
14256 DiagnosticSeverity::ERROR => colors.error,
14257 DiagnosticSeverity::WARNING => colors.warning,
14258 DiagnosticSeverity::INFORMATION => colors.info,
14259 DiagnosticSeverity::HINT => colors.info,
14260 _ => colors.ignored,
14261 }
14262}
14263
14264pub fn styled_runs_for_code_label<'a>(
14265 label: &'a CodeLabel,
14266 syntax_theme: &'a theme::SyntaxTheme,
14267) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14268 let fade_out = HighlightStyle {
14269 fade_out: Some(0.35),
14270 ..Default::default()
14271 };
14272
14273 let mut prev_end = label.filter_range.end;
14274 label
14275 .runs
14276 .iter()
14277 .enumerate()
14278 .flat_map(move |(ix, (range, highlight_id))| {
14279 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14280 style
14281 } else {
14282 return Default::default();
14283 };
14284 let mut muted_style = style;
14285 muted_style.highlight(fade_out);
14286
14287 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14288 if range.start >= label.filter_range.end {
14289 if range.start > prev_end {
14290 runs.push((prev_end..range.start, fade_out));
14291 }
14292 runs.push((range.clone(), muted_style));
14293 } else if range.end <= label.filter_range.end {
14294 runs.push((range.clone(), style));
14295 } else {
14296 runs.push((range.start..label.filter_range.end, style));
14297 runs.push((label.filter_range.end..range.end, muted_style));
14298 }
14299 prev_end = cmp::max(prev_end, range.end);
14300
14301 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14302 runs.push((prev_end..label.text.len(), fade_out));
14303 }
14304
14305 runs
14306 })
14307}
14308
14309pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14310 let mut prev_index = 0;
14311 let mut prev_codepoint: Option<char> = None;
14312 text.char_indices()
14313 .chain([(text.len(), '\0')])
14314 .filter_map(move |(index, codepoint)| {
14315 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14316 let is_boundary = index == text.len()
14317 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14318 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14319 if is_boundary {
14320 let chunk = &text[prev_index..index];
14321 prev_index = index;
14322 Some(chunk)
14323 } else {
14324 None
14325 }
14326 })
14327}
14328
14329pub trait RangeToAnchorExt: Sized {
14330 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14331
14332 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14333 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14334 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14335 }
14336}
14337
14338impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14339 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14340 let start_offset = self.start.to_offset(snapshot);
14341 let end_offset = self.end.to_offset(snapshot);
14342 if start_offset == end_offset {
14343 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14344 } else {
14345 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14346 }
14347 }
14348}
14349
14350pub trait RowExt {
14351 fn as_f32(&self) -> f32;
14352
14353 fn next_row(&self) -> Self;
14354
14355 fn previous_row(&self) -> Self;
14356
14357 fn minus(&self, other: Self) -> u32;
14358}
14359
14360impl RowExt for DisplayRow {
14361 fn as_f32(&self) -> f32 {
14362 self.0 as f32
14363 }
14364
14365 fn next_row(&self) -> Self {
14366 Self(self.0 + 1)
14367 }
14368
14369 fn previous_row(&self) -> Self {
14370 Self(self.0.saturating_sub(1))
14371 }
14372
14373 fn minus(&self, other: Self) -> u32 {
14374 self.0 - other.0
14375 }
14376}
14377
14378impl RowExt for MultiBufferRow {
14379 fn as_f32(&self) -> f32 {
14380 self.0 as f32
14381 }
14382
14383 fn next_row(&self) -> Self {
14384 Self(self.0 + 1)
14385 }
14386
14387 fn previous_row(&self) -> Self {
14388 Self(self.0.saturating_sub(1))
14389 }
14390
14391 fn minus(&self, other: Self) -> u32 {
14392 self.0 - other.0
14393 }
14394}
14395
14396trait RowRangeExt {
14397 type Row;
14398
14399 fn len(&self) -> usize;
14400
14401 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14402}
14403
14404impl RowRangeExt for Range<MultiBufferRow> {
14405 type Row = MultiBufferRow;
14406
14407 fn len(&self) -> usize {
14408 (self.end.0 - self.start.0) as usize
14409 }
14410
14411 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14412 (self.start.0..self.end.0).map(MultiBufferRow)
14413 }
14414}
14415
14416impl RowRangeExt for Range<DisplayRow> {
14417 type Row = DisplayRow;
14418
14419 fn len(&self) -> usize {
14420 (self.end.0 - self.start.0) as usize
14421 }
14422
14423 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14424 (self.start.0..self.end.0).map(DisplayRow)
14425 }
14426}
14427
14428fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14429 if hunk.diff_base_byte_range.is_empty() {
14430 DiffHunkStatus::Added
14431 } else if hunk.row_range.is_empty() {
14432 DiffHunkStatus::Removed
14433 } else {
14434 DiffHunkStatus::Modified
14435 }
14436}
14437
14438/// If select range has more than one line, we
14439/// just point the cursor to range.start.
14440fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14441 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14442 range
14443 } else {
14444 range.start..range.start
14445 }
14446}