1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31mod inline_completion_provider;
32pub mod items;
33mod linked_editing_ranges;
34mod lsp_ext;
35mod mouse_context_menu;
36pub mod movement;
37mod persistence;
38mod proposed_changes_editor;
39mod rust_analyzer_ext;
40pub mod scroll;
41mod selections_collection;
42pub mod tasks;
43
44#[cfg(test)]
45mod editor_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50use ::git::diff::DiffHunkStatus;
51use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
52pub(crate) use actions::*;
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use debounced_delay::DebouncedDelay;
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings, ShowScrollbar,
65};
66pub use editor_settings_controls::*;
67use element::LineWithInvisibles;
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use futures::{future, FutureExt};
72use fuzzy::{StringMatch, StringMatchCandidate};
73use git::blame::GitBlame;
74use gpui::{
75 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
76 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
77 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
78 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
79 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
80 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
81 UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
82 VisualContext, WeakFocusHandle, WeakView, WindowContext,
83};
84use highlight_matching_bracket::refresh_matching_bracket_highlights;
85use hover_popover::{hide_hover, HoverState};
86pub(crate) use hunk_diff::HoveredHunk;
87use hunk_diff::{diff_hunk_to_display, ExpandedHunks};
88use indent_guides::ActiveIndentGuidesState;
89use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
90pub use inline_completion_provider::*;
91pub use items::MAX_TAB_TITLE_LEN;
92use itertools::Itertools;
93use language::{
94 language_settings::{self, all_language_settings, InlayHintSettings},
95 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
96 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
97 Point, Selection, SelectionGoal, TransactionId,
98};
99use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
100use linked_editing_ranges::refresh_linked_ranges;
101pub use proposed_changes_editor::{
102 ProposedChangesBuffer, ProposedChangesEditor, ProposedChangesEditorToolbar,
103};
104use similar::{ChangeTag, TextDiff};
105use task::{ResolvedTask, TaskTemplate, TaskVariables};
106
107use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
108pub use lsp::CompletionContext;
109use lsp::{
110 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
111 LanguageServerId,
112};
113use mouse_context_menu::MouseContextMenu;
114use movement::TextLayoutDetails;
115pub use multi_buffer::{
116 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
117 ToPoint,
118};
119use multi_buffer::{
120 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
121};
122use ordered_float::OrderedFloat;
123use parking_lot::{Mutex, RwLock};
124use project::project_settings::{GitGutterSetting, ProjectSettings};
125use project::{
126 lsp_store::FormatTrigger, CodeAction, Completion, CompletionIntent, Item, Location, Project,
127 ProjectPath, ProjectTransaction, TaskSourceKind,
128};
129use rand::prelude::*;
130use rpc::{proto::*, ErrorExt};
131use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
132use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
133use serde::{Deserialize, Serialize};
134use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
135use smallvec::SmallVec;
136use snippet::Snippet;
137use std::{
138 any::TypeId,
139 borrow::Cow,
140 cell::RefCell,
141 cmp::{self, Ordering, Reverse},
142 mem,
143 num::NonZeroU32,
144 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
145 path::{Path, PathBuf},
146 rc::Rc,
147 sync::Arc,
148 time::{Duration, Instant},
149};
150pub use sum_tree::Bias;
151use sum_tree::TreeMap;
152use text::{BufferId, OffsetUtf16, Rope};
153use theme::{
154 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
155 ThemeColors, ThemeSettings,
156};
157use ui::{
158 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
159 ListItem, Popover, PopoverMenuHandle, Tooltip,
160};
161use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
162use workspace::item::{ItemHandle, PreviewTabsSettings};
163use workspace::notifications::{DetachAndPromptErr, NotificationId};
164use workspace::{
165 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
166};
167use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
168
169use crate::hover_links::find_url;
170use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
171
172pub const FILE_HEADER_HEIGHT: u32 = 1;
173pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
174pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
175pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
176const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
177const MAX_LINE_LEN: usize = 1024;
178const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
179const MAX_SELECTION_HISTORY_LEN: usize = 1024;
180pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
181#[doc(hidden)]
182pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
183#[doc(hidden)]
184pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
185
186pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
187pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
188
189pub fn render_parsed_markdown(
190 element_id: impl Into<ElementId>,
191 parsed: &language::ParsedMarkdown,
192 editor_style: &EditorStyle,
193 workspace: Option<WeakView<Workspace>>,
194 cx: &mut WindowContext,
195) -> InteractiveText {
196 let code_span_background_color = cx
197 .theme()
198 .colors()
199 .editor_document_highlight_read_background;
200
201 let highlights = gpui::combine_highlights(
202 parsed.highlights.iter().filter_map(|(range, highlight)| {
203 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
204 Some((range.clone(), highlight))
205 }),
206 parsed
207 .regions
208 .iter()
209 .zip(&parsed.region_ranges)
210 .filter_map(|(region, range)| {
211 if region.code {
212 Some((
213 range.clone(),
214 HighlightStyle {
215 background_color: Some(code_span_background_color),
216 ..Default::default()
217 },
218 ))
219 } else {
220 None
221 }
222 }),
223 );
224
225 let mut links = Vec::new();
226 let mut link_ranges = Vec::new();
227 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
228 if let Some(link) = region.link.clone() {
229 links.push(link);
230 link_ranges.push(range.clone());
231 }
232 }
233
234 InteractiveText::new(
235 element_id,
236 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
237 )
238 .on_click(link_ranges, move |clicked_range_ix, cx| {
239 match &links[clicked_range_ix] {
240 markdown::Link::Web { url } => cx.open_url(url),
241 markdown::Link::Path { path } => {
242 if let Some(workspace) = &workspace {
243 _ = workspace.update(cx, |workspace, cx| {
244 workspace.open_abs_path(path.clone(), false, cx).detach();
245 });
246 }
247 }
248 }
249 })
250}
251
252#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
253pub(crate) enum InlayId {
254 Suggestion(usize),
255 Hint(usize),
256}
257
258impl InlayId {
259 fn id(&self) -> usize {
260 match self {
261 Self::Suggestion(id) => *id,
262 Self::Hint(id) => *id,
263 }
264 }
265}
266
267enum DiffRowHighlight {}
268enum DocumentHighlightRead {}
269enum DocumentHighlightWrite {}
270enum InputComposition {}
271
272#[derive(Copy, Clone, PartialEq, Eq)]
273pub enum Direction {
274 Prev,
275 Next,
276}
277
278#[derive(Debug, Copy, Clone, PartialEq, Eq)]
279pub enum Navigated {
280 Yes,
281 No,
282}
283
284impl Navigated {
285 pub fn from_bool(yes: bool) -> Navigated {
286 if yes {
287 Navigated::Yes
288 } else {
289 Navigated::No
290 }
291 }
292}
293
294pub fn init_settings(cx: &mut AppContext) {
295 EditorSettings::register(cx);
296}
297
298pub fn init(cx: &mut AppContext) {
299 init_settings(cx);
300
301 workspace::register_project_item::<Editor>(cx);
302 workspace::FollowableViewRegistry::register::<Editor>(cx);
303 workspace::register_serializable_item::<Editor>(cx);
304
305 cx.observe_new_views(
306 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
307 workspace.register_action(Editor::new_file);
308 workspace.register_action(Editor::new_file_vertical);
309 workspace.register_action(Editor::new_file_horizontal);
310 },
311 )
312 .detach();
313
314 cx.on_action(move |_: &workspace::NewFile, cx| {
315 let app_state = workspace::AppState::global(cx);
316 if let Some(app_state) = app_state.upgrade() {
317 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
318 Editor::new_file(workspace, &Default::default(), cx)
319 })
320 .detach();
321 }
322 });
323 cx.on_action(move |_: &workspace::NewWindow, cx| {
324 let app_state = workspace::AppState::global(cx);
325 if let Some(app_state) = app_state.upgrade() {
326 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
327 Editor::new_file(workspace, &Default::default(), cx)
328 })
329 .detach();
330 }
331 });
332}
333
334pub struct SearchWithinRange;
335
336trait InvalidationRegion {
337 fn ranges(&self) -> &[Range<Anchor>];
338}
339
340#[derive(Clone, Debug, PartialEq)]
341pub enum SelectPhase {
342 Begin {
343 position: DisplayPoint,
344 add: bool,
345 click_count: usize,
346 },
347 BeginColumnar {
348 position: DisplayPoint,
349 reset: bool,
350 goal_column: u32,
351 },
352 Extend {
353 position: DisplayPoint,
354 click_count: usize,
355 },
356 Update {
357 position: DisplayPoint,
358 goal_column: u32,
359 scroll_delta: gpui::Point<f32>,
360 },
361 End,
362}
363
364#[derive(Clone, Debug)]
365pub enum SelectMode {
366 Character,
367 Word(Range<Anchor>),
368 Line(Range<Anchor>),
369 All,
370}
371
372#[derive(Copy, Clone, PartialEq, Eq, Debug)]
373pub enum EditorMode {
374 SingleLine { auto_width: bool },
375 AutoHeight { max_lines: usize },
376 Full,
377}
378
379#[derive(Copy, Clone, Debug)]
380pub enum SoftWrap {
381 /// Prefer not to wrap at all.
382 ///
383 /// Note: this is currently internal, as actually limited by [`crate::MAX_LINE_LEN`] until it wraps.
384 /// The mode is used inside git diff hunks, where it's seems currently more useful to not wrap as much as possible.
385 GitDiff,
386 /// Prefer a single line generally, unless an overly long line is encountered.
387 None,
388 /// Soft wrap lines that exceed the editor width.
389 EditorWidth,
390 /// Soft wrap lines at the preferred line length.
391 Column(u32),
392 /// Soft wrap line at the preferred line length or the editor width (whichever is smaller).
393 Bounded(u32),
394}
395
396#[derive(Clone)]
397pub struct EditorStyle {
398 pub background: Hsla,
399 pub local_player: PlayerColor,
400 pub text: TextStyle,
401 pub scrollbar_width: Pixels,
402 pub syntax: Arc<SyntaxTheme>,
403 pub status: StatusColors,
404 pub inlay_hints_style: HighlightStyle,
405 pub suggestions_style: HighlightStyle,
406 pub unnecessary_code_fade: f32,
407}
408
409impl Default for EditorStyle {
410 fn default() -> Self {
411 Self {
412 background: Hsla::default(),
413 local_player: PlayerColor::default(),
414 text: TextStyle::default(),
415 scrollbar_width: Pixels::default(),
416 syntax: Default::default(),
417 // HACK: Status colors don't have a real default.
418 // We should look into removing the status colors from the editor
419 // style and retrieve them directly from the theme.
420 status: StatusColors::dark(),
421 inlay_hints_style: HighlightStyle::default(),
422 suggestions_style: HighlightStyle::default(),
423 unnecessary_code_fade: Default::default(),
424 }
425 }
426}
427
428pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
429 let show_background = all_language_settings(None, cx)
430 .language(None)
431 .inlay_hints
432 .show_background;
433
434 HighlightStyle {
435 color: Some(cx.theme().status().hint),
436 background_color: show_background.then(|| cx.theme().status().hint_background),
437 ..HighlightStyle::default()
438 }
439}
440
441type CompletionId = usize;
442
443#[derive(Clone, Debug)]
444struct CompletionState {
445 // render_inlay_ids represents the inlay hints that are inserted
446 // for rendering the inline completions. They may be discontinuous
447 // in the event that the completion provider returns some intersection
448 // with the existing content.
449 render_inlay_ids: Vec<InlayId>,
450 // text is the resulting rope that is inserted when the user accepts a completion.
451 text: Rope,
452 // position is the position of the cursor when the completion was triggered.
453 position: multi_buffer::Anchor,
454 // delete_range is the range of text that this completion state covers.
455 // if the completion is accepted, this range should be deleted.
456 delete_range: Option<Range<multi_buffer::Anchor>>,
457}
458
459#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
460struct EditorActionId(usize);
461
462impl EditorActionId {
463 pub fn post_inc(&mut self) -> Self {
464 let answer = self.0;
465
466 *self = Self(answer + 1);
467
468 Self(answer)
469 }
470}
471
472// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
473// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
474
475type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
476type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
477
478#[derive(Default)]
479struct ScrollbarMarkerState {
480 scrollbar_size: Size<Pixels>,
481 dirty: bool,
482 markers: Arc<[PaintQuad]>,
483 pending_refresh: Option<Task<Result<()>>>,
484}
485
486impl ScrollbarMarkerState {
487 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
488 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
489 }
490}
491
492#[derive(Clone, Debug)]
493struct RunnableTasks {
494 templates: Vec<(TaskSourceKind, TaskTemplate)>,
495 offset: MultiBufferOffset,
496 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
497 column: u32,
498 // Values of all named captures, including those starting with '_'
499 extra_variables: HashMap<String, String>,
500 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
501 context_range: Range<BufferOffset>,
502}
503
504#[derive(Clone)]
505struct ResolvedTasks {
506 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
507 position: Anchor,
508}
509#[derive(Copy, Clone, Debug)]
510struct MultiBufferOffset(usize);
511#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
512struct BufferOffset(usize);
513
514// Addons allow storing per-editor state in other crates (e.g. Vim)
515pub trait Addon: 'static {
516 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
517
518 fn to_any(&self) -> &dyn std::any::Any;
519}
520
521/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
522///
523/// See the [module level documentation](self) for more information.
524pub struct Editor {
525 focus_handle: FocusHandle,
526 last_focused_descendant: Option<WeakFocusHandle>,
527 /// The text buffer being edited
528 buffer: Model<MultiBuffer>,
529 /// Map of how text in the buffer should be displayed.
530 /// Handles soft wraps, folds, fake inlay text insertions, etc.
531 pub display_map: Model<DisplayMap>,
532 pub selections: SelectionsCollection,
533 pub scroll_manager: ScrollManager,
534 /// When inline assist editors are linked, they all render cursors because
535 /// typing enters text into each of them, even the ones that aren't focused.
536 pub(crate) show_cursor_when_unfocused: bool,
537 columnar_selection_tail: Option<Anchor>,
538 add_selections_state: Option<AddSelectionsState>,
539 select_next_state: Option<SelectNextState>,
540 select_prev_state: Option<SelectNextState>,
541 selection_history: SelectionHistory,
542 autoclose_regions: Vec<AutocloseRegion>,
543 snippet_stack: InvalidationStack<SnippetState>,
544 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
545 ime_transaction: Option<TransactionId>,
546 active_diagnostics: Option<ActiveDiagnosticGroup>,
547 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
548 project: Option<Model<Project>>,
549 completion_provider: Option<Box<dyn CompletionProvider>>,
550 collaboration_hub: Option<Box<dyn CollaborationHub>>,
551 blink_manager: Model<BlinkManager>,
552 show_cursor_names: bool,
553 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
554 pub show_local_selections: bool,
555 mode: EditorMode,
556 show_breadcrumbs: bool,
557 show_gutter: bool,
558 show_line_numbers: Option<bool>,
559 use_relative_line_numbers: Option<bool>,
560 show_git_diff_gutter: Option<bool>,
561 show_code_actions: Option<bool>,
562 show_runnables: Option<bool>,
563 show_wrap_guides: Option<bool>,
564 show_indent_guides: Option<bool>,
565 placeholder_text: Option<Arc<str>>,
566 highlight_order: usize,
567 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
568 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
569 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
570 scrollbar_marker_state: ScrollbarMarkerState,
571 active_indent_guides_state: ActiveIndentGuidesState,
572 nav_history: Option<ItemNavHistory>,
573 context_menu: RwLock<Option<ContextMenu>>,
574 mouse_context_menu: Option<MouseContextMenu>,
575 hunk_controls_menu_handle: PopoverMenuHandle<ui::ContextMenu>,
576 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
577 signature_help_state: SignatureHelpState,
578 auto_signature_help: Option<bool>,
579 find_all_references_task_sources: Vec<Anchor>,
580 next_completion_id: CompletionId,
581 completion_documentation_pre_resolve_debounce: DebouncedDelay,
582 available_code_actions: Option<(Location, Arc<[AvailableCodeAction]>)>,
583 code_actions_task: Option<Task<Result<()>>>,
584 document_highlights_task: Option<Task<()>>,
585 linked_editing_range_task: Option<Task<Option<()>>>,
586 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
587 pending_rename: Option<RenameState>,
588 searchable: bool,
589 cursor_shape: CursorShape,
590 current_line_highlight: Option<CurrentLineHighlight>,
591 collapse_matches: bool,
592 autoindent_mode: Option<AutoindentMode>,
593 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
594 input_enabled: bool,
595 use_modal_editing: bool,
596 read_only: bool,
597 leader_peer_id: Option<PeerId>,
598 remote_id: Option<ViewId>,
599 hover_state: HoverState,
600 gutter_hovered: bool,
601 hovered_link_state: Option<HoveredLinkState>,
602 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
603 code_action_providers: Vec<Arc<dyn CodeActionProvider>>,
604 active_inline_completion: Option<CompletionState>,
605 // enable_inline_completions is a switch that Vim can use to disable
606 // inline completions based on its mode.
607 enable_inline_completions: bool,
608 show_inline_completions_override: Option<bool>,
609 inlay_hint_cache: InlayHintCache,
610 expanded_hunks: ExpandedHunks,
611 next_inlay_id: usize,
612 _subscriptions: Vec<Subscription>,
613 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
614 gutter_dimensions: GutterDimensions,
615 style: Option<EditorStyle>,
616 next_editor_action_id: EditorActionId,
617 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
618 use_autoclose: bool,
619 use_auto_surround: bool,
620 auto_replace_emoji_shortcode: bool,
621 show_git_blame_gutter: bool,
622 show_git_blame_inline: bool,
623 show_git_blame_inline_delay_task: Option<Task<()>>,
624 git_blame_inline_enabled: bool,
625 serialize_dirty_buffers: bool,
626 show_selection_menu: Option<bool>,
627 blame: Option<Model<GitBlame>>,
628 blame_subscription: Option<Subscription>,
629 custom_context_menu: Option<
630 Box<
631 dyn 'static
632 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
633 >,
634 >,
635 last_bounds: Option<Bounds<Pixels>>,
636 expect_bounds_change: Option<Bounds<Pixels>>,
637 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
638 tasks_update_task: Option<Task<()>>,
639 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
640 file_header_size: u32,
641 breadcrumb_header: Option<String>,
642 focused_block: Option<FocusedBlock>,
643 next_scroll_position: NextScrollCursorCenterTopBottom,
644 addons: HashMap<TypeId, Box<dyn Addon>>,
645 _scroll_cursor_center_top_bottom_task: Task<()>,
646}
647
648#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
649enum NextScrollCursorCenterTopBottom {
650 #[default]
651 Center,
652 Top,
653 Bottom,
654}
655
656impl NextScrollCursorCenterTopBottom {
657 fn next(&self) -> Self {
658 match self {
659 Self::Center => Self::Top,
660 Self::Top => Self::Bottom,
661 Self::Bottom => Self::Center,
662 }
663 }
664}
665
666#[derive(Clone)]
667pub struct EditorSnapshot {
668 pub mode: EditorMode,
669 show_gutter: bool,
670 show_line_numbers: Option<bool>,
671 show_git_diff_gutter: Option<bool>,
672 show_code_actions: Option<bool>,
673 show_runnables: Option<bool>,
674 git_blame_gutter_max_author_length: Option<usize>,
675 pub display_snapshot: DisplaySnapshot,
676 pub placeholder_text: Option<Arc<str>>,
677 is_focused: bool,
678 scroll_anchor: ScrollAnchor,
679 ongoing_scroll: OngoingScroll,
680 current_line_highlight: CurrentLineHighlight,
681 gutter_hovered: bool,
682}
683
684const GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED: usize = 20;
685
686#[derive(Default, Debug, Clone, Copy)]
687pub struct GutterDimensions {
688 pub left_padding: Pixels,
689 pub right_padding: Pixels,
690 pub width: Pixels,
691 pub margin: Pixels,
692 pub git_blame_entries_width: Option<Pixels>,
693}
694
695impl GutterDimensions {
696 /// The full width of the space taken up by the gutter.
697 pub fn full_width(&self) -> Pixels {
698 self.margin + self.width
699 }
700
701 /// The width of the space reserved for the fold indicators,
702 /// use alongside 'justify_end' and `gutter_width` to
703 /// right align content with the line numbers
704 pub fn fold_area_width(&self) -> Pixels {
705 self.margin + self.right_padding
706 }
707}
708
709#[derive(Debug)]
710pub struct RemoteSelection {
711 pub replica_id: ReplicaId,
712 pub selection: Selection<Anchor>,
713 pub cursor_shape: CursorShape,
714 pub peer_id: PeerId,
715 pub line_mode: bool,
716 pub participant_index: Option<ParticipantIndex>,
717 pub user_name: Option<SharedString>,
718}
719
720#[derive(Clone, Debug)]
721struct SelectionHistoryEntry {
722 selections: Arc<[Selection<Anchor>]>,
723 select_next_state: Option<SelectNextState>,
724 select_prev_state: Option<SelectNextState>,
725 add_selections_state: Option<AddSelectionsState>,
726}
727
728enum SelectionHistoryMode {
729 Normal,
730 Undoing,
731 Redoing,
732}
733
734#[derive(Clone, PartialEq, Eq, Hash)]
735struct HoveredCursor {
736 replica_id: u16,
737 selection_id: usize,
738}
739
740impl Default for SelectionHistoryMode {
741 fn default() -> Self {
742 Self::Normal
743 }
744}
745
746#[derive(Default)]
747struct SelectionHistory {
748 #[allow(clippy::type_complexity)]
749 selections_by_transaction:
750 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
751 mode: SelectionHistoryMode,
752 undo_stack: VecDeque<SelectionHistoryEntry>,
753 redo_stack: VecDeque<SelectionHistoryEntry>,
754}
755
756impl SelectionHistory {
757 fn insert_transaction(
758 &mut self,
759 transaction_id: TransactionId,
760 selections: Arc<[Selection<Anchor>]>,
761 ) {
762 self.selections_by_transaction
763 .insert(transaction_id, (selections, None));
764 }
765
766 #[allow(clippy::type_complexity)]
767 fn transaction(
768 &self,
769 transaction_id: TransactionId,
770 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
771 self.selections_by_transaction.get(&transaction_id)
772 }
773
774 #[allow(clippy::type_complexity)]
775 fn transaction_mut(
776 &mut self,
777 transaction_id: TransactionId,
778 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
779 self.selections_by_transaction.get_mut(&transaction_id)
780 }
781
782 fn push(&mut self, entry: SelectionHistoryEntry) {
783 if !entry.selections.is_empty() {
784 match self.mode {
785 SelectionHistoryMode::Normal => {
786 self.push_undo(entry);
787 self.redo_stack.clear();
788 }
789 SelectionHistoryMode::Undoing => self.push_redo(entry),
790 SelectionHistoryMode::Redoing => self.push_undo(entry),
791 }
792 }
793 }
794
795 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
796 if self
797 .undo_stack
798 .back()
799 .map_or(true, |e| e.selections != entry.selections)
800 {
801 self.undo_stack.push_back(entry);
802 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
803 self.undo_stack.pop_front();
804 }
805 }
806 }
807
808 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
809 if self
810 .redo_stack
811 .back()
812 .map_or(true, |e| e.selections != entry.selections)
813 {
814 self.redo_stack.push_back(entry);
815 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
816 self.redo_stack.pop_front();
817 }
818 }
819 }
820}
821
822struct RowHighlight {
823 index: usize,
824 range: Range<Anchor>,
825 color: Hsla,
826 should_autoscroll: bool,
827}
828
829#[derive(Clone, Debug)]
830struct AddSelectionsState {
831 above: bool,
832 stack: Vec<usize>,
833}
834
835#[derive(Clone)]
836struct SelectNextState {
837 query: AhoCorasick,
838 wordwise: bool,
839 done: bool,
840}
841
842impl std::fmt::Debug for SelectNextState {
843 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
844 f.debug_struct(std::any::type_name::<Self>())
845 .field("wordwise", &self.wordwise)
846 .field("done", &self.done)
847 .finish()
848 }
849}
850
851#[derive(Debug)]
852struct AutocloseRegion {
853 selection_id: usize,
854 range: Range<Anchor>,
855 pair: BracketPair,
856}
857
858#[derive(Debug)]
859struct SnippetState {
860 ranges: Vec<Vec<Range<Anchor>>>,
861 active_index: usize,
862}
863
864#[doc(hidden)]
865pub struct RenameState {
866 pub range: Range<Anchor>,
867 pub old_name: Arc<str>,
868 pub editor: View<Editor>,
869 block_id: CustomBlockId,
870}
871
872struct InvalidationStack<T>(Vec<T>);
873
874struct RegisteredInlineCompletionProvider {
875 provider: Arc<dyn InlineCompletionProviderHandle>,
876 _subscription: Subscription,
877}
878
879enum ContextMenu {
880 Completions(CompletionsMenu),
881 CodeActions(CodeActionsMenu),
882}
883
884impl ContextMenu {
885 fn select_first(
886 &mut self,
887 project: Option<&Model<Project>>,
888 cx: &mut ViewContext<Editor>,
889 ) -> bool {
890 if self.visible() {
891 match self {
892 ContextMenu::Completions(menu) => menu.select_first(project, cx),
893 ContextMenu::CodeActions(menu) => menu.select_first(cx),
894 }
895 true
896 } else {
897 false
898 }
899 }
900
901 fn select_prev(
902 &mut self,
903 project: Option<&Model<Project>>,
904 cx: &mut ViewContext<Editor>,
905 ) -> bool {
906 if self.visible() {
907 match self {
908 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
909 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
910 }
911 true
912 } else {
913 false
914 }
915 }
916
917 fn select_next(
918 &mut self,
919 project: Option<&Model<Project>>,
920 cx: &mut ViewContext<Editor>,
921 ) -> bool {
922 if self.visible() {
923 match self {
924 ContextMenu::Completions(menu) => menu.select_next(project, cx),
925 ContextMenu::CodeActions(menu) => menu.select_next(cx),
926 }
927 true
928 } else {
929 false
930 }
931 }
932
933 fn select_last(
934 &mut self,
935 project: Option<&Model<Project>>,
936 cx: &mut ViewContext<Editor>,
937 ) -> bool {
938 if self.visible() {
939 match self {
940 ContextMenu::Completions(menu) => menu.select_last(project, cx),
941 ContextMenu::CodeActions(menu) => menu.select_last(cx),
942 }
943 true
944 } else {
945 false
946 }
947 }
948
949 fn visible(&self) -> bool {
950 match self {
951 ContextMenu::Completions(menu) => menu.visible(),
952 ContextMenu::CodeActions(menu) => menu.visible(),
953 }
954 }
955
956 fn render(
957 &self,
958 cursor_position: DisplayPoint,
959 style: &EditorStyle,
960 max_height: Pixels,
961 workspace: Option<WeakView<Workspace>>,
962 cx: &mut ViewContext<Editor>,
963 ) -> (ContextMenuOrigin, AnyElement) {
964 match self {
965 ContextMenu::Completions(menu) => (
966 ContextMenuOrigin::EditorPoint(cursor_position),
967 menu.render(style, max_height, workspace, cx),
968 ),
969 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
970 }
971 }
972}
973
974enum ContextMenuOrigin {
975 EditorPoint(DisplayPoint),
976 GutterIndicator(DisplayRow),
977}
978
979#[derive(Clone)]
980struct CompletionsMenu {
981 id: CompletionId,
982 sort_completions: bool,
983 initial_position: Anchor,
984 buffer: Model<Buffer>,
985 completions: Arc<RwLock<Box<[Completion]>>>,
986 match_candidates: Arc<[StringMatchCandidate]>,
987 matches: Arc<[StringMatch]>,
988 selected_item: usize,
989 scroll_handle: UniformListScrollHandle,
990 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
991}
992
993impl CompletionsMenu {
994 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
995 self.selected_item = 0;
996 self.scroll_handle.scroll_to_item(self.selected_item);
997 self.attempt_resolve_selected_completion_documentation(project, cx);
998 cx.notify();
999 }
1000
1001 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
1002 if self.selected_item > 0 {
1003 self.selected_item -= 1;
1004 } else {
1005 self.selected_item = self.matches.len() - 1;
1006 }
1007 self.scroll_handle.scroll_to_item(self.selected_item);
1008 self.attempt_resolve_selected_completion_documentation(project, cx);
1009 cx.notify();
1010 }
1011
1012 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
1013 if self.selected_item + 1 < self.matches.len() {
1014 self.selected_item += 1;
1015 } else {
1016 self.selected_item = 0;
1017 }
1018 self.scroll_handle.scroll_to_item(self.selected_item);
1019 self.attempt_resolve_selected_completion_documentation(project, cx);
1020 cx.notify();
1021 }
1022
1023 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
1024 self.selected_item = self.matches.len() - 1;
1025 self.scroll_handle.scroll_to_item(self.selected_item);
1026 self.attempt_resolve_selected_completion_documentation(project, cx);
1027 cx.notify();
1028 }
1029
1030 fn pre_resolve_completion_documentation(
1031 buffer: Model<Buffer>,
1032 completions: Arc<RwLock<Box<[Completion]>>>,
1033 matches: Arc<[StringMatch]>,
1034 editor: &Editor,
1035 cx: &mut ViewContext<Editor>,
1036 ) -> Task<()> {
1037 let settings = EditorSettings::get_global(cx);
1038 if !settings.show_completion_documentation {
1039 return Task::ready(());
1040 }
1041
1042 let Some(provider) = editor.completion_provider.as_ref() else {
1043 return Task::ready(());
1044 };
1045
1046 let resolve_task = provider.resolve_completions(
1047 buffer,
1048 matches.iter().map(|m| m.candidate_id).collect(),
1049 completions.clone(),
1050 cx,
1051 );
1052
1053 cx.spawn(move |this, mut cx| async move {
1054 if let Some(true) = resolve_task.await.log_err() {
1055 this.update(&mut cx, |_, cx| cx.notify()).ok();
1056 }
1057 })
1058 }
1059
1060 fn attempt_resolve_selected_completion_documentation(
1061 &mut self,
1062 project: Option<&Model<Project>>,
1063 cx: &mut ViewContext<Editor>,
1064 ) {
1065 let settings = EditorSettings::get_global(cx);
1066 if !settings.show_completion_documentation {
1067 return;
1068 }
1069
1070 let completion_index = self.matches[self.selected_item].candidate_id;
1071 let Some(project) = project else {
1072 return;
1073 };
1074
1075 let resolve_task = project.update(cx, |project, cx| {
1076 project.resolve_completions(
1077 self.buffer.clone(),
1078 vec![completion_index],
1079 self.completions.clone(),
1080 cx,
1081 )
1082 });
1083
1084 let delay_ms =
1085 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1086 let delay = Duration::from_millis(delay_ms);
1087
1088 self.selected_completion_documentation_resolve_debounce
1089 .lock()
1090 .fire_new(delay, cx, |_, cx| {
1091 cx.spawn(move |this, mut cx| async move {
1092 if let Some(true) = resolve_task.await.log_err() {
1093 this.update(&mut cx, |_, cx| cx.notify()).ok();
1094 }
1095 })
1096 });
1097 }
1098
1099 fn visible(&self) -> bool {
1100 !self.matches.is_empty()
1101 }
1102
1103 fn render(
1104 &self,
1105 style: &EditorStyle,
1106 max_height: Pixels,
1107 workspace: Option<WeakView<Workspace>>,
1108 cx: &mut ViewContext<Editor>,
1109 ) -> AnyElement {
1110 let settings = EditorSettings::get_global(cx);
1111 let show_completion_documentation = settings.show_completion_documentation;
1112
1113 let widest_completion_ix = self
1114 .matches
1115 .iter()
1116 .enumerate()
1117 .max_by_key(|(_, mat)| {
1118 let completions = self.completions.read();
1119 let completion = &completions[mat.candidate_id];
1120 let documentation = &completion.documentation;
1121
1122 let mut len = completion.label.text.chars().count();
1123 if let Some(Documentation::SingleLine(text)) = documentation {
1124 if show_completion_documentation {
1125 len += text.chars().count();
1126 }
1127 }
1128
1129 len
1130 })
1131 .map(|(ix, _)| ix);
1132
1133 let completions = self.completions.clone();
1134 let matches = self.matches.clone();
1135 let selected_item = self.selected_item;
1136 let style = style.clone();
1137
1138 let multiline_docs = if show_completion_documentation {
1139 let mat = &self.matches[selected_item];
1140 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1141 Some(Documentation::MultiLinePlainText(text)) => {
1142 Some(div().child(SharedString::from(text.clone())))
1143 }
1144 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1145 Some(div().child(render_parsed_markdown(
1146 "completions_markdown",
1147 parsed,
1148 &style,
1149 workspace,
1150 cx,
1151 )))
1152 }
1153 _ => None,
1154 };
1155 multiline_docs.map(|div| {
1156 div.id("multiline_docs")
1157 .max_h(max_height)
1158 .flex_1()
1159 .px_1p5()
1160 .py_1()
1161 .min_w(px(260.))
1162 .max_w(px(640.))
1163 .w(px(500.))
1164 .overflow_y_scroll()
1165 .occlude()
1166 })
1167 } else {
1168 None
1169 };
1170
1171 let list = uniform_list(
1172 cx.view().clone(),
1173 "completions",
1174 matches.len(),
1175 move |_editor, range, cx| {
1176 let start_ix = range.start;
1177 let completions_guard = completions.read();
1178
1179 matches[range]
1180 .iter()
1181 .enumerate()
1182 .map(|(ix, mat)| {
1183 let item_ix = start_ix + ix;
1184 let candidate_id = mat.candidate_id;
1185 let completion = &completions_guard[candidate_id];
1186
1187 let documentation = if show_completion_documentation {
1188 &completion.documentation
1189 } else {
1190 &None
1191 };
1192
1193 let highlights = gpui::combine_highlights(
1194 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1195 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1196 |(range, mut highlight)| {
1197 // Ignore font weight for syntax highlighting, as we'll use it
1198 // for fuzzy matches.
1199 highlight.font_weight = None;
1200
1201 if completion.lsp_completion.deprecated.unwrap_or(false) {
1202 highlight.strikethrough = Some(StrikethroughStyle {
1203 thickness: 1.0.into(),
1204 ..Default::default()
1205 });
1206 highlight.color = Some(cx.theme().colors().text_muted);
1207 }
1208
1209 (range, highlight)
1210 },
1211 ),
1212 );
1213 let completion_label = StyledText::new(completion.label.text.clone())
1214 .with_highlights(&style.text, highlights);
1215 let documentation_label =
1216 if let Some(Documentation::SingleLine(text)) = documentation {
1217 if text.trim().is_empty() {
1218 None
1219 } else {
1220 Some(
1221 Label::new(text.clone())
1222 .ml_4()
1223 .size(LabelSize::Small)
1224 .color(Color::Muted),
1225 )
1226 }
1227 } else {
1228 None
1229 };
1230
1231 let color_swatch = completion
1232 .color()
1233 .map(|color| div().size_4().bg(color).rounded_sm());
1234
1235 div().min_w(px(220.)).max_w(px(540.)).child(
1236 ListItem::new(mat.candidate_id)
1237 .inset(true)
1238 .selected(item_ix == selected_item)
1239 .on_click(cx.listener(move |editor, _event, cx| {
1240 cx.stop_propagation();
1241 if let Some(task) = editor.confirm_completion(
1242 &ConfirmCompletion {
1243 item_ix: Some(item_ix),
1244 },
1245 cx,
1246 ) {
1247 task.detach_and_log_err(cx)
1248 }
1249 }))
1250 .start_slot::<Div>(color_swatch)
1251 .child(h_flex().overflow_hidden().child(completion_label))
1252 .end_slot::<Label>(documentation_label),
1253 )
1254 })
1255 .collect()
1256 },
1257 )
1258 .occlude()
1259 .max_h(max_height)
1260 .track_scroll(self.scroll_handle.clone())
1261 .with_width_from_item(widest_completion_ix)
1262 .with_sizing_behavior(ListSizingBehavior::Infer);
1263
1264 Popover::new()
1265 .child(list)
1266 .when_some(multiline_docs, |popover, multiline_docs| {
1267 popover.aside(multiline_docs)
1268 })
1269 .into_any_element()
1270 }
1271
1272 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1273 let mut matches = if let Some(query) = query {
1274 fuzzy::match_strings(
1275 &self.match_candidates,
1276 query,
1277 query.chars().any(|c| c.is_uppercase()),
1278 100,
1279 &Default::default(),
1280 executor,
1281 )
1282 .await
1283 } else {
1284 self.match_candidates
1285 .iter()
1286 .enumerate()
1287 .map(|(candidate_id, candidate)| StringMatch {
1288 candidate_id,
1289 score: Default::default(),
1290 positions: Default::default(),
1291 string: candidate.string.clone(),
1292 })
1293 .collect()
1294 };
1295
1296 // Remove all candidates where the query's start does not match the start of any word in the candidate
1297 if let Some(query) = query {
1298 if let Some(query_start) = query.chars().next() {
1299 matches.retain(|string_match| {
1300 split_words(&string_match.string).any(|word| {
1301 // Check that the first codepoint of the word as lowercase matches the first
1302 // codepoint of the query as lowercase
1303 word.chars()
1304 .flat_map(|codepoint| codepoint.to_lowercase())
1305 .zip(query_start.to_lowercase())
1306 .all(|(word_cp, query_cp)| word_cp == query_cp)
1307 })
1308 });
1309 }
1310 }
1311
1312 let completions = self.completions.read();
1313 if self.sort_completions {
1314 matches.sort_unstable_by_key(|mat| {
1315 // We do want to strike a balance here between what the language server tells us
1316 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1317 // `Creat` and there is a local variable called `CreateComponent`).
1318 // So what we do is: we bucket all matches into two buckets
1319 // - Strong matches
1320 // - Weak matches
1321 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1322 // and the Weak matches are the rest.
1323 //
1324 // For the strong matches, we sort by the language-servers score first and for the weak
1325 // matches, we prefer our fuzzy finder first.
1326 //
1327 // The thinking behind that: it's useless to take the sort_text the language-server gives
1328 // us into account when it's obviously a bad match.
1329
1330 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1331 enum MatchScore<'a> {
1332 Strong {
1333 sort_text: Option<&'a str>,
1334 score: Reverse<OrderedFloat<f64>>,
1335 sort_key: (usize, &'a str),
1336 },
1337 Weak {
1338 score: Reverse<OrderedFloat<f64>>,
1339 sort_text: Option<&'a str>,
1340 sort_key: (usize, &'a str),
1341 },
1342 }
1343
1344 let completion = &completions[mat.candidate_id];
1345 let sort_key = completion.sort_key();
1346 let sort_text = completion.lsp_completion.sort_text.as_deref();
1347 let score = Reverse(OrderedFloat(mat.score));
1348
1349 if mat.score >= 0.2 {
1350 MatchScore::Strong {
1351 sort_text,
1352 score,
1353 sort_key,
1354 }
1355 } else {
1356 MatchScore::Weak {
1357 score,
1358 sort_text,
1359 sort_key,
1360 }
1361 }
1362 });
1363 }
1364
1365 for mat in &mut matches {
1366 let completion = &completions[mat.candidate_id];
1367 mat.string.clone_from(&completion.label.text);
1368 for position in &mut mat.positions {
1369 *position += completion.label.filter_range.start;
1370 }
1371 }
1372 drop(completions);
1373
1374 self.matches = matches.into();
1375 self.selected_item = 0;
1376 }
1377}
1378
1379struct AvailableCodeAction {
1380 excerpt_id: ExcerptId,
1381 action: CodeAction,
1382 provider: Arc<dyn CodeActionProvider>,
1383}
1384
1385#[derive(Clone)]
1386struct CodeActionContents {
1387 tasks: Option<Arc<ResolvedTasks>>,
1388 actions: Option<Arc<[AvailableCodeAction]>>,
1389}
1390
1391impl CodeActionContents {
1392 fn len(&self) -> usize {
1393 match (&self.tasks, &self.actions) {
1394 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1395 (Some(tasks), None) => tasks.templates.len(),
1396 (None, Some(actions)) => actions.len(),
1397 (None, None) => 0,
1398 }
1399 }
1400
1401 fn is_empty(&self) -> bool {
1402 match (&self.tasks, &self.actions) {
1403 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1404 (Some(tasks), None) => tasks.templates.is_empty(),
1405 (None, Some(actions)) => actions.is_empty(),
1406 (None, None) => true,
1407 }
1408 }
1409
1410 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1411 self.tasks
1412 .iter()
1413 .flat_map(|tasks| {
1414 tasks
1415 .templates
1416 .iter()
1417 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1418 })
1419 .chain(self.actions.iter().flat_map(|actions| {
1420 actions.iter().map(|available| CodeActionsItem::CodeAction {
1421 excerpt_id: available.excerpt_id,
1422 action: available.action.clone(),
1423 provider: available.provider.clone(),
1424 })
1425 }))
1426 }
1427 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1428 match (&self.tasks, &self.actions) {
1429 (Some(tasks), Some(actions)) => {
1430 if index < tasks.templates.len() {
1431 tasks
1432 .templates
1433 .get(index)
1434 .cloned()
1435 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1436 } else {
1437 actions.get(index - tasks.templates.len()).map(|available| {
1438 CodeActionsItem::CodeAction {
1439 excerpt_id: available.excerpt_id,
1440 action: available.action.clone(),
1441 provider: available.provider.clone(),
1442 }
1443 })
1444 }
1445 }
1446 (Some(tasks), None) => tasks
1447 .templates
1448 .get(index)
1449 .cloned()
1450 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1451 (None, Some(actions)) => {
1452 actions
1453 .get(index)
1454 .map(|available| CodeActionsItem::CodeAction {
1455 excerpt_id: available.excerpt_id,
1456 action: available.action.clone(),
1457 provider: available.provider.clone(),
1458 })
1459 }
1460 (None, None) => None,
1461 }
1462 }
1463}
1464
1465#[allow(clippy::large_enum_variant)]
1466#[derive(Clone)]
1467enum CodeActionsItem {
1468 Task(TaskSourceKind, ResolvedTask),
1469 CodeAction {
1470 excerpt_id: ExcerptId,
1471 action: CodeAction,
1472 provider: Arc<dyn CodeActionProvider>,
1473 },
1474}
1475
1476impl CodeActionsItem {
1477 fn as_task(&self) -> Option<&ResolvedTask> {
1478 let Self::Task(_, task) = self else {
1479 return None;
1480 };
1481 Some(task)
1482 }
1483 fn as_code_action(&self) -> Option<&CodeAction> {
1484 let Self::CodeAction { action, .. } = self else {
1485 return None;
1486 };
1487 Some(action)
1488 }
1489 fn label(&self) -> String {
1490 match self {
1491 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1492 Self::Task(_, task) => task.resolved_label.clone(),
1493 }
1494 }
1495}
1496
1497struct CodeActionsMenu {
1498 actions: CodeActionContents,
1499 buffer: Model<Buffer>,
1500 selected_item: usize,
1501 scroll_handle: UniformListScrollHandle,
1502 deployed_from_indicator: Option<DisplayRow>,
1503}
1504
1505impl CodeActionsMenu {
1506 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1507 self.selected_item = 0;
1508 self.scroll_handle.scroll_to_item(self.selected_item);
1509 cx.notify()
1510 }
1511
1512 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1513 if self.selected_item > 0 {
1514 self.selected_item -= 1;
1515 } else {
1516 self.selected_item = self.actions.len() - 1;
1517 }
1518 self.scroll_handle.scroll_to_item(self.selected_item);
1519 cx.notify();
1520 }
1521
1522 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1523 if self.selected_item + 1 < self.actions.len() {
1524 self.selected_item += 1;
1525 } else {
1526 self.selected_item = 0;
1527 }
1528 self.scroll_handle.scroll_to_item(self.selected_item);
1529 cx.notify();
1530 }
1531
1532 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1533 self.selected_item = self.actions.len() - 1;
1534 self.scroll_handle.scroll_to_item(self.selected_item);
1535 cx.notify()
1536 }
1537
1538 fn visible(&self) -> bool {
1539 !self.actions.is_empty()
1540 }
1541
1542 fn render(
1543 &self,
1544 cursor_position: DisplayPoint,
1545 _style: &EditorStyle,
1546 max_height: Pixels,
1547 cx: &mut ViewContext<Editor>,
1548 ) -> (ContextMenuOrigin, AnyElement) {
1549 let actions = self.actions.clone();
1550 let selected_item = self.selected_item;
1551 let element = uniform_list(
1552 cx.view().clone(),
1553 "code_actions_menu",
1554 self.actions.len(),
1555 move |_this, range, cx| {
1556 actions
1557 .iter()
1558 .skip(range.start)
1559 .take(range.end - range.start)
1560 .enumerate()
1561 .map(|(ix, action)| {
1562 let item_ix = range.start + ix;
1563 let selected = selected_item == item_ix;
1564 let colors = cx.theme().colors();
1565 div()
1566 .px_1()
1567 .rounded_md()
1568 .text_color(colors.text)
1569 .when(selected, |style| {
1570 style
1571 .bg(colors.element_active)
1572 .text_color(colors.text_accent)
1573 })
1574 .hover(|style| {
1575 style
1576 .bg(colors.element_hover)
1577 .text_color(colors.text_accent)
1578 })
1579 .whitespace_nowrap()
1580 .when_some(action.as_code_action(), |this, action| {
1581 this.on_mouse_down(
1582 MouseButton::Left,
1583 cx.listener(move |editor, _, cx| {
1584 cx.stop_propagation();
1585 if let Some(task) = editor.confirm_code_action(
1586 &ConfirmCodeAction {
1587 item_ix: Some(item_ix),
1588 },
1589 cx,
1590 ) {
1591 task.detach_and_log_err(cx)
1592 }
1593 }),
1594 )
1595 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1596 .child(SharedString::from(action.lsp_action.title.clone()))
1597 })
1598 .when_some(action.as_task(), |this, task| {
1599 this.on_mouse_down(
1600 MouseButton::Left,
1601 cx.listener(move |editor, _, cx| {
1602 cx.stop_propagation();
1603 if let Some(task) = editor.confirm_code_action(
1604 &ConfirmCodeAction {
1605 item_ix: Some(item_ix),
1606 },
1607 cx,
1608 ) {
1609 task.detach_and_log_err(cx)
1610 }
1611 }),
1612 )
1613 .child(SharedString::from(task.resolved_label.clone()))
1614 })
1615 })
1616 .collect()
1617 },
1618 )
1619 .elevation_1(cx)
1620 .p_1()
1621 .max_h(max_height)
1622 .occlude()
1623 .track_scroll(self.scroll_handle.clone())
1624 .with_width_from_item(
1625 self.actions
1626 .iter()
1627 .enumerate()
1628 .max_by_key(|(_, action)| match action {
1629 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1630 CodeActionsItem::CodeAction { action, .. } => {
1631 action.lsp_action.title.chars().count()
1632 }
1633 })
1634 .map(|(ix, _)| ix),
1635 )
1636 .with_sizing_behavior(ListSizingBehavior::Infer)
1637 .into_any_element();
1638
1639 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1640 ContextMenuOrigin::GutterIndicator(row)
1641 } else {
1642 ContextMenuOrigin::EditorPoint(cursor_position)
1643 };
1644
1645 (cursor_position, element)
1646 }
1647}
1648
1649#[derive(Debug)]
1650struct ActiveDiagnosticGroup {
1651 primary_range: Range<Anchor>,
1652 primary_message: String,
1653 group_id: usize,
1654 blocks: HashMap<CustomBlockId, Diagnostic>,
1655 is_valid: bool,
1656}
1657
1658#[derive(Serialize, Deserialize, Clone, Debug)]
1659pub struct ClipboardSelection {
1660 pub len: usize,
1661 pub is_entire_line: bool,
1662 pub first_line_indent: u32,
1663}
1664
1665#[derive(Debug)]
1666pub(crate) struct NavigationData {
1667 cursor_anchor: Anchor,
1668 cursor_position: Point,
1669 scroll_anchor: ScrollAnchor,
1670 scroll_top_row: u32,
1671}
1672
1673#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1674enum GotoDefinitionKind {
1675 Symbol,
1676 Declaration,
1677 Type,
1678 Implementation,
1679}
1680
1681#[derive(Debug, Clone)]
1682enum InlayHintRefreshReason {
1683 Toggle(bool),
1684 SettingsChange(InlayHintSettings),
1685 NewLinesShown,
1686 BufferEdited(HashSet<Arc<Language>>),
1687 RefreshRequested,
1688 ExcerptsRemoved(Vec<ExcerptId>),
1689}
1690
1691impl InlayHintRefreshReason {
1692 fn description(&self) -> &'static str {
1693 match self {
1694 Self::Toggle(_) => "toggle",
1695 Self::SettingsChange(_) => "settings change",
1696 Self::NewLinesShown => "new lines shown",
1697 Self::BufferEdited(_) => "buffer edited",
1698 Self::RefreshRequested => "refresh requested",
1699 Self::ExcerptsRemoved(_) => "excerpts removed",
1700 }
1701 }
1702}
1703
1704pub(crate) struct FocusedBlock {
1705 id: BlockId,
1706 focus_handle: WeakFocusHandle,
1707}
1708
1709impl Editor {
1710 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1711 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1712 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1713 Self::new(
1714 EditorMode::SingleLine { auto_width: false },
1715 buffer,
1716 None,
1717 false,
1718 cx,
1719 )
1720 }
1721
1722 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1723 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1724 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1725 Self::new(EditorMode::Full, buffer, None, false, cx)
1726 }
1727
1728 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1729 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1730 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1731 Self::new(
1732 EditorMode::SingleLine { auto_width: true },
1733 buffer,
1734 None,
1735 false,
1736 cx,
1737 )
1738 }
1739
1740 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1741 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1742 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1743 Self::new(
1744 EditorMode::AutoHeight { max_lines },
1745 buffer,
1746 None,
1747 false,
1748 cx,
1749 )
1750 }
1751
1752 pub fn for_buffer(
1753 buffer: Model<Buffer>,
1754 project: Option<Model<Project>>,
1755 cx: &mut ViewContext<Self>,
1756 ) -> Self {
1757 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1758 Self::new(EditorMode::Full, buffer, project, false, cx)
1759 }
1760
1761 pub fn for_multibuffer(
1762 buffer: Model<MultiBuffer>,
1763 project: Option<Model<Project>>,
1764 show_excerpt_controls: bool,
1765 cx: &mut ViewContext<Self>,
1766 ) -> Self {
1767 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1768 }
1769
1770 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1771 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1772 let mut clone = Self::new(
1773 self.mode,
1774 self.buffer.clone(),
1775 self.project.clone(),
1776 show_excerpt_controls,
1777 cx,
1778 );
1779 self.display_map.update(cx, |display_map, cx| {
1780 let snapshot = display_map.snapshot(cx);
1781 clone.display_map.update(cx, |display_map, cx| {
1782 display_map.set_state(&snapshot, cx);
1783 });
1784 });
1785 clone.selections.clone_state(&self.selections);
1786 clone.scroll_manager.clone_state(&self.scroll_manager);
1787 clone.searchable = self.searchable;
1788 clone
1789 }
1790
1791 pub fn new(
1792 mode: EditorMode,
1793 buffer: Model<MultiBuffer>,
1794 project: Option<Model<Project>>,
1795 show_excerpt_controls: bool,
1796 cx: &mut ViewContext<Self>,
1797 ) -> Self {
1798 let style = cx.text_style();
1799 let font_size = style.font_size.to_pixels(cx.rem_size());
1800 let editor = cx.view().downgrade();
1801 let fold_placeholder = FoldPlaceholder {
1802 constrain_width: true,
1803 render: Arc::new(move |fold_id, fold_range, cx| {
1804 let editor = editor.clone();
1805 div()
1806 .id(fold_id)
1807 .bg(cx.theme().colors().ghost_element_background)
1808 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1809 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1810 .rounded_sm()
1811 .size_full()
1812 .cursor_pointer()
1813 .child("⋯")
1814 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1815 .on_click(move |_, cx| {
1816 editor
1817 .update(cx, |editor, cx| {
1818 editor.unfold_ranges(
1819 [fold_range.start..fold_range.end],
1820 true,
1821 false,
1822 cx,
1823 );
1824 cx.stop_propagation();
1825 })
1826 .ok();
1827 })
1828 .into_any()
1829 }),
1830 merge_adjacent: true,
1831 };
1832 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1833 let display_map = cx.new_model(|cx| {
1834 DisplayMap::new(
1835 buffer.clone(),
1836 style.font(),
1837 font_size,
1838 None,
1839 show_excerpt_controls,
1840 file_header_size,
1841 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1842 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1843 fold_placeholder,
1844 cx,
1845 )
1846 });
1847
1848 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1849
1850 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1851
1852 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1853 .then(|| language_settings::SoftWrap::None);
1854
1855 let mut project_subscriptions = Vec::new();
1856 if mode == EditorMode::Full {
1857 if let Some(project) = project.as_ref() {
1858 if buffer.read(cx).is_singleton() {
1859 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1860 cx.emit(EditorEvent::TitleChanged);
1861 }));
1862 }
1863 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1864 if let project::Event::RefreshInlayHints = event {
1865 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1866 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1867 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1868 let focus_handle = editor.focus_handle(cx);
1869 if focus_handle.is_focused(cx) {
1870 let snapshot = buffer.read(cx).snapshot();
1871 for (range, snippet) in snippet_edits {
1872 let editor_range =
1873 language::range_from_lsp(*range).to_offset(&snapshot);
1874 editor
1875 .insert_snippet(&[editor_range], snippet.clone(), cx)
1876 .ok();
1877 }
1878 }
1879 }
1880 }
1881 }));
1882 if let Some(task_inventory) = project
1883 .read(cx)
1884 .task_store()
1885 .read(cx)
1886 .task_inventory()
1887 .cloned()
1888 {
1889 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1890 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1891 }));
1892 }
1893 }
1894 }
1895
1896 let inlay_hint_settings = inlay_hint_settings(
1897 selections.newest_anchor().head(),
1898 &buffer.read(cx).snapshot(cx),
1899 cx,
1900 );
1901 let focus_handle = cx.focus_handle();
1902 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1903 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1904 .detach();
1905 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1906 .detach();
1907 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1908
1909 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1910 Some(false)
1911 } else {
1912 None
1913 };
1914
1915 let mut code_action_providers = Vec::new();
1916 if let Some(project) = project.clone() {
1917 code_action_providers.push(Arc::new(project) as Arc<_>);
1918 }
1919
1920 let mut this = Self {
1921 focus_handle,
1922 show_cursor_when_unfocused: false,
1923 last_focused_descendant: None,
1924 buffer: buffer.clone(),
1925 display_map: display_map.clone(),
1926 selections,
1927 scroll_manager: ScrollManager::new(cx),
1928 columnar_selection_tail: None,
1929 add_selections_state: None,
1930 select_next_state: None,
1931 select_prev_state: None,
1932 selection_history: Default::default(),
1933 autoclose_regions: Default::default(),
1934 snippet_stack: Default::default(),
1935 select_larger_syntax_node_stack: Vec::new(),
1936 ime_transaction: Default::default(),
1937 active_diagnostics: None,
1938 soft_wrap_mode_override,
1939 completion_provider: project.clone().map(|project| Box::new(project) as _),
1940 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1941 project,
1942 blink_manager: blink_manager.clone(),
1943 show_local_selections: true,
1944 mode,
1945 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1946 show_gutter: mode == EditorMode::Full,
1947 show_line_numbers: None,
1948 use_relative_line_numbers: None,
1949 show_git_diff_gutter: None,
1950 show_code_actions: None,
1951 show_runnables: None,
1952 show_wrap_guides: None,
1953 show_indent_guides,
1954 placeholder_text: None,
1955 highlight_order: 0,
1956 highlighted_rows: HashMap::default(),
1957 background_highlights: Default::default(),
1958 gutter_highlights: TreeMap::default(),
1959 scrollbar_marker_state: ScrollbarMarkerState::default(),
1960 active_indent_guides_state: ActiveIndentGuidesState::default(),
1961 nav_history: None,
1962 context_menu: RwLock::new(None),
1963 mouse_context_menu: None,
1964 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1965 completion_tasks: Default::default(),
1966 signature_help_state: SignatureHelpState::default(),
1967 auto_signature_help: None,
1968 find_all_references_task_sources: Vec::new(),
1969 next_completion_id: 0,
1970 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1971 next_inlay_id: 0,
1972 code_action_providers,
1973 available_code_actions: Default::default(),
1974 code_actions_task: Default::default(),
1975 document_highlights_task: Default::default(),
1976 linked_editing_range_task: Default::default(),
1977 pending_rename: Default::default(),
1978 searchable: true,
1979 cursor_shape: EditorSettings::get_global(cx)
1980 .cursor_shape
1981 .unwrap_or_default(),
1982 current_line_highlight: None,
1983 autoindent_mode: Some(AutoindentMode::EachLine),
1984 collapse_matches: false,
1985 workspace: None,
1986 input_enabled: true,
1987 use_modal_editing: mode == EditorMode::Full,
1988 read_only: false,
1989 use_autoclose: true,
1990 use_auto_surround: true,
1991 auto_replace_emoji_shortcode: false,
1992 leader_peer_id: None,
1993 remote_id: None,
1994 hover_state: Default::default(),
1995 hovered_link_state: Default::default(),
1996 inline_completion_provider: None,
1997 active_inline_completion: None,
1998 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1999 expanded_hunks: ExpandedHunks::default(),
2000 gutter_hovered: false,
2001 pixel_position_of_newest_cursor: None,
2002 last_bounds: None,
2003 expect_bounds_change: None,
2004 gutter_dimensions: GutterDimensions::default(),
2005 style: None,
2006 show_cursor_names: false,
2007 hovered_cursors: Default::default(),
2008 next_editor_action_id: EditorActionId::default(),
2009 editor_actions: Rc::default(),
2010 show_inline_completions_override: None,
2011 enable_inline_completions: true,
2012 custom_context_menu: None,
2013 show_git_blame_gutter: false,
2014 show_git_blame_inline: false,
2015 show_selection_menu: None,
2016 show_git_blame_inline_delay_task: None,
2017 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2018 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2019 .session
2020 .restore_unsaved_buffers,
2021 blame: None,
2022 blame_subscription: None,
2023 file_header_size,
2024 tasks: Default::default(),
2025 _subscriptions: vec![
2026 cx.observe(&buffer, Self::on_buffer_changed),
2027 cx.subscribe(&buffer, Self::on_buffer_event),
2028 cx.observe(&display_map, Self::on_display_map_changed),
2029 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2030 cx.observe_global::<SettingsStore>(Self::settings_changed),
2031 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2032 cx.observe_window_activation(|editor, cx| {
2033 let active = cx.is_window_active();
2034 editor.blink_manager.update(cx, |blink_manager, cx| {
2035 if active {
2036 blink_manager.enable(cx);
2037 } else {
2038 blink_manager.disable(cx);
2039 }
2040 });
2041 }),
2042 ],
2043 tasks_update_task: None,
2044 linked_edit_ranges: Default::default(),
2045 previous_search_ranges: None,
2046 breadcrumb_header: None,
2047 focused_block: None,
2048 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2049 addons: HashMap::default(),
2050 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2051 };
2052 this.tasks_update_task = Some(this.refresh_runnables(cx));
2053 this._subscriptions.extend(project_subscriptions);
2054
2055 this.end_selection(cx);
2056 this.scroll_manager.show_scrollbar(cx);
2057
2058 if mode == EditorMode::Full {
2059 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2060 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2061
2062 if this.git_blame_inline_enabled {
2063 this.git_blame_inline_enabled = true;
2064 this.start_git_blame_inline(false, cx);
2065 }
2066 }
2067
2068 this.report_editor_event("open", None, cx);
2069 this
2070 }
2071
2072 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2073 self.mouse_context_menu
2074 .as_ref()
2075 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2076 }
2077
2078 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2079 let mut key_context = KeyContext::new_with_defaults();
2080 key_context.add("Editor");
2081 let mode = match self.mode {
2082 EditorMode::SingleLine { .. } => "single_line",
2083 EditorMode::AutoHeight { .. } => "auto_height",
2084 EditorMode::Full => "full",
2085 };
2086
2087 if EditorSettings::jupyter_enabled(cx) {
2088 key_context.add("jupyter");
2089 }
2090
2091 key_context.set("mode", mode);
2092 if self.pending_rename.is_some() {
2093 key_context.add("renaming");
2094 }
2095 if self.context_menu_visible() {
2096 match self.context_menu.read().as_ref() {
2097 Some(ContextMenu::Completions(_)) => {
2098 key_context.add("menu");
2099 key_context.add("showing_completions")
2100 }
2101 Some(ContextMenu::CodeActions(_)) => {
2102 key_context.add("menu");
2103 key_context.add("showing_code_actions")
2104 }
2105 None => {}
2106 }
2107 }
2108
2109 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2110 if !self.focus_handle(cx).contains_focused(cx)
2111 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2112 {
2113 for addon in self.addons.values() {
2114 addon.extend_key_context(&mut key_context, cx)
2115 }
2116 }
2117
2118 if let Some(extension) = self
2119 .buffer
2120 .read(cx)
2121 .as_singleton()
2122 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2123 {
2124 key_context.set("extension", extension.to_string());
2125 }
2126
2127 if self.has_active_inline_completion(cx) {
2128 key_context.add("copilot_suggestion");
2129 key_context.add("inline_completion");
2130 }
2131
2132 key_context
2133 }
2134
2135 pub fn new_file(
2136 workspace: &mut Workspace,
2137 _: &workspace::NewFile,
2138 cx: &mut ViewContext<Workspace>,
2139 ) {
2140 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2141 "Failed to create buffer",
2142 cx,
2143 |e, _| match e.error_code() {
2144 ErrorCode::RemoteUpgradeRequired => Some(format!(
2145 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2146 e.error_tag("required").unwrap_or("the latest version")
2147 )),
2148 _ => None,
2149 },
2150 );
2151 }
2152
2153 pub fn new_in_workspace(
2154 workspace: &mut Workspace,
2155 cx: &mut ViewContext<Workspace>,
2156 ) -> Task<Result<View<Editor>>> {
2157 let project = workspace.project().clone();
2158 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2159
2160 cx.spawn(|workspace, mut cx| async move {
2161 let buffer = create.await?;
2162 workspace.update(&mut cx, |workspace, cx| {
2163 let editor =
2164 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2165 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2166 editor
2167 })
2168 })
2169 }
2170
2171 fn new_file_vertical(
2172 workspace: &mut Workspace,
2173 _: &workspace::NewFileSplitVertical,
2174 cx: &mut ViewContext<Workspace>,
2175 ) {
2176 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2177 }
2178
2179 fn new_file_horizontal(
2180 workspace: &mut Workspace,
2181 _: &workspace::NewFileSplitHorizontal,
2182 cx: &mut ViewContext<Workspace>,
2183 ) {
2184 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2185 }
2186
2187 fn new_file_in_direction(
2188 workspace: &mut Workspace,
2189 direction: SplitDirection,
2190 cx: &mut ViewContext<Workspace>,
2191 ) {
2192 let project = workspace.project().clone();
2193 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2194
2195 cx.spawn(|workspace, mut cx| async move {
2196 let buffer = create.await?;
2197 workspace.update(&mut cx, move |workspace, cx| {
2198 workspace.split_item(
2199 direction,
2200 Box::new(
2201 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2202 ),
2203 cx,
2204 )
2205 })?;
2206 anyhow::Ok(())
2207 })
2208 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2209 ErrorCode::RemoteUpgradeRequired => Some(format!(
2210 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2211 e.error_tag("required").unwrap_or("the latest version")
2212 )),
2213 _ => None,
2214 });
2215 }
2216
2217 pub fn leader_peer_id(&self) -> Option<PeerId> {
2218 self.leader_peer_id
2219 }
2220
2221 pub fn buffer(&self) -> &Model<MultiBuffer> {
2222 &self.buffer
2223 }
2224
2225 pub fn workspace(&self) -> Option<View<Workspace>> {
2226 self.workspace.as_ref()?.0.upgrade()
2227 }
2228
2229 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2230 self.buffer().read(cx).title(cx)
2231 }
2232
2233 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2234 let git_blame_gutter_max_author_length = self
2235 .render_git_blame_gutter(cx)
2236 .then(|| {
2237 if let Some(blame) = self.blame.as_ref() {
2238 let max_author_length =
2239 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2240 Some(max_author_length)
2241 } else {
2242 None
2243 }
2244 })
2245 .flatten();
2246
2247 EditorSnapshot {
2248 mode: self.mode,
2249 show_gutter: self.show_gutter,
2250 show_line_numbers: self.show_line_numbers,
2251 show_git_diff_gutter: self.show_git_diff_gutter,
2252 show_code_actions: self.show_code_actions,
2253 show_runnables: self.show_runnables,
2254 git_blame_gutter_max_author_length,
2255 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2256 scroll_anchor: self.scroll_manager.anchor(),
2257 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2258 placeholder_text: self.placeholder_text.clone(),
2259 is_focused: self.focus_handle.is_focused(cx),
2260 current_line_highlight: self
2261 .current_line_highlight
2262 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2263 gutter_hovered: self.gutter_hovered,
2264 }
2265 }
2266
2267 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2268 self.buffer.read(cx).language_at(point, cx)
2269 }
2270
2271 pub fn file_at<T: ToOffset>(
2272 &self,
2273 point: T,
2274 cx: &AppContext,
2275 ) -> Option<Arc<dyn language::File>> {
2276 self.buffer.read(cx).read(cx).file_at(point).cloned()
2277 }
2278
2279 pub fn active_excerpt(
2280 &self,
2281 cx: &AppContext,
2282 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2283 self.buffer
2284 .read(cx)
2285 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2286 }
2287
2288 pub fn mode(&self) -> EditorMode {
2289 self.mode
2290 }
2291
2292 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2293 self.collaboration_hub.as_deref()
2294 }
2295
2296 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2297 self.collaboration_hub = Some(hub);
2298 }
2299
2300 pub fn set_custom_context_menu(
2301 &mut self,
2302 f: impl 'static
2303 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2304 ) {
2305 self.custom_context_menu = Some(Box::new(f))
2306 }
2307
2308 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2309 self.completion_provider = Some(provider);
2310 }
2311
2312 pub fn set_inline_completion_provider<T>(
2313 &mut self,
2314 provider: Option<Model<T>>,
2315 cx: &mut ViewContext<Self>,
2316 ) where
2317 T: InlineCompletionProvider,
2318 {
2319 self.inline_completion_provider =
2320 provider.map(|provider| RegisteredInlineCompletionProvider {
2321 _subscription: cx.observe(&provider, |this, _, cx| {
2322 if this.focus_handle.is_focused(cx) {
2323 this.update_visible_inline_completion(cx);
2324 }
2325 }),
2326 provider: Arc::new(provider),
2327 });
2328 self.refresh_inline_completion(false, false, cx);
2329 }
2330
2331 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2332 self.placeholder_text.as_deref()
2333 }
2334
2335 pub fn set_placeholder_text(
2336 &mut self,
2337 placeholder_text: impl Into<Arc<str>>,
2338 cx: &mut ViewContext<Self>,
2339 ) {
2340 let placeholder_text = Some(placeholder_text.into());
2341 if self.placeholder_text != placeholder_text {
2342 self.placeholder_text = placeholder_text;
2343 cx.notify();
2344 }
2345 }
2346
2347 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2348 self.cursor_shape = cursor_shape;
2349
2350 // Disrupt blink for immediate user feedback that the cursor shape has changed
2351 self.blink_manager.update(cx, BlinkManager::show_cursor);
2352
2353 cx.notify();
2354 }
2355
2356 pub fn set_current_line_highlight(
2357 &mut self,
2358 current_line_highlight: Option<CurrentLineHighlight>,
2359 ) {
2360 self.current_line_highlight = current_line_highlight;
2361 }
2362
2363 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2364 self.collapse_matches = collapse_matches;
2365 }
2366
2367 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2368 if self.collapse_matches {
2369 return range.start..range.start;
2370 }
2371 range.clone()
2372 }
2373
2374 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2375 if self.display_map.read(cx).clip_at_line_ends != clip {
2376 self.display_map
2377 .update(cx, |map, _| map.clip_at_line_ends = clip);
2378 }
2379 }
2380
2381 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2382 self.input_enabled = input_enabled;
2383 }
2384
2385 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2386 self.enable_inline_completions = enabled;
2387 }
2388
2389 pub fn set_autoindent(&mut self, autoindent: bool) {
2390 if autoindent {
2391 self.autoindent_mode = Some(AutoindentMode::EachLine);
2392 } else {
2393 self.autoindent_mode = None;
2394 }
2395 }
2396
2397 pub fn read_only(&self, cx: &AppContext) -> bool {
2398 self.read_only || self.buffer.read(cx).read_only()
2399 }
2400
2401 pub fn set_read_only(&mut self, read_only: bool) {
2402 self.read_only = read_only;
2403 }
2404
2405 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2406 self.use_autoclose = autoclose;
2407 }
2408
2409 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2410 self.use_auto_surround = auto_surround;
2411 }
2412
2413 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2414 self.auto_replace_emoji_shortcode = auto_replace;
2415 }
2416
2417 pub fn toggle_inline_completions(
2418 &mut self,
2419 _: &ToggleInlineCompletions,
2420 cx: &mut ViewContext<Self>,
2421 ) {
2422 if self.show_inline_completions_override.is_some() {
2423 self.set_show_inline_completions(None, cx);
2424 } else {
2425 let cursor = self.selections.newest_anchor().head();
2426 if let Some((buffer, cursor_buffer_position)) =
2427 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2428 {
2429 let show_inline_completions =
2430 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2431 self.set_show_inline_completions(Some(show_inline_completions), cx);
2432 }
2433 }
2434 }
2435
2436 pub fn set_show_inline_completions(
2437 &mut self,
2438 show_inline_completions: Option<bool>,
2439 cx: &mut ViewContext<Self>,
2440 ) {
2441 self.show_inline_completions_override = show_inline_completions;
2442 self.refresh_inline_completion(false, true, cx);
2443 }
2444
2445 fn should_show_inline_completions(
2446 &self,
2447 buffer: &Model<Buffer>,
2448 buffer_position: language::Anchor,
2449 cx: &AppContext,
2450 ) -> bool {
2451 if let Some(provider) = self.inline_completion_provider() {
2452 if let Some(show_inline_completions) = self.show_inline_completions_override {
2453 show_inline_completions
2454 } else {
2455 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2456 }
2457 } else {
2458 false
2459 }
2460 }
2461
2462 pub fn set_use_modal_editing(&mut self, to: bool) {
2463 self.use_modal_editing = to;
2464 }
2465
2466 pub fn use_modal_editing(&self) -> bool {
2467 self.use_modal_editing
2468 }
2469
2470 fn selections_did_change(
2471 &mut self,
2472 local: bool,
2473 old_cursor_position: &Anchor,
2474 show_completions: bool,
2475 cx: &mut ViewContext<Self>,
2476 ) {
2477 cx.invalidate_character_coordinates();
2478
2479 // Copy selections to primary selection buffer
2480 #[cfg(target_os = "linux")]
2481 if local {
2482 let selections = self.selections.all::<usize>(cx);
2483 let buffer_handle = self.buffer.read(cx).read(cx);
2484
2485 let mut text = String::new();
2486 for (index, selection) in selections.iter().enumerate() {
2487 let text_for_selection = buffer_handle
2488 .text_for_range(selection.start..selection.end)
2489 .collect::<String>();
2490
2491 text.push_str(&text_for_selection);
2492 if index != selections.len() - 1 {
2493 text.push('\n');
2494 }
2495 }
2496
2497 if !text.is_empty() {
2498 cx.write_to_primary(ClipboardItem::new_string(text));
2499 }
2500 }
2501
2502 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2503 self.buffer.update(cx, |buffer, cx| {
2504 buffer.set_active_selections(
2505 &self.selections.disjoint_anchors(),
2506 self.selections.line_mode,
2507 self.cursor_shape,
2508 cx,
2509 )
2510 });
2511 }
2512 let display_map = self
2513 .display_map
2514 .update(cx, |display_map, cx| display_map.snapshot(cx));
2515 let buffer = &display_map.buffer_snapshot;
2516 self.add_selections_state = None;
2517 self.select_next_state = None;
2518 self.select_prev_state = None;
2519 self.select_larger_syntax_node_stack.clear();
2520 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2521 self.snippet_stack
2522 .invalidate(&self.selections.disjoint_anchors(), buffer);
2523 self.take_rename(false, cx);
2524
2525 let new_cursor_position = self.selections.newest_anchor().head();
2526
2527 self.push_to_nav_history(
2528 *old_cursor_position,
2529 Some(new_cursor_position.to_point(buffer)),
2530 cx,
2531 );
2532
2533 if local {
2534 let new_cursor_position = self.selections.newest_anchor().head();
2535 let mut context_menu = self.context_menu.write();
2536 let completion_menu = match context_menu.as_ref() {
2537 Some(ContextMenu::Completions(menu)) => Some(menu),
2538
2539 _ => {
2540 *context_menu = None;
2541 None
2542 }
2543 };
2544
2545 if let Some(completion_menu) = completion_menu {
2546 let cursor_position = new_cursor_position.to_offset(buffer);
2547 let (word_range, kind) =
2548 buffer.surrounding_word(completion_menu.initial_position, true);
2549 if kind == Some(CharKind::Word)
2550 && word_range.to_inclusive().contains(&cursor_position)
2551 {
2552 let mut completion_menu = completion_menu.clone();
2553 drop(context_menu);
2554
2555 let query = Self::completion_query(buffer, cursor_position);
2556 cx.spawn(move |this, mut cx| async move {
2557 completion_menu
2558 .filter(query.as_deref(), cx.background_executor().clone())
2559 .await;
2560
2561 this.update(&mut cx, |this, cx| {
2562 let mut context_menu = this.context_menu.write();
2563 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2564 return;
2565 };
2566
2567 if menu.id > completion_menu.id {
2568 return;
2569 }
2570
2571 *context_menu = Some(ContextMenu::Completions(completion_menu));
2572 drop(context_menu);
2573 cx.notify();
2574 })
2575 })
2576 .detach();
2577
2578 if show_completions {
2579 self.show_completions(&ShowCompletions { trigger: None }, cx);
2580 }
2581 } else {
2582 drop(context_menu);
2583 self.hide_context_menu(cx);
2584 }
2585 } else {
2586 drop(context_menu);
2587 }
2588
2589 hide_hover(self, cx);
2590
2591 if old_cursor_position.to_display_point(&display_map).row()
2592 != new_cursor_position.to_display_point(&display_map).row()
2593 {
2594 self.available_code_actions.take();
2595 }
2596 self.refresh_code_actions(cx);
2597 self.refresh_document_highlights(cx);
2598 refresh_matching_bracket_highlights(self, cx);
2599 self.discard_inline_completion(false, cx);
2600 linked_editing_ranges::refresh_linked_ranges(self, cx);
2601 if self.git_blame_inline_enabled {
2602 self.start_inline_blame_timer(cx);
2603 }
2604 }
2605
2606 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2607 cx.emit(EditorEvent::SelectionsChanged { local });
2608
2609 if self.selections.disjoint_anchors().len() == 1 {
2610 cx.emit(SearchEvent::ActiveMatchChanged)
2611 }
2612 cx.notify();
2613 }
2614
2615 pub fn change_selections<R>(
2616 &mut self,
2617 autoscroll: Option<Autoscroll>,
2618 cx: &mut ViewContext<Self>,
2619 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2620 ) -> R {
2621 self.change_selections_inner(autoscroll, true, cx, change)
2622 }
2623
2624 pub fn change_selections_inner<R>(
2625 &mut self,
2626 autoscroll: Option<Autoscroll>,
2627 request_completions: bool,
2628 cx: &mut ViewContext<Self>,
2629 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2630 ) -> R {
2631 let old_cursor_position = self.selections.newest_anchor().head();
2632 self.push_to_selection_history();
2633
2634 let (changed, result) = self.selections.change_with(cx, change);
2635
2636 if changed {
2637 if let Some(autoscroll) = autoscroll {
2638 self.request_autoscroll(autoscroll, cx);
2639 }
2640 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2641
2642 if self.should_open_signature_help_automatically(
2643 &old_cursor_position,
2644 self.signature_help_state.backspace_pressed(),
2645 cx,
2646 ) {
2647 self.show_signature_help(&ShowSignatureHelp, cx);
2648 }
2649 self.signature_help_state.set_backspace_pressed(false);
2650 }
2651
2652 result
2653 }
2654
2655 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2656 where
2657 I: IntoIterator<Item = (Range<S>, T)>,
2658 S: ToOffset,
2659 T: Into<Arc<str>>,
2660 {
2661 if self.read_only(cx) {
2662 return;
2663 }
2664
2665 self.buffer
2666 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2667 }
2668
2669 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2670 where
2671 I: IntoIterator<Item = (Range<S>, T)>,
2672 S: ToOffset,
2673 T: Into<Arc<str>>,
2674 {
2675 if self.read_only(cx) {
2676 return;
2677 }
2678
2679 self.buffer.update(cx, |buffer, cx| {
2680 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2681 });
2682 }
2683
2684 pub fn edit_with_block_indent<I, S, T>(
2685 &mut self,
2686 edits: I,
2687 original_indent_columns: Vec<u32>,
2688 cx: &mut ViewContext<Self>,
2689 ) where
2690 I: IntoIterator<Item = (Range<S>, T)>,
2691 S: ToOffset,
2692 T: Into<Arc<str>>,
2693 {
2694 if self.read_only(cx) {
2695 return;
2696 }
2697
2698 self.buffer.update(cx, |buffer, cx| {
2699 buffer.edit(
2700 edits,
2701 Some(AutoindentMode::Block {
2702 original_indent_columns,
2703 }),
2704 cx,
2705 )
2706 });
2707 }
2708
2709 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2710 self.hide_context_menu(cx);
2711
2712 match phase {
2713 SelectPhase::Begin {
2714 position,
2715 add,
2716 click_count,
2717 } => self.begin_selection(position, add, click_count, cx),
2718 SelectPhase::BeginColumnar {
2719 position,
2720 goal_column,
2721 reset,
2722 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2723 SelectPhase::Extend {
2724 position,
2725 click_count,
2726 } => self.extend_selection(position, click_count, cx),
2727 SelectPhase::Update {
2728 position,
2729 goal_column,
2730 scroll_delta,
2731 } => self.update_selection(position, goal_column, scroll_delta, cx),
2732 SelectPhase::End => self.end_selection(cx),
2733 }
2734 }
2735
2736 fn extend_selection(
2737 &mut self,
2738 position: DisplayPoint,
2739 click_count: usize,
2740 cx: &mut ViewContext<Self>,
2741 ) {
2742 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2743 let tail = self.selections.newest::<usize>(cx).tail();
2744 self.begin_selection(position, false, click_count, cx);
2745
2746 let position = position.to_offset(&display_map, Bias::Left);
2747 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2748
2749 let mut pending_selection = self
2750 .selections
2751 .pending_anchor()
2752 .expect("extend_selection not called with pending selection");
2753 if position >= tail {
2754 pending_selection.start = tail_anchor;
2755 } else {
2756 pending_selection.end = tail_anchor;
2757 pending_selection.reversed = true;
2758 }
2759
2760 let mut pending_mode = self.selections.pending_mode().unwrap();
2761 match &mut pending_mode {
2762 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2763 _ => {}
2764 }
2765
2766 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2767 s.set_pending(pending_selection, pending_mode)
2768 });
2769 }
2770
2771 fn begin_selection(
2772 &mut self,
2773 position: DisplayPoint,
2774 add: bool,
2775 click_count: usize,
2776 cx: &mut ViewContext<Self>,
2777 ) {
2778 if !self.focus_handle.is_focused(cx) {
2779 self.last_focused_descendant = None;
2780 cx.focus(&self.focus_handle);
2781 }
2782
2783 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2784 let buffer = &display_map.buffer_snapshot;
2785 let newest_selection = self.selections.newest_anchor().clone();
2786 let position = display_map.clip_point(position, Bias::Left);
2787
2788 let start;
2789 let end;
2790 let mode;
2791 let auto_scroll;
2792 match click_count {
2793 1 => {
2794 start = buffer.anchor_before(position.to_point(&display_map));
2795 end = start;
2796 mode = SelectMode::Character;
2797 auto_scroll = true;
2798 }
2799 2 => {
2800 let range = movement::surrounding_word(&display_map, position);
2801 start = buffer.anchor_before(range.start.to_point(&display_map));
2802 end = buffer.anchor_before(range.end.to_point(&display_map));
2803 mode = SelectMode::Word(start..end);
2804 auto_scroll = true;
2805 }
2806 3 => {
2807 let position = display_map
2808 .clip_point(position, Bias::Left)
2809 .to_point(&display_map);
2810 let line_start = display_map.prev_line_boundary(position).0;
2811 let next_line_start = buffer.clip_point(
2812 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2813 Bias::Left,
2814 );
2815 start = buffer.anchor_before(line_start);
2816 end = buffer.anchor_before(next_line_start);
2817 mode = SelectMode::Line(start..end);
2818 auto_scroll = true;
2819 }
2820 _ => {
2821 start = buffer.anchor_before(0);
2822 end = buffer.anchor_before(buffer.len());
2823 mode = SelectMode::All;
2824 auto_scroll = false;
2825 }
2826 }
2827
2828 let point_to_delete: Option<usize> = {
2829 let selected_points: Vec<Selection<Point>> =
2830 self.selections.disjoint_in_range(start..end, cx);
2831
2832 if !add || click_count > 1 {
2833 None
2834 } else if !selected_points.is_empty() {
2835 Some(selected_points[0].id)
2836 } else {
2837 let clicked_point_already_selected =
2838 self.selections.disjoint.iter().find(|selection| {
2839 selection.start.to_point(buffer) == start.to_point(buffer)
2840 || selection.end.to_point(buffer) == end.to_point(buffer)
2841 });
2842
2843 clicked_point_already_selected.map(|selection| selection.id)
2844 }
2845 };
2846
2847 let selections_count = self.selections.count();
2848
2849 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2850 if let Some(point_to_delete) = point_to_delete {
2851 s.delete(point_to_delete);
2852
2853 if selections_count == 1 {
2854 s.set_pending_anchor_range(start..end, mode);
2855 }
2856 } else {
2857 if !add {
2858 s.clear_disjoint();
2859 } else if click_count > 1 {
2860 s.delete(newest_selection.id)
2861 }
2862
2863 s.set_pending_anchor_range(start..end, mode);
2864 }
2865 });
2866 }
2867
2868 fn begin_columnar_selection(
2869 &mut self,
2870 position: DisplayPoint,
2871 goal_column: u32,
2872 reset: bool,
2873 cx: &mut ViewContext<Self>,
2874 ) {
2875 if !self.focus_handle.is_focused(cx) {
2876 self.last_focused_descendant = None;
2877 cx.focus(&self.focus_handle);
2878 }
2879
2880 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2881
2882 if reset {
2883 let pointer_position = display_map
2884 .buffer_snapshot
2885 .anchor_before(position.to_point(&display_map));
2886
2887 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2888 s.clear_disjoint();
2889 s.set_pending_anchor_range(
2890 pointer_position..pointer_position,
2891 SelectMode::Character,
2892 );
2893 });
2894 }
2895
2896 let tail = self.selections.newest::<Point>(cx).tail();
2897 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2898
2899 if !reset {
2900 self.select_columns(
2901 tail.to_display_point(&display_map),
2902 position,
2903 goal_column,
2904 &display_map,
2905 cx,
2906 );
2907 }
2908 }
2909
2910 fn update_selection(
2911 &mut self,
2912 position: DisplayPoint,
2913 goal_column: u32,
2914 scroll_delta: gpui::Point<f32>,
2915 cx: &mut ViewContext<Self>,
2916 ) {
2917 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2918
2919 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2920 let tail = tail.to_display_point(&display_map);
2921 self.select_columns(tail, position, goal_column, &display_map, cx);
2922 } else if let Some(mut pending) = self.selections.pending_anchor() {
2923 let buffer = self.buffer.read(cx).snapshot(cx);
2924 let head;
2925 let tail;
2926 let mode = self.selections.pending_mode().unwrap();
2927 match &mode {
2928 SelectMode::Character => {
2929 head = position.to_point(&display_map);
2930 tail = pending.tail().to_point(&buffer);
2931 }
2932 SelectMode::Word(original_range) => {
2933 let original_display_range = original_range.start.to_display_point(&display_map)
2934 ..original_range.end.to_display_point(&display_map);
2935 let original_buffer_range = original_display_range.start.to_point(&display_map)
2936 ..original_display_range.end.to_point(&display_map);
2937 if movement::is_inside_word(&display_map, position)
2938 || original_display_range.contains(&position)
2939 {
2940 let word_range = movement::surrounding_word(&display_map, position);
2941 if word_range.start < original_display_range.start {
2942 head = word_range.start.to_point(&display_map);
2943 } else {
2944 head = word_range.end.to_point(&display_map);
2945 }
2946 } else {
2947 head = position.to_point(&display_map);
2948 }
2949
2950 if head <= original_buffer_range.start {
2951 tail = original_buffer_range.end;
2952 } else {
2953 tail = original_buffer_range.start;
2954 }
2955 }
2956 SelectMode::Line(original_range) => {
2957 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2958
2959 let position = display_map
2960 .clip_point(position, Bias::Left)
2961 .to_point(&display_map);
2962 let line_start = display_map.prev_line_boundary(position).0;
2963 let next_line_start = buffer.clip_point(
2964 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2965 Bias::Left,
2966 );
2967
2968 if line_start < original_range.start {
2969 head = line_start
2970 } else {
2971 head = next_line_start
2972 }
2973
2974 if head <= original_range.start {
2975 tail = original_range.end;
2976 } else {
2977 tail = original_range.start;
2978 }
2979 }
2980 SelectMode::All => {
2981 return;
2982 }
2983 };
2984
2985 if head < tail {
2986 pending.start = buffer.anchor_before(head);
2987 pending.end = buffer.anchor_before(tail);
2988 pending.reversed = true;
2989 } else {
2990 pending.start = buffer.anchor_before(tail);
2991 pending.end = buffer.anchor_before(head);
2992 pending.reversed = false;
2993 }
2994
2995 self.change_selections(None, cx, |s| {
2996 s.set_pending(pending, mode);
2997 });
2998 } else {
2999 log::error!("update_selection dispatched with no pending selection");
3000 return;
3001 }
3002
3003 self.apply_scroll_delta(scroll_delta, cx);
3004 cx.notify();
3005 }
3006
3007 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3008 self.columnar_selection_tail.take();
3009 if self.selections.pending_anchor().is_some() {
3010 let selections = self.selections.all::<usize>(cx);
3011 self.change_selections(None, cx, |s| {
3012 s.select(selections);
3013 s.clear_pending();
3014 });
3015 }
3016 }
3017
3018 fn select_columns(
3019 &mut self,
3020 tail: DisplayPoint,
3021 head: DisplayPoint,
3022 goal_column: u32,
3023 display_map: &DisplaySnapshot,
3024 cx: &mut ViewContext<Self>,
3025 ) {
3026 let start_row = cmp::min(tail.row(), head.row());
3027 let end_row = cmp::max(tail.row(), head.row());
3028 let start_column = cmp::min(tail.column(), goal_column);
3029 let end_column = cmp::max(tail.column(), goal_column);
3030 let reversed = start_column < tail.column();
3031
3032 let selection_ranges = (start_row.0..=end_row.0)
3033 .map(DisplayRow)
3034 .filter_map(|row| {
3035 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3036 let start = display_map
3037 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3038 .to_point(display_map);
3039 let end = display_map
3040 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3041 .to_point(display_map);
3042 if reversed {
3043 Some(end..start)
3044 } else {
3045 Some(start..end)
3046 }
3047 } else {
3048 None
3049 }
3050 })
3051 .collect::<Vec<_>>();
3052
3053 self.change_selections(None, cx, |s| {
3054 s.select_ranges(selection_ranges);
3055 });
3056 cx.notify();
3057 }
3058
3059 pub fn has_pending_nonempty_selection(&self) -> bool {
3060 let pending_nonempty_selection = match self.selections.pending_anchor() {
3061 Some(Selection { start, end, .. }) => start != end,
3062 None => false,
3063 };
3064
3065 pending_nonempty_selection
3066 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3067 }
3068
3069 pub fn has_pending_selection(&self) -> bool {
3070 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3071 }
3072
3073 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3074 if self.clear_expanded_diff_hunks(cx) {
3075 cx.notify();
3076 return;
3077 }
3078 if self.dismiss_menus_and_popups(true, cx) {
3079 return;
3080 }
3081
3082 if self.mode == EditorMode::Full
3083 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3084 {
3085 return;
3086 }
3087
3088 cx.propagate();
3089 }
3090
3091 pub fn dismiss_menus_and_popups(
3092 &mut self,
3093 should_report_inline_completion_event: bool,
3094 cx: &mut ViewContext<Self>,
3095 ) -> bool {
3096 if self.take_rename(false, cx).is_some() {
3097 return true;
3098 }
3099
3100 if hide_hover(self, cx) {
3101 return true;
3102 }
3103
3104 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3105 return true;
3106 }
3107
3108 if self.hide_context_menu(cx).is_some() {
3109 return true;
3110 }
3111
3112 if self.mouse_context_menu.take().is_some() {
3113 return true;
3114 }
3115
3116 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3117 return true;
3118 }
3119
3120 if self.snippet_stack.pop().is_some() {
3121 return true;
3122 }
3123
3124 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3125 self.dismiss_diagnostics(cx);
3126 return true;
3127 }
3128
3129 false
3130 }
3131
3132 fn linked_editing_ranges_for(
3133 &self,
3134 selection: Range<text::Anchor>,
3135 cx: &AppContext,
3136 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3137 if self.linked_edit_ranges.is_empty() {
3138 return None;
3139 }
3140 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3141 selection.end.buffer_id.and_then(|end_buffer_id| {
3142 if selection.start.buffer_id != Some(end_buffer_id) {
3143 return None;
3144 }
3145 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3146 let snapshot = buffer.read(cx).snapshot();
3147 self.linked_edit_ranges
3148 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3149 .map(|ranges| (ranges, snapshot, buffer))
3150 })?;
3151 use text::ToOffset as TO;
3152 // find offset from the start of current range to current cursor position
3153 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3154
3155 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3156 let start_difference = start_offset - start_byte_offset;
3157 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3158 let end_difference = end_offset - start_byte_offset;
3159 // Current range has associated linked ranges.
3160 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3161 for range in linked_ranges.iter() {
3162 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3163 let end_offset = start_offset + end_difference;
3164 let start_offset = start_offset + start_difference;
3165 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3166 continue;
3167 }
3168 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3169 if s.start.buffer_id != selection.start.buffer_id
3170 || s.end.buffer_id != selection.end.buffer_id
3171 {
3172 return false;
3173 }
3174 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3175 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3176 }) {
3177 continue;
3178 }
3179 let start = buffer_snapshot.anchor_after(start_offset);
3180 let end = buffer_snapshot.anchor_after(end_offset);
3181 linked_edits
3182 .entry(buffer.clone())
3183 .or_default()
3184 .push(start..end);
3185 }
3186 Some(linked_edits)
3187 }
3188
3189 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3190 let text: Arc<str> = text.into();
3191
3192 if self.read_only(cx) {
3193 return;
3194 }
3195
3196 let selections = self.selections.all_adjusted(cx);
3197 let mut bracket_inserted = false;
3198 let mut edits = Vec::new();
3199 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3200 let mut new_selections = Vec::with_capacity(selections.len());
3201 let mut new_autoclose_regions = Vec::new();
3202 let snapshot = self.buffer.read(cx).read(cx);
3203
3204 for (selection, autoclose_region) in
3205 self.selections_with_autoclose_regions(selections, &snapshot)
3206 {
3207 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3208 // Determine if the inserted text matches the opening or closing
3209 // bracket of any of this language's bracket pairs.
3210 let mut bracket_pair = None;
3211 let mut is_bracket_pair_start = false;
3212 let mut is_bracket_pair_end = false;
3213 if !text.is_empty() {
3214 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3215 // and they are removing the character that triggered IME popup.
3216 for (pair, enabled) in scope.brackets() {
3217 if !pair.close && !pair.surround {
3218 continue;
3219 }
3220
3221 if enabled && pair.start.ends_with(text.as_ref()) {
3222 bracket_pair = Some(pair.clone());
3223 is_bracket_pair_start = true;
3224 break;
3225 }
3226 if pair.end.as_str() == text.as_ref() {
3227 bracket_pair = Some(pair.clone());
3228 is_bracket_pair_end = true;
3229 break;
3230 }
3231 }
3232 }
3233
3234 if let Some(bracket_pair) = bracket_pair {
3235 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3236 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3237 let auto_surround =
3238 self.use_auto_surround && snapshot_settings.use_auto_surround;
3239 if selection.is_empty() {
3240 if is_bracket_pair_start {
3241 let prefix_len = bracket_pair.start.len() - text.len();
3242
3243 // If the inserted text is a suffix of an opening bracket and the
3244 // selection is preceded by the rest of the opening bracket, then
3245 // insert the closing bracket.
3246 let following_text_allows_autoclose = snapshot
3247 .chars_at(selection.start)
3248 .next()
3249 .map_or(true, |c| scope.should_autoclose_before(c));
3250 let preceding_text_matches_prefix = prefix_len == 0
3251 || (selection.start.column >= (prefix_len as u32)
3252 && snapshot.contains_str_at(
3253 Point::new(
3254 selection.start.row,
3255 selection.start.column - (prefix_len as u32),
3256 ),
3257 &bracket_pair.start[..prefix_len],
3258 ));
3259
3260 if autoclose
3261 && bracket_pair.close
3262 && following_text_allows_autoclose
3263 && preceding_text_matches_prefix
3264 {
3265 let anchor = snapshot.anchor_before(selection.end);
3266 new_selections.push((selection.map(|_| anchor), text.len()));
3267 new_autoclose_regions.push((
3268 anchor,
3269 text.len(),
3270 selection.id,
3271 bracket_pair.clone(),
3272 ));
3273 edits.push((
3274 selection.range(),
3275 format!("{}{}", text, bracket_pair.end).into(),
3276 ));
3277 bracket_inserted = true;
3278 continue;
3279 }
3280 }
3281
3282 if let Some(region) = autoclose_region {
3283 // If the selection is followed by an auto-inserted closing bracket,
3284 // then don't insert that closing bracket again; just move the selection
3285 // past the closing bracket.
3286 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3287 && text.as_ref() == region.pair.end.as_str();
3288 if should_skip {
3289 let anchor = snapshot.anchor_after(selection.end);
3290 new_selections
3291 .push((selection.map(|_| anchor), region.pair.end.len()));
3292 continue;
3293 }
3294 }
3295
3296 let always_treat_brackets_as_autoclosed = snapshot
3297 .settings_at(selection.start, cx)
3298 .always_treat_brackets_as_autoclosed;
3299 if always_treat_brackets_as_autoclosed
3300 && is_bracket_pair_end
3301 && snapshot.contains_str_at(selection.end, text.as_ref())
3302 {
3303 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3304 // and the inserted text is a closing bracket and the selection is followed
3305 // by the closing bracket then move the selection past the closing bracket.
3306 let anchor = snapshot.anchor_after(selection.end);
3307 new_selections.push((selection.map(|_| anchor), text.len()));
3308 continue;
3309 }
3310 }
3311 // If an opening bracket is 1 character long and is typed while
3312 // text is selected, then surround that text with the bracket pair.
3313 else if auto_surround
3314 && bracket_pair.surround
3315 && is_bracket_pair_start
3316 && bracket_pair.start.chars().count() == 1
3317 {
3318 edits.push((selection.start..selection.start, text.clone()));
3319 edits.push((
3320 selection.end..selection.end,
3321 bracket_pair.end.as_str().into(),
3322 ));
3323 bracket_inserted = true;
3324 new_selections.push((
3325 Selection {
3326 id: selection.id,
3327 start: snapshot.anchor_after(selection.start),
3328 end: snapshot.anchor_before(selection.end),
3329 reversed: selection.reversed,
3330 goal: selection.goal,
3331 },
3332 0,
3333 ));
3334 continue;
3335 }
3336 }
3337 }
3338
3339 if self.auto_replace_emoji_shortcode
3340 && selection.is_empty()
3341 && text.as_ref().ends_with(':')
3342 {
3343 if let Some(possible_emoji_short_code) =
3344 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3345 {
3346 if !possible_emoji_short_code.is_empty() {
3347 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3348 let emoji_shortcode_start = Point::new(
3349 selection.start.row,
3350 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3351 );
3352
3353 // Remove shortcode from buffer
3354 edits.push((
3355 emoji_shortcode_start..selection.start,
3356 "".to_string().into(),
3357 ));
3358 new_selections.push((
3359 Selection {
3360 id: selection.id,
3361 start: snapshot.anchor_after(emoji_shortcode_start),
3362 end: snapshot.anchor_before(selection.start),
3363 reversed: selection.reversed,
3364 goal: selection.goal,
3365 },
3366 0,
3367 ));
3368
3369 // Insert emoji
3370 let selection_start_anchor = snapshot.anchor_after(selection.start);
3371 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3372 edits.push((selection.start..selection.end, emoji.to_string().into()));
3373
3374 continue;
3375 }
3376 }
3377 }
3378 }
3379
3380 // If not handling any auto-close operation, then just replace the selected
3381 // text with the given input and move the selection to the end of the
3382 // newly inserted text.
3383 let anchor = snapshot.anchor_after(selection.end);
3384 if !self.linked_edit_ranges.is_empty() {
3385 let start_anchor = snapshot.anchor_before(selection.start);
3386
3387 let is_word_char = text.chars().next().map_or(true, |char| {
3388 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3389 classifier.is_word(char)
3390 });
3391
3392 if is_word_char {
3393 if let Some(ranges) = self
3394 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3395 {
3396 for (buffer, edits) in ranges {
3397 linked_edits
3398 .entry(buffer.clone())
3399 .or_default()
3400 .extend(edits.into_iter().map(|range| (range, text.clone())));
3401 }
3402 }
3403 }
3404 }
3405
3406 new_selections.push((selection.map(|_| anchor), 0));
3407 edits.push((selection.start..selection.end, text.clone()));
3408 }
3409
3410 drop(snapshot);
3411
3412 self.transact(cx, |this, cx| {
3413 this.buffer.update(cx, |buffer, cx| {
3414 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3415 });
3416 for (buffer, edits) in linked_edits {
3417 buffer.update(cx, |buffer, cx| {
3418 let snapshot = buffer.snapshot();
3419 let edits = edits
3420 .into_iter()
3421 .map(|(range, text)| {
3422 use text::ToPoint as TP;
3423 let end_point = TP::to_point(&range.end, &snapshot);
3424 let start_point = TP::to_point(&range.start, &snapshot);
3425 (start_point..end_point, text)
3426 })
3427 .sorted_by_key(|(range, _)| range.start)
3428 .collect::<Vec<_>>();
3429 buffer.edit(edits, None, cx);
3430 })
3431 }
3432 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3433 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3434 let snapshot = this.buffer.read(cx).read(cx);
3435 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3436 .zip(new_selection_deltas)
3437 .map(|(selection, delta)| Selection {
3438 id: selection.id,
3439 start: selection.start + delta,
3440 end: selection.end + delta,
3441 reversed: selection.reversed,
3442 goal: SelectionGoal::None,
3443 })
3444 .collect::<Vec<_>>();
3445
3446 let mut i = 0;
3447 for (position, delta, selection_id, pair) in new_autoclose_regions {
3448 let position = position.to_offset(&snapshot) + delta;
3449 let start = snapshot.anchor_before(position);
3450 let end = snapshot.anchor_after(position);
3451 while let Some(existing_state) = this.autoclose_regions.get(i) {
3452 match existing_state.range.start.cmp(&start, &snapshot) {
3453 Ordering::Less => i += 1,
3454 Ordering::Greater => break,
3455 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3456 Ordering::Less => i += 1,
3457 Ordering::Equal => break,
3458 Ordering::Greater => break,
3459 },
3460 }
3461 }
3462 this.autoclose_regions.insert(
3463 i,
3464 AutocloseRegion {
3465 selection_id,
3466 range: start..end,
3467 pair,
3468 },
3469 );
3470 }
3471
3472 drop(snapshot);
3473 let had_active_inline_completion = this.has_active_inline_completion(cx);
3474 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3475 s.select(new_selections)
3476 });
3477
3478 if !bracket_inserted {
3479 if let Some(on_type_format_task) =
3480 this.trigger_on_type_formatting(text.to_string(), cx)
3481 {
3482 on_type_format_task.detach_and_log_err(cx);
3483 }
3484 }
3485
3486 let editor_settings = EditorSettings::get_global(cx);
3487 if bracket_inserted
3488 && (editor_settings.auto_signature_help
3489 || editor_settings.show_signature_help_after_edits)
3490 {
3491 this.show_signature_help(&ShowSignatureHelp, cx);
3492 }
3493
3494 let trigger_in_words = !had_active_inline_completion;
3495 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3496 linked_editing_ranges::refresh_linked_ranges(this, cx);
3497 this.refresh_inline_completion(true, false, cx);
3498 });
3499 }
3500
3501 fn find_possible_emoji_shortcode_at_position(
3502 snapshot: &MultiBufferSnapshot,
3503 position: Point,
3504 ) -> Option<String> {
3505 let mut chars = Vec::new();
3506 let mut found_colon = false;
3507 for char in snapshot.reversed_chars_at(position).take(100) {
3508 // Found a possible emoji shortcode in the middle of the buffer
3509 if found_colon {
3510 if char.is_whitespace() {
3511 chars.reverse();
3512 return Some(chars.iter().collect());
3513 }
3514 // If the previous character is not a whitespace, we are in the middle of a word
3515 // and we only want to complete the shortcode if the word is made up of other emojis
3516 let mut containing_word = String::new();
3517 for ch in snapshot
3518 .reversed_chars_at(position)
3519 .skip(chars.len() + 1)
3520 .take(100)
3521 {
3522 if ch.is_whitespace() {
3523 break;
3524 }
3525 containing_word.push(ch);
3526 }
3527 let containing_word = containing_word.chars().rev().collect::<String>();
3528 if util::word_consists_of_emojis(containing_word.as_str()) {
3529 chars.reverse();
3530 return Some(chars.iter().collect());
3531 }
3532 }
3533
3534 if char.is_whitespace() || !char.is_ascii() {
3535 return None;
3536 }
3537 if char == ':' {
3538 found_colon = true;
3539 } else {
3540 chars.push(char);
3541 }
3542 }
3543 // Found a possible emoji shortcode at the beginning of the buffer
3544 chars.reverse();
3545 Some(chars.iter().collect())
3546 }
3547
3548 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3549 self.transact(cx, |this, cx| {
3550 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3551 let selections = this.selections.all::<usize>(cx);
3552 let multi_buffer = this.buffer.read(cx);
3553 let buffer = multi_buffer.snapshot(cx);
3554 selections
3555 .iter()
3556 .map(|selection| {
3557 let start_point = selection.start.to_point(&buffer);
3558 let mut indent =
3559 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3560 indent.len = cmp::min(indent.len, start_point.column);
3561 let start = selection.start;
3562 let end = selection.end;
3563 let selection_is_empty = start == end;
3564 let language_scope = buffer.language_scope_at(start);
3565 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3566 &language_scope
3567 {
3568 let leading_whitespace_len = buffer
3569 .reversed_chars_at(start)
3570 .take_while(|c| c.is_whitespace() && *c != '\n')
3571 .map(|c| c.len_utf8())
3572 .sum::<usize>();
3573
3574 let trailing_whitespace_len = buffer
3575 .chars_at(end)
3576 .take_while(|c| c.is_whitespace() && *c != '\n')
3577 .map(|c| c.len_utf8())
3578 .sum::<usize>();
3579
3580 let insert_extra_newline =
3581 language.brackets().any(|(pair, enabled)| {
3582 let pair_start = pair.start.trim_end();
3583 let pair_end = pair.end.trim_start();
3584
3585 enabled
3586 && pair.newline
3587 && buffer.contains_str_at(
3588 end + trailing_whitespace_len,
3589 pair_end,
3590 )
3591 && buffer.contains_str_at(
3592 (start - leading_whitespace_len)
3593 .saturating_sub(pair_start.len()),
3594 pair_start,
3595 )
3596 });
3597
3598 // Comment extension on newline is allowed only for cursor selections
3599 let comment_delimiter = maybe!({
3600 if !selection_is_empty {
3601 return None;
3602 }
3603
3604 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3605 return None;
3606 }
3607
3608 let delimiters = language.line_comment_prefixes();
3609 let max_len_of_delimiter =
3610 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3611 let (snapshot, range) =
3612 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3613
3614 let mut index_of_first_non_whitespace = 0;
3615 let comment_candidate = snapshot
3616 .chars_for_range(range)
3617 .skip_while(|c| {
3618 let should_skip = c.is_whitespace();
3619 if should_skip {
3620 index_of_first_non_whitespace += 1;
3621 }
3622 should_skip
3623 })
3624 .take(max_len_of_delimiter)
3625 .collect::<String>();
3626 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3627 comment_candidate.starts_with(comment_prefix.as_ref())
3628 })?;
3629 let cursor_is_placed_after_comment_marker =
3630 index_of_first_non_whitespace + comment_prefix.len()
3631 <= start_point.column as usize;
3632 if cursor_is_placed_after_comment_marker {
3633 Some(comment_prefix.clone())
3634 } else {
3635 None
3636 }
3637 });
3638 (comment_delimiter, insert_extra_newline)
3639 } else {
3640 (None, false)
3641 };
3642
3643 let capacity_for_delimiter = comment_delimiter
3644 .as_deref()
3645 .map(str::len)
3646 .unwrap_or_default();
3647 let mut new_text =
3648 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3649 new_text.push('\n');
3650 new_text.extend(indent.chars());
3651 if let Some(delimiter) = &comment_delimiter {
3652 new_text.push_str(delimiter);
3653 }
3654 if insert_extra_newline {
3655 new_text = new_text.repeat(2);
3656 }
3657
3658 let anchor = buffer.anchor_after(end);
3659 let new_selection = selection.map(|_| anchor);
3660 (
3661 (start..end, new_text),
3662 (insert_extra_newline, new_selection),
3663 )
3664 })
3665 .unzip()
3666 };
3667
3668 this.edit_with_autoindent(edits, cx);
3669 let buffer = this.buffer.read(cx).snapshot(cx);
3670 let new_selections = selection_fixup_info
3671 .into_iter()
3672 .map(|(extra_newline_inserted, new_selection)| {
3673 let mut cursor = new_selection.end.to_point(&buffer);
3674 if extra_newline_inserted {
3675 cursor.row -= 1;
3676 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3677 }
3678 new_selection.map(|_| cursor)
3679 })
3680 .collect();
3681
3682 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3683 this.refresh_inline_completion(true, false, cx);
3684 });
3685 }
3686
3687 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3688 let buffer = self.buffer.read(cx);
3689 let snapshot = buffer.snapshot(cx);
3690
3691 let mut edits = Vec::new();
3692 let mut rows = Vec::new();
3693
3694 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3695 let cursor = selection.head();
3696 let row = cursor.row;
3697
3698 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3699
3700 let newline = "\n".to_string();
3701 edits.push((start_of_line..start_of_line, newline));
3702
3703 rows.push(row + rows_inserted as u32);
3704 }
3705
3706 self.transact(cx, |editor, cx| {
3707 editor.edit(edits, cx);
3708
3709 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3710 let mut index = 0;
3711 s.move_cursors_with(|map, _, _| {
3712 let row = rows[index];
3713 index += 1;
3714
3715 let point = Point::new(row, 0);
3716 let boundary = map.next_line_boundary(point).1;
3717 let clipped = map.clip_point(boundary, Bias::Left);
3718
3719 (clipped, SelectionGoal::None)
3720 });
3721 });
3722
3723 let mut indent_edits = Vec::new();
3724 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3725 for row in rows {
3726 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3727 for (row, indent) in indents {
3728 if indent.len == 0 {
3729 continue;
3730 }
3731
3732 let text = match indent.kind {
3733 IndentKind::Space => " ".repeat(indent.len as usize),
3734 IndentKind::Tab => "\t".repeat(indent.len as usize),
3735 };
3736 let point = Point::new(row.0, 0);
3737 indent_edits.push((point..point, text));
3738 }
3739 }
3740 editor.edit(indent_edits, cx);
3741 });
3742 }
3743
3744 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3745 let buffer = self.buffer.read(cx);
3746 let snapshot = buffer.snapshot(cx);
3747
3748 let mut edits = Vec::new();
3749 let mut rows = Vec::new();
3750 let mut rows_inserted = 0;
3751
3752 for selection in self.selections.all_adjusted(cx) {
3753 let cursor = selection.head();
3754 let row = cursor.row;
3755
3756 let point = Point::new(row + 1, 0);
3757 let start_of_line = snapshot.clip_point(point, Bias::Left);
3758
3759 let newline = "\n".to_string();
3760 edits.push((start_of_line..start_of_line, newline));
3761
3762 rows_inserted += 1;
3763 rows.push(row + rows_inserted);
3764 }
3765
3766 self.transact(cx, |editor, cx| {
3767 editor.edit(edits, cx);
3768
3769 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3770 let mut index = 0;
3771 s.move_cursors_with(|map, _, _| {
3772 let row = rows[index];
3773 index += 1;
3774
3775 let point = Point::new(row, 0);
3776 let boundary = map.next_line_boundary(point).1;
3777 let clipped = map.clip_point(boundary, Bias::Left);
3778
3779 (clipped, SelectionGoal::None)
3780 });
3781 });
3782
3783 let mut indent_edits = Vec::new();
3784 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3785 for row in rows {
3786 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3787 for (row, indent) in indents {
3788 if indent.len == 0 {
3789 continue;
3790 }
3791
3792 let text = match indent.kind {
3793 IndentKind::Space => " ".repeat(indent.len as usize),
3794 IndentKind::Tab => "\t".repeat(indent.len as usize),
3795 };
3796 let point = Point::new(row.0, 0);
3797 indent_edits.push((point..point, text));
3798 }
3799 }
3800 editor.edit(indent_edits, cx);
3801 });
3802 }
3803
3804 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3805 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3806 original_indent_columns: Vec::new(),
3807 });
3808 self.insert_with_autoindent_mode(text, autoindent, cx);
3809 }
3810
3811 fn insert_with_autoindent_mode(
3812 &mut self,
3813 text: &str,
3814 autoindent_mode: Option<AutoindentMode>,
3815 cx: &mut ViewContext<Self>,
3816 ) {
3817 if self.read_only(cx) {
3818 return;
3819 }
3820
3821 let text: Arc<str> = text.into();
3822 self.transact(cx, |this, cx| {
3823 let old_selections = this.selections.all_adjusted(cx);
3824 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3825 let anchors = {
3826 let snapshot = buffer.read(cx);
3827 old_selections
3828 .iter()
3829 .map(|s| {
3830 let anchor = snapshot.anchor_after(s.head());
3831 s.map(|_| anchor)
3832 })
3833 .collect::<Vec<_>>()
3834 };
3835 buffer.edit(
3836 old_selections
3837 .iter()
3838 .map(|s| (s.start..s.end, text.clone())),
3839 autoindent_mode,
3840 cx,
3841 );
3842 anchors
3843 });
3844
3845 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3846 s.select_anchors(selection_anchors);
3847 })
3848 });
3849 }
3850
3851 fn trigger_completion_on_input(
3852 &mut self,
3853 text: &str,
3854 trigger_in_words: bool,
3855 cx: &mut ViewContext<Self>,
3856 ) {
3857 if self.is_completion_trigger(text, trigger_in_words, cx) {
3858 self.show_completions(
3859 &ShowCompletions {
3860 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3861 },
3862 cx,
3863 );
3864 } else {
3865 self.hide_context_menu(cx);
3866 }
3867 }
3868
3869 fn is_completion_trigger(
3870 &self,
3871 text: &str,
3872 trigger_in_words: bool,
3873 cx: &mut ViewContext<Self>,
3874 ) -> bool {
3875 let position = self.selections.newest_anchor().head();
3876 let multibuffer = self.buffer.read(cx);
3877 let Some(buffer) = position
3878 .buffer_id
3879 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3880 else {
3881 return false;
3882 };
3883
3884 if let Some(completion_provider) = &self.completion_provider {
3885 completion_provider.is_completion_trigger(
3886 &buffer,
3887 position.text_anchor,
3888 text,
3889 trigger_in_words,
3890 cx,
3891 )
3892 } else {
3893 false
3894 }
3895 }
3896
3897 /// If any empty selections is touching the start of its innermost containing autoclose
3898 /// region, expand it to select the brackets.
3899 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3900 let selections = self.selections.all::<usize>(cx);
3901 let buffer = self.buffer.read(cx).read(cx);
3902 let new_selections = self
3903 .selections_with_autoclose_regions(selections, &buffer)
3904 .map(|(mut selection, region)| {
3905 if !selection.is_empty() {
3906 return selection;
3907 }
3908
3909 if let Some(region) = region {
3910 let mut range = region.range.to_offset(&buffer);
3911 if selection.start == range.start && range.start >= region.pair.start.len() {
3912 range.start -= region.pair.start.len();
3913 if buffer.contains_str_at(range.start, ®ion.pair.start)
3914 && buffer.contains_str_at(range.end, ®ion.pair.end)
3915 {
3916 range.end += region.pair.end.len();
3917 selection.start = range.start;
3918 selection.end = range.end;
3919
3920 return selection;
3921 }
3922 }
3923 }
3924
3925 let always_treat_brackets_as_autoclosed = buffer
3926 .settings_at(selection.start, cx)
3927 .always_treat_brackets_as_autoclosed;
3928
3929 if !always_treat_brackets_as_autoclosed {
3930 return selection;
3931 }
3932
3933 if let Some(scope) = buffer.language_scope_at(selection.start) {
3934 for (pair, enabled) in scope.brackets() {
3935 if !enabled || !pair.close {
3936 continue;
3937 }
3938
3939 if buffer.contains_str_at(selection.start, &pair.end) {
3940 let pair_start_len = pair.start.len();
3941 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3942 {
3943 selection.start -= pair_start_len;
3944 selection.end += pair.end.len();
3945
3946 return selection;
3947 }
3948 }
3949 }
3950 }
3951
3952 selection
3953 })
3954 .collect();
3955
3956 drop(buffer);
3957 self.change_selections(None, cx, |selections| selections.select(new_selections));
3958 }
3959
3960 /// Iterate the given selections, and for each one, find the smallest surrounding
3961 /// autoclose region. This uses the ordering of the selections and the autoclose
3962 /// regions to avoid repeated comparisons.
3963 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3964 &'a self,
3965 selections: impl IntoIterator<Item = Selection<D>>,
3966 buffer: &'a MultiBufferSnapshot,
3967 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3968 let mut i = 0;
3969 let mut regions = self.autoclose_regions.as_slice();
3970 selections.into_iter().map(move |selection| {
3971 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3972
3973 let mut enclosing = None;
3974 while let Some(pair_state) = regions.get(i) {
3975 if pair_state.range.end.to_offset(buffer) < range.start {
3976 regions = ®ions[i + 1..];
3977 i = 0;
3978 } else if pair_state.range.start.to_offset(buffer) > range.end {
3979 break;
3980 } else {
3981 if pair_state.selection_id == selection.id {
3982 enclosing = Some(pair_state);
3983 }
3984 i += 1;
3985 }
3986 }
3987
3988 (selection.clone(), enclosing)
3989 })
3990 }
3991
3992 /// Remove any autoclose regions that no longer contain their selection.
3993 fn invalidate_autoclose_regions(
3994 &mut self,
3995 mut selections: &[Selection<Anchor>],
3996 buffer: &MultiBufferSnapshot,
3997 ) {
3998 self.autoclose_regions.retain(|state| {
3999 let mut i = 0;
4000 while let Some(selection) = selections.get(i) {
4001 if selection.end.cmp(&state.range.start, buffer).is_lt() {
4002 selections = &selections[1..];
4003 continue;
4004 }
4005 if selection.start.cmp(&state.range.end, buffer).is_gt() {
4006 break;
4007 }
4008 if selection.id == state.selection_id {
4009 return true;
4010 } else {
4011 i += 1;
4012 }
4013 }
4014 false
4015 });
4016 }
4017
4018 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4019 let offset = position.to_offset(buffer);
4020 let (word_range, kind) = buffer.surrounding_word(offset, true);
4021 if offset > word_range.start && kind == Some(CharKind::Word) {
4022 Some(
4023 buffer
4024 .text_for_range(word_range.start..offset)
4025 .collect::<String>(),
4026 )
4027 } else {
4028 None
4029 }
4030 }
4031
4032 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4033 self.refresh_inlay_hints(
4034 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4035 cx,
4036 );
4037 }
4038
4039 pub fn inlay_hints_enabled(&self) -> bool {
4040 self.inlay_hint_cache.enabled
4041 }
4042
4043 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4044 if self.project.is_none() || self.mode != EditorMode::Full {
4045 return;
4046 }
4047
4048 let reason_description = reason.description();
4049 let ignore_debounce = matches!(
4050 reason,
4051 InlayHintRefreshReason::SettingsChange(_)
4052 | InlayHintRefreshReason::Toggle(_)
4053 | InlayHintRefreshReason::ExcerptsRemoved(_)
4054 );
4055 let (invalidate_cache, required_languages) = match reason {
4056 InlayHintRefreshReason::Toggle(enabled) => {
4057 self.inlay_hint_cache.enabled = enabled;
4058 if enabled {
4059 (InvalidationStrategy::RefreshRequested, None)
4060 } else {
4061 self.inlay_hint_cache.clear();
4062 self.splice_inlays(
4063 self.visible_inlay_hints(cx)
4064 .iter()
4065 .map(|inlay| inlay.id)
4066 .collect(),
4067 Vec::new(),
4068 cx,
4069 );
4070 return;
4071 }
4072 }
4073 InlayHintRefreshReason::SettingsChange(new_settings) => {
4074 match self.inlay_hint_cache.update_settings(
4075 &self.buffer,
4076 new_settings,
4077 self.visible_inlay_hints(cx),
4078 cx,
4079 ) {
4080 ControlFlow::Break(Some(InlaySplice {
4081 to_remove,
4082 to_insert,
4083 })) => {
4084 self.splice_inlays(to_remove, to_insert, cx);
4085 return;
4086 }
4087 ControlFlow::Break(None) => return,
4088 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4089 }
4090 }
4091 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4092 if let Some(InlaySplice {
4093 to_remove,
4094 to_insert,
4095 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4096 {
4097 self.splice_inlays(to_remove, to_insert, cx);
4098 }
4099 return;
4100 }
4101 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4102 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4103 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4104 }
4105 InlayHintRefreshReason::RefreshRequested => {
4106 (InvalidationStrategy::RefreshRequested, None)
4107 }
4108 };
4109
4110 if let Some(InlaySplice {
4111 to_remove,
4112 to_insert,
4113 }) = self.inlay_hint_cache.spawn_hint_refresh(
4114 reason_description,
4115 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4116 invalidate_cache,
4117 ignore_debounce,
4118 cx,
4119 ) {
4120 self.splice_inlays(to_remove, to_insert, cx);
4121 }
4122 }
4123
4124 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4125 self.display_map
4126 .read(cx)
4127 .current_inlays()
4128 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4129 .cloned()
4130 .collect()
4131 }
4132
4133 pub fn excerpts_for_inlay_hints_query(
4134 &self,
4135 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4136 cx: &mut ViewContext<Editor>,
4137 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4138 let Some(project) = self.project.as_ref() else {
4139 return HashMap::default();
4140 };
4141 let project = project.read(cx);
4142 let multi_buffer = self.buffer().read(cx);
4143 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4144 let multi_buffer_visible_start = self
4145 .scroll_manager
4146 .anchor()
4147 .anchor
4148 .to_point(&multi_buffer_snapshot);
4149 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4150 multi_buffer_visible_start
4151 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4152 Bias::Left,
4153 );
4154 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4155 multi_buffer
4156 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4157 .into_iter()
4158 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4159 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4160 let buffer = buffer_handle.read(cx);
4161 let buffer_file = project::File::from_dyn(buffer.file())?;
4162 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4163 let worktree_entry = buffer_worktree
4164 .read(cx)
4165 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4166 if worktree_entry.is_ignored {
4167 return None;
4168 }
4169
4170 let language = buffer.language()?;
4171 if let Some(restrict_to_languages) = restrict_to_languages {
4172 if !restrict_to_languages.contains(language) {
4173 return None;
4174 }
4175 }
4176 Some((
4177 excerpt_id,
4178 (
4179 buffer_handle,
4180 buffer.version().clone(),
4181 excerpt_visible_range,
4182 ),
4183 ))
4184 })
4185 .collect()
4186 }
4187
4188 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4189 TextLayoutDetails {
4190 text_system: cx.text_system().clone(),
4191 editor_style: self.style.clone().unwrap(),
4192 rem_size: cx.rem_size(),
4193 scroll_anchor: self.scroll_manager.anchor(),
4194 visible_rows: self.visible_line_count(),
4195 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4196 }
4197 }
4198
4199 fn splice_inlays(
4200 &self,
4201 to_remove: Vec<InlayId>,
4202 to_insert: Vec<Inlay>,
4203 cx: &mut ViewContext<Self>,
4204 ) {
4205 self.display_map.update(cx, |display_map, cx| {
4206 display_map.splice_inlays(to_remove, to_insert, cx);
4207 });
4208 cx.notify();
4209 }
4210
4211 fn trigger_on_type_formatting(
4212 &self,
4213 input: String,
4214 cx: &mut ViewContext<Self>,
4215 ) -> Option<Task<Result<()>>> {
4216 if input.len() != 1 {
4217 return None;
4218 }
4219
4220 let project = self.project.as_ref()?;
4221 let position = self.selections.newest_anchor().head();
4222 let (buffer, buffer_position) = self
4223 .buffer
4224 .read(cx)
4225 .text_anchor_for_position(position, cx)?;
4226
4227 let settings = language_settings::language_settings(
4228 buffer.read(cx).language_at(buffer_position).as_ref(),
4229 buffer.read(cx).file(),
4230 cx,
4231 );
4232 if !settings.use_on_type_format {
4233 return None;
4234 }
4235
4236 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4237 // hence we do LSP request & edit on host side only — add formats to host's history.
4238 let push_to_lsp_host_history = true;
4239 // If this is not the host, append its history with new edits.
4240 let push_to_client_history = project.read(cx).is_via_collab();
4241
4242 let on_type_formatting = project.update(cx, |project, cx| {
4243 project.on_type_format(
4244 buffer.clone(),
4245 buffer_position,
4246 input,
4247 push_to_lsp_host_history,
4248 cx,
4249 )
4250 });
4251 Some(cx.spawn(|editor, mut cx| async move {
4252 if let Some(transaction) = on_type_formatting.await? {
4253 if push_to_client_history {
4254 buffer
4255 .update(&mut cx, |buffer, _| {
4256 buffer.push_transaction(transaction, Instant::now());
4257 })
4258 .ok();
4259 }
4260 editor.update(&mut cx, |editor, cx| {
4261 editor.refresh_document_highlights(cx);
4262 })?;
4263 }
4264 Ok(())
4265 }))
4266 }
4267
4268 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4269 if self.pending_rename.is_some() {
4270 return;
4271 }
4272
4273 let Some(provider) = self.completion_provider.as_ref() else {
4274 return;
4275 };
4276
4277 let position = self.selections.newest_anchor().head();
4278 let (buffer, buffer_position) =
4279 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4280 output
4281 } else {
4282 return;
4283 };
4284
4285 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4286 let is_followup_invoke = {
4287 let context_menu_state = self.context_menu.read();
4288 matches!(
4289 context_menu_state.deref(),
4290 Some(ContextMenu::Completions(_))
4291 )
4292 };
4293 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4294 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4295 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4296 CompletionTriggerKind::TRIGGER_CHARACTER
4297 }
4298
4299 _ => CompletionTriggerKind::INVOKED,
4300 };
4301 let completion_context = CompletionContext {
4302 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4303 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4304 Some(String::from(trigger))
4305 } else {
4306 None
4307 }
4308 }),
4309 trigger_kind,
4310 };
4311 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4312 let sort_completions = provider.sort_completions();
4313
4314 let id = post_inc(&mut self.next_completion_id);
4315 let task = cx.spawn(|this, mut cx| {
4316 async move {
4317 this.update(&mut cx, |this, _| {
4318 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4319 })?;
4320 let completions = completions.await.log_err();
4321 let menu = if let Some(completions) = completions {
4322 let mut menu = CompletionsMenu {
4323 id,
4324 sort_completions,
4325 initial_position: position,
4326 match_candidates: completions
4327 .iter()
4328 .enumerate()
4329 .map(|(id, completion)| {
4330 StringMatchCandidate::new(
4331 id,
4332 completion.label.text[completion.label.filter_range.clone()]
4333 .into(),
4334 )
4335 })
4336 .collect(),
4337 buffer: buffer.clone(),
4338 completions: Arc::new(RwLock::new(completions.into())),
4339 matches: Vec::new().into(),
4340 selected_item: 0,
4341 scroll_handle: UniformListScrollHandle::new(),
4342 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4343 DebouncedDelay::new(),
4344 )),
4345 };
4346 menu.filter(query.as_deref(), cx.background_executor().clone())
4347 .await;
4348
4349 if menu.matches.is_empty() {
4350 None
4351 } else {
4352 this.update(&mut cx, |editor, cx| {
4353 let completions = menu.completions.clone();
4354 let matches = menu.matches.clone();
4355
4356 let delay_ms = EditorSettings::get_global(cx)
4357 .completion_documentation_secondary_query_debounce;
4358 let delay = Duration::from_millis(delay_ms);
4359 editor
4360 .completion_documentation_pre_resolve_debounce
4361 .fire_new(delay, cx, |editor, cx| {
4362 CompletionsMenu::pre_resolve_completion_documentation(
4363 buffer,
4364 completions,
4365 matches,
4366 editor,
4367 cx,
4368 )
4369 });
4370 })
4371 .ok();
4372 Some(menu)
4373 }
4374 } else {
4375 None
4376 };
4377
4378 this.update(&mut cx, |this, cx| {
4379 let mut context_menu = this.context_menu.write();
4380 match context_menu.as_ref() {
4381 None => {}
4382
4383 Some(ContextMenu::Completions(prev_menu)) => {
4384 if prev_menu.id > id {
4385 return;
4386 }
4387 }
4388
4389 _ => return,
4390 }
4391
4392 if this.focus_handle.is_focused(cx) && menu.is_some() {
4393 let menu = menu.unwrap();
4394 *context_menu = Some(ContextMenu::Completions(menu));
4395 drop(context_menu);
4396 this.discard_inline_completion(false, cx);
4397 cx.notify();
4398 } else if this.completion_tasks.len() <= 1 {
4399 // If there are no more completion tasks and the last menu was
4400 // empty, we should hide it. If it was already hidden, we should
4401 // also show the copilot completion when available.
4402 drop(context_menu);
4403 if this.hide_context_menu(cx).is_none() {
4404 this.update_visible_inline_completion(cx);
4405 }
4406 }
4407 })?;
4408
4409 Ok::<_, anyhow::Error>(())
4410 }
4411 .log_err()
4412 });
4413
4414 self.completion_tasks.push((id, task));
4415 }
4416
4417 pub fn confirm_completion(
4418 &mut self,
4419 action: &ConfirmCompletion,
4420 cx: &mut ViewContext<Self>,
4421 ) -> Option<Task<Result<()>>> {
4422 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4423 }
4424
4425 pub fn compose_completion(
4426 &mut self,
4427 action: &ComposeCompletion,
4428 cx: &mut ViewContext<Self>,
4429 ) -> Option<Task<Result<()>>> {
4430 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4431 }
4432
4433 fn do_completion(
4434 &mut self,
4435 item_ix: Option<usize>,
4436 intent: CompletionIntent,
4437 cx: &mut ViewContext<Self>,
4438 ) -> Option<Task<anyhow::Result<()>>> {
4439 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4440 menu
4441 } else {
4442 return None;
4443 };
4444
4445 let mut resolve_task_store = completions_menu
4446 .selected_completion_documentation_resolve_debounce
4447 .lock();
4448 let selected_completion_resolve = resolve_task_store.start_now();
4449 let menu_pre_resolve = self
4450 .completion_documentation_pre_resolve_debounce
4451 .start_now();
4452 drop(resolve_task_store);
4453
4454 Some(cx.spawn(|editor, mut cx| async move {
4455 match (selected_completion_resolve, menu_pre_resolve) {
4456 (None, None) => {}
4457 (Some(resolve), None) | (None, Some(resolve)) => resolve.await,
4458 (Some(resolve_1), Some(resolve_2)) => {
4459 futures::join!(resolve_1, resolve_2);
4460 }
4461 }
4462 if let Some(apply_edits_task) = editor.update(&mut cx, |editor, cx| {
4463 editor.apply_resolved_completion(completions_menu, item_ix, intent, cx)
4464 })? {
4465 apply_edits_task.await?;
4466 }
4467 Ok(())
4468 }))
4469 }
4470
4471 fn apply_resolved_completion(
4472 &mut self,
4473 completions_menu: CompletionsMenu,
4474 item_ix: Option<usize>,
4475 intent: CompletionIntent,
4476 cx: &mut ViewContext<'_, Editor>,
4477 ) -> Option<Task<anyhow::Result<Option<language::Transaction>>>> {
4478 use language::ToOffset as _;
4479
4480 let mat = completions_menu
4481 .matches
4482 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4483 let buffer_handle = completions_menu.buffer;
4484 let completions = completions_menu.completions.read();
4485 let completion = completions.get(mat.candidate_id)?;
4486 cx.stop_propagation();
4487
4488 let snippet;
4489 let text;
4490
4491 if completion.is_snippet() {
4492 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4493 text = snippet.as_ref().unwrap().text.clone();
4494 } else {
4495 snippet = None;
4496 text = completion.new_text.clone();
4497 };
4498 let selections = self.selections.all::<usize>(cx);
4499 let buffer = buffer_handle.read(cx);
4500 let old_range = completion.old_range.to_offset(buffer);
4501 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4502
4503 let newest_selection = self.selections.newest_anchor();
4504 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4505 return None;
4506 }
4507
4508 let lookbehind = newest_selection
4509 .start
4510 .text_anchor
4511 .to_offset(buffer)
4512 .saturating_sub(old_range.start);
4513 let lookahead = old_range
4514 .end
4515 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4516 let mut common_prefix_len = old_text
4517 .bytes()
4518 .zip(text.bytes())
4519 .take_while(|(a, b)| a == b)
4520 .count();
4521
4522 let snapshot = self.buffer.read(cx).snapshot(cx);
4523 let mut range_to_replace: Option<Range<isize>> = None;
4524 let mut ranges = Vec::new();
4525 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4526 for selection in &selections {
4527 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4528 let start = selection.start.saturating_sub(lookbehind);
4529 let end = selection.end + lookahead;
4530 if selection.id == newest_selection.id {
4531 range_to_replace = Some(
4532 ((start + common_prefix_len) as isize - selection.start as isize)
4533 ..(end as isize - selection.start as isize),
4534 );
4535 }
4536 ranges.push(start + common_prefix_len..end);
4537 } else {
4538 common_prefix_len = 0;
4539 ranges.clear();
4540 ranges.extend(selections.iter().map(|s| {
4541 if s.id == newest_selection.id {
4542 range_to_replace = Some(
4543 old_range.start.to_offset_utf16(&snapshot).0 as isize
4544 - selection.start as isize
4545 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4546 - selection.start as isize,
4547 );
4548 old_range.clone()
4549 } else {
4550 s.start..s.end
4551 }
4552 }));
4553 break;
4554 }
4555 if !self.linked_edit_ranges.is_empty() {
4556 let start_anchor = snapshot.anchor_before(selection.head());
4557 let end_anchor = snapshot.anchor_after(selection.tail());
4558 if let Some(ranges) = self
4559 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4560 {
4561 for (buffer, edits) in ranges {
4562 linked_edits.entry(buffer.clone()).or_default().extend(
4563 edits
4564 .into_iter()
4565 .map(|range| (range, text[common_prefix_len..].to_owned())),
4566 );
4567 }
4568 }
4569 }
4570 }
4571 let text = &text[common_prefix_len..];
4572
4573 cx.emit(EditorEvent::InputHandled {
4574 utf16_range_to_replace: range_to_replace,
4575 text: text.into(),
4576 });
4577
4578 self.transact(cx, |this, cx| {
4579 if let Some(mut snippet) = snippet {
4580 snippet.text = text.to_string();
4581 for tabstop in snippet.tabstops.iter_mut().flatten() {
4582 tabstop.start -= common_prefix_len as isize;
4583 tabstop.end -= common_prefix_len as isize;
4584 }
4585
4586 this.insert_snippet(&ranges, snippet, cx).log_err();
4587 } else {
4588 this.buffer.update(cx, |buffer, cx| {
4589 buffer.edit(
4590 ranges.iter().map(|range| (range.clone(), text)),
4591 this.autoindent_mode.clone(),
4592 cx,
4593 );
4594 });
4595 }
4596 for (buffer, edits) in linked_edits {
4597 buffer.update(cx, |buffer, cx| {
4598 let snapshot = buffer.snapshot();
4599 let edits = edits
4600 .into_iter()
4601 .map(|(range, text)| {
4602 use text::ToPoint as TP;
4603 let end_point = TP::to_point(&range.end, &snapshot);
4604 let start_point = TP::to_point(&range.start, &snapshot);
4605 (start_point..end_point, text)
4606 })
4607 .sorted_by_key(|(range, _)| range.start)
4608 .collect::<Vec<_>>();
4609 buffer.edit(edits, None, cx);
4610 })
4611 }
4612
4613 this.refresh_inline_completion(true, false, cx);
4614 });
4615
4616 let show_new_completions_on_confirm = completion
4617 .confirm
4618 .as_ref()
4619 .map_or(false, |confirm| confirm(intent, cx));
4620 if show_new_completions_on_confirm {
4621 self.show_completions(&ShowCompletions { trigger: None }, cx);
4622 }
4623
4624 let provider = self.completion_provider.as_ref()?;
4625 let apply_edits = provider.apply_additional_edits_for_completion(
4626 buffer_handle,
4627 completion.clone(),
4628 true,
4629 cx,
4630 );
4631
4632 let editor_settings = EditorSettings::get_global(cx);
4633 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4634 // After the code completion is finished, users often want to know what signatures are needed.
4635 // so we should automatically call signature_help
4636 self.show_signature_help(&ShowSignatureHelp, cx);
4637 }
4638 Some(apply_edits)
4639 }
4640
4641 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4642 let mut context_menu = self.context_menu.write();
4643 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4644 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4645 // Toggle if we're selecting the same one
4646 *context_menu = None;
4647 cx.notify();
4648 return;
4649 } else {
4650 // Otherwise, clear it and start a new one
4651 *context_menu = None;
4652 cx.notify();
4653 }
4654 }
4655 drop(context_menu);
4656 let snapshot = self.snapshot(cx);
4657 let deployed_from_indicator = action.deployed_from_indicator;
4658 let mut task = self.code_actions_task.take();
4659 let action = action.clone();
4660 cx.spawn(|editor, mut cx| async move {
4661 while let Some(prev_task) = task {
4662 prev_task.await.log_err();
4663 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4664 }
4665
4666 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4667 if editor.focus_handle.is_focused(cx) {
4668 let multibuffer_point = action
4669 .deployed_from_indicator
4670 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4671 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4672 let (buffer, buffer_row) = snapshot
4673 .buffer_snapshot
4674 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4675 .and_then(|(buffer_snapshot, range)| {
4676 editor
4677 .buffer
4678 .read(cx)
4679 .buffer(buffer_snapshot.remote_id())
4680 .map(|buffer| (buffer, range.start.row))
4681 })?;
4682 let (_, code_actions) = editor
4683 .available_code_actions
4684 .clone()
4685 .and_then(|(location, code_actions)| {
4686 let snapshot = location.buffer.read(cx).snapshot();
4687 let point_range = location.range.to_point(&snapshot);
4688 let point_range = point_range.start.row..=point_range.end.row;
4689 if point_range.contains(&buffer_row) {
4690 Some((location, code_actions))
4691 } else {
4692 None
4693 }
4694 })
4695 .unzip();
4696 let buffer_id = buffer.read(cx).remote_id();
4697 let tasks = editor
4698 .tasks
4699 .get(&(buffer_id, buffer_row))
4700 .map(|t| Arc::new(t.to_owned()));
4701 if tasks.is_none() && code_actions.is_none() {
4702 return None;
4703 }
4704
4705 editor.completion_tasks.clear();
4706 editor.discard_inline_completion(false, cx);
4707 let task_context =
4708 tasks
4709 .as_ref()
4710 .zip(editor.project.clone())
4711 .map(|(tasks, project)| {
4712 let position = Point::new(buffer_row, tasks.column);
4713 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4714 let location = Location {
4715 buffer: buffer.clone(),
4716 range: range_start..range_start,
4717 };
4718 // Fill in the environmental variables from the tree-sitter captures
4719 let mut captured_task_variables = TaskVariables::default();
4720 for (capture_name, value) in tasks.extra_variables.clone() {
4721 captured_task_variables.insert(
4722 task::VariableName::Custom(capture_name.into()),
4723 value.clone(),
4724 );
4725 }
4726 project.update(cx, |project, cx| {
4727 project.task_store().update(cx, |task_store, cx| {
4728 task_store.task_context_for_location(
4729 captured_task_variables,
4730 location,
4731 cx,
4732 )
4733 })
4734 })
4735 });
4736
4737 Some(cx.spawn(|editor, mut cx| async move {
4738 let task_context = match task_context {
4739 Some(task_context) => task_context.await,
4740 None => None,
4741 };
4742 let resolved_tasks =
4743 tasks.zip(task_context).map(|(tasks, task_context)| {
4744 Arc::new(ResolvedTasks {
4745 templates: tasks
4746 .templates
4747 .iter()
4748 .filter_map(|(kind, template)| {
4749 template
4750 .resolve_task(&kind.to_id_base(), &task_context)
4751 .map(|task| (kind.clone(), task))
4752 })
4753 .collect(),
4754 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4755 multibuffer_point.row,
4756 tasks.column,
4757 )),
4758 })
4759 });
4760 let spawn_straight_away = resolved_tasks
4761 .as_ref()
4762 .map_or(false, |tasks| tasks.templates.len() == 1)
4763 && code_actions
4764 .as_ref()
4765 .map_or(true, |actions| actions.is_empty());
4766 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4767 *editor.context_menu.write() =
4768 Some(ContextMenu::CodeActions(CodeActionsMenu {
4769 buffer,
4770 actions: CodeActionContents {
4771 tasks: resolved_tasks,
4772 actions: code_actions,
4773 },
4774 selected_item: Default::default(),
4775 scroll_handle: UniformListScrollHandle::default(),
4776 deployed_from_indicator,
4777 }));
4778 if spawn_straight_away {
4779 if let Some(task) = editor.confirm_code_action(
4780 &ConfirmCodeAction { item_ix: Some(0) },
4781 cx,
4782 ) {
4783 cx.notify();
4784 return task;
4785 }
4786 }
4787 cx.notify();
4788 Task::ready(Ok(()))
4789 }) {
4790 task.await
4791 } else {
4792 Ok(())
4793 }
4794 }))
4795 } else {
4796 Some(Task::ready(Ok(())))
4797 }
4798 })?;
4799 if let Some(task) = spawned_test_task {
4800 task.await?;
4801 }
4802
4803 Ok::<_, anyhow::Error>(())
4804 })
4805 .detach_and_log_err(cx);
4806 }
4807
4808 pub fn confirm_code_action(
4809 &mut self,
4810 action: &ConfirmCodeAction,
4811 cx: &mut ViewContext<Self>,
4812 ) -> Option<Task<Result<()>>> {
4813 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4814 menu
4815 } else {
4816 return None;
4817 };
4818 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4819 let action = actions_menu.actions.get(action_ix)?;
4820 let title = action.label();
4821 let buffer = actions_menu.buffer;
4822 let workspace = self.workspace()?;
4823
4824 match action {
4825 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4826 workspace.update(cx, |workspace, cx| {
4827 workspace::tasks::schedule_resolved_task(
4828 workspace,
4829 task_source_kind,
4830 resolved_task,
4831 false,
4832 cx,
4833 );
4834
4835 Some(Task::ready(Ok(())))
4836 })
4837 }
4838 CodeActionsItem::CodeAction {
4839 excerpt_id,
4840 action,
4841 provider,
4842 } => {
4843 let apply_code_action =
4844 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4845 let workspace = workspace.downgrade();
4846 Some(cx.spawn(|editor, cx| async move {
4847 let project_transaction = apply_code_action.await?;
4848 Self::open_project_transaction(
4849 &editor,
4850 workspace,
4851 project_transaction,
4852 title,
4853 cx,
4854 )
4855 .await
4856 }))
4857 }
4858 }
4859 }
4860
4861 pub async fn open_project_transaction(
4862 this: &WeakView<Editor>,
4863 workspace: WeakView<Workspace>,
4864 transaction: ProjectTransaction,
4865 title: String,
4866 mut cx: AsyncWindowContext,
4867 ) -> Result<()> {
4868 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4869 cx.update(|cx| {
4870 entries.sort_unstable_by_key(|(buffer, _)| {
4871 buffer.read(cx).file().map(|f| f.path().clone())
4872 });
4873 })?;
4874
4875 // If the project transaction's edits are all contained within this editor, then
4876 // avoid opening a new editor to display them.
4877
4878 if let Some((buffer, transaction)) = entries.first() {
4879 if entries.len() == 1 {
4880 let excerpt = this.update(&mut cx, |editor, cx| {
4881 editor
4882 .buffer()
4883 .read(cx)
4884 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4885 })?;
4886 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4887 if excerpted_buffer == *buffer {
4888 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4889 let excerpt_range = excerpt_range.to_offset(buffer);
4890 buffer
4891 .edited_ranges_for_transaction::<usize>(transaction)
4892 .all(|range| {
4893 excerpt_range.start <= range.start
4894 && excerpt_range.end >= range.end
4895 })
4896 })?;
4897
4898 if all_edits_within_excerpt {
4899 return Ok(());
4900 }
4901 }
4902 }
4903 }
4904 } else {
4905 return Ok(());
4906 }
4907
4908 let mut ranges_to_highlight = Vec::new();
4909 let excerpt_buffer = cx.new_model(|cx| {
4910 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4911 for (buffer_handle, transaction) in &entries {
4912 let buffer = buffer_handle.read(cx);
4913 ranges_to_highlight.extend(
4914 multibuffer.push_excerpts_with_context_lines(
4915 buffer_handle.clone(),
4916 buffer
4917 .edited_ranges_for_transaction::<usize>(transaction)
4918 .collect(),
4919 DEFAULT_MULTIBUFFER_CONTEXT,
4920 cx,
4921 ),
4922 );
4923 }
4924 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4925 multibuffer
4926 })?;
4927
4928 workspace.update(&mut cx, |workspace, cx| {
4929 let project = workspace.project().clone();
4930 let editor =
4931 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4932 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4933 editor.update(cx, |editor, cx| {
4934 editor.highlight_background::<Self>(
4935 &ranges_to_highlight,
4936 |theme| theme.editor_highlighted_line_background,
4937 cx,
4938 );
4939 });
4940 })?;
4941
4942 Ok(())
4943 }
4944
4945 pub fn push_code_action_provider(
4946 &mut self,
4947 provider: Arc<dyn CodeActionProvider>,
4948 cx: &mut ViewContext<Self>,
4949 ) {
4950 self.code_action_providers.push(provider);
4951 self.refresh_code_actions(cx);
4952 }
4953
4954 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4955 let buffer = self.buffer.read(cx);
4956 let newest_selection = self.selections.newest_anchor().clone();
4957 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4958 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4959 if start_buffer != end_buffer {
4960 return None;
4961 }
4962
4963 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4964 cx.background_executor()
4965 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4966 .await;
4967
4968 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4969 let providers = this.code_action_providers.clone();
4970 let tasks = this
4971 .code_action_providers
4972 .iter()
4973 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4974 .collect::<Vec<_>>();
4975 (providers, tasks)
4976 })?;
4977
4978 let mut actions = Vec::new();
4979 for (provider, provider_actions) in
4980 providers.into_iter().zip(future::join_all(tasks).await)
4981 {
4982 if let Some(provider_actions) = provider_actions.log_err() {
4983 actions.extend(provider_actions.into_iter().map(|action| {
4984 AvailableCodeAction {
4985 excerpt_id: newest_selection.start.excerpt_id,
4986 action,
4987 provider: provider.clone(),
4988 }
4989 }));
4990 }
4991 }
4992
4993 this.update(&mut cx, |this, cx| {
4994 this.available_code_actions = if actions.is_empty() {
4995 None
4996 } else {
4997 Some((
4998 Location {
4999 buffer: start_buffer,
5000 range: start..end,
5001 },
5002 actions.into(),
5003 ))
5004 };
5005 cx.notify();
5006 })
5007 }));
5008 None
5009 }
5010
5011 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5012 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5013 self.show_git_blame_inline = false;
5014
5015 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5016 cx.background_executor().timer(delay).await;
5017
5018 this.update(&mut cx, |this, cx| {
5019 this.show_git_blame_inline = true;
5020 cx.notify();
5021 })
5022 .log_err();
5023 }));
5024 }
5025 }
5026
5027 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5028 if self.pending_rename.is_some() {
5029 return None;
5030 }
5031
5032 let project = self.project.clone()?;
5033 let buffer = self.buffer.read(cx);
5034 let newest_selection = self.selections.newest_anchor().clone();
5035 let cursor_position = newest_selection.head();
5036 let (cursor_buffer, cursor_buffer_position) =
5037 buffer.text_anchor_for_position(cursor_position, cx)?;
5038 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5039 if cursor_buffer != tail_buffer {
5040 return None;
5041 }
5042
5043 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5044 cx.background_executor()
5045 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5046 .await;
5047
5048 let highlights = if let Some(highlights) = project
5049 .update(&mut cx, |project, cx| {
5050 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5051 })
5052 .log_err()
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 revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6243 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6244 if !revert_changes.is_empty() {
6245 self.transact(cx, |editor, cx| {
6246 editor.revert(revert_changes, cx);
6247 });
6248 }
6249 }
6250
6251 fn apply_selected_diff_hunks(&mut self, _: &ApplyDiffHunk, cx: &mut ViewContext<Self>) {
6252 let snapshot = self.buffer.read(cx).snapshot(cx);
6253 let hunks = hunks_for_selections(&snapshot, &self.selections.disjoint_anchors());
6254 let mut ranges_by_buffer = HashMap::default();
6255 self.transact(cx, |editor, cx| {
6256 for hunk in hunks {
6257 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
6258 ranges_by_buffer
6259 .entry(buffer.clone())
6260 .or_insert_with(Vec::new)
6261 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
6262 }
6263 }
6264
6265 for (buffer, ranges) in ranges_by_buffer {
6266 buffer.update(cx, |buffer, cx| {
6267 buffer.merge_into_base(ranges, cx);
6268 });
6269 }
6270 });
6271 }
6272
6273 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6274 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6275 let project_path = buffer.read(cx).project_path(cx)?;
6276 let project = self.project.as_ref()?.read(cx);
6277 let entry = project.entry_for_path(&project_path, cx)?;
6278 let abs_path = project.absolute_path(&project_path, cx)?;
6279 let parent = if entry.is_symlink {
6280 abs_path.canonicalize().ok()?
6281 } else {
6282 abs_path
6283 }
6284 .parent()?
6285 .to_path_buf();
6286 Some(parent)
6287 }) {
6288 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6289 }
6290 }
6291
6292 fn gather_revert_changes(
6293 &mut self,
6294 selections: &[Selection<Anchor>],
6295 cx: &mut ViewContext<'_, Editor>,
6296 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6297 let mut revert_changes = HashMap::default();
6298 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6299 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6300 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6301 }
6302 revert_changes
6303 }
6304
6305 pub fn prepare_revert_change(
6306 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6307 multi_buffer: &Model<MultiBuffer>,
6308 hunk: &MultiBufferDiffHunk,
6309 cx: &AppContext,
6310 ) -> Option<()> {
6311 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6312 let buffer = buffer.read(cx);
6313 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6314 let buffer_snapshot = buffer.snapshot();
6315 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6316 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6317 probe
6318 .0
6319 .start
6320 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6321 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6322 }) {
6323 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6324 Some(())
6325 } else {
6326 None
6327 }
6328 }
6329
6330 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6331 self.manipulate_lines(cx, |lines| lines.reverse())
6332 }
6333
6334 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6335 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6336 }
6337
6338 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6339 where
6340 Fn: FnMut(&mut Vec<&str>),
6341 {
6342 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6343 let buffer = self.buffer.read(cx).snapshot(cx);
6344
6345 let mut edits = Vec::new();
6346
6347 let selections = self.selections.all::<Point>(cx);
6348 let mut selections = selections.iter().peekable();
6349 let mut contiguous_row_selections = Vec::new();
6350 let mut new_selections = Vec::new();
6351 let mut added_lines = 0;
6352 let mut removed_lines = 0;
6353
6354 while let Some(selection) = selections.next() {
6355 let (start_row, end_row) = consume_contiguous_rows(
6356 &mut contiguous_row_selections,
6357 selection,
6358 &display_map,
6359 &mut selections,
6360 );
6361
6362 let start_point = Point::new(start_row.0, 0);
6363 let end_point = Point::new(
6364 end_row.previous_row().0,
6365 buffer.line_len(end_row.previous_row()),
6366 );
6367 let text = buffer
6368 .text_for_range(start_point..end_point)
6369 .collect::<String>();
6370
6371 let mut lines = text.split('\n').collect_vec();
6372
6373 let lines_before = lines.len();
6374 callback(&mut lines);
6375 let lines_after = lines.len();
6376
6377 edits.push((start_point..end_point, lines.join("\n")));
6378
6379 // Selections must change based on added and removed line count
6380 let start_row =
6381 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6382 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6383 new_selections.push(Selection {
6384 id: selection.id,
6385 start: start_row,
6386 end: end_row,
6387 goal: SelectionGoal::None,
6388 reversed: selection.reversed,
6389 });
6390
6391 if lines_after > lines_before {
6392 added_lines += lines_after - lines_before;
6393 } else if lines_before > lines_after {
6394 removed_lines += lines_before - lines_after;
6395 }
6396 }
6397
6398 self.transact(cx, |this, cx| {
6399 let buffer = this.buffer.update(cx, |buffer, cx| {
6400 buffer.edit(edits, None, cx);
6401 buffer.snapshot(cx)
6402 });
6403
6404 // Recalculate offsets on newly edited buffer
6405 let new_selections = new_selections
6406 .iter()
6407 .map(|s| {
6408 let start_point = Point::new(s.start.0, 0);
6409 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6410 Selection {
6411 id: s.id,
6412 start: buffer.point_to_offset(start_point),
6413 end: buffer.point_to_offset(end_point),
6414 goal: s.goal,
6415 reversed: s.reversed,
6416 }
6417 })
6418 .collect();
6419
6420 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6421 s.select(new_selections);
6422 });
6423
6424 this.request_autoscroll(Autoscroll::fit(), cx);
6425 });
6426 }
6427
6428 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6429 self.manipulate_text(cx, |text| text.to_uppercase())
6430 }
6431
6432 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6433 self.manipulate_text(cx, |text| text.to_lowercase())
6434 }
6435
6436 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6437 self.manipulate_text(cx, |text| {
6438 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6439 // https://github.com/rutrum/convert-case/issues/16
6440 text.split('\n')
6441 .map(|line| line.to_case(Case::Title))
6442 .join("\n")
6443 })
6444 }
6445
6446 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6447 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6448 }
6449
6450 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6451 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6452 }
6453
6454 pub fn convert_to_upper_camel_case(
6455 &mut self,
6456 _: &ConvertToUpperCamelCase,
6457 cx: &mut ViewContext<Self>,
6458 ) {
6459 self.manipulate_text(cx, |text| {
6460 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6461 // https://github.com/rutrum/convert-case/issues/16
6462 text.split('\n')
6463 .map(|line| line.to_case(Case::UpperCamel))
6464 .join("\n")
6465 })
6466 }
6467
6468 pub fn convert_to_lower_camel_case(
6469 &mut self,
6470 _: &ConvertToLowerCamelCase,
6471 cx: &mut ViewContext<Self>,
6472 ) {
6473 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6474 }
6475
6476 pub fn convert_to_opposite_case(
6477 &mut self,
6478 _: &ConvertToOppositeCase,
6479 cx: &mut ViewContext<Self>,
6480 ) {
6481 self.manipulate_text(cx, |text| {
6482 text.chars()
6483 .fold(String::with_capacity(text.len()), |mut t, c| {
6484 if c.is_uppercase() {
6485 t.extend(c.to_lowercase());
6486 } else {
6487 t.extend(c.to_uppercase());
6488 }
6489 t
6490 })
6491 })
6492 }
6493
6494 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6495 where
6496 Fn: FnMut(&str) -> String,
6497 {
6498 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6499 let buffer = self.buffer.read(cx).snapshot(cx);
6500
6501 let mut new_selections = Vec::new();
6502 let mut edits = Vec::new();
6503 let mut selection_adjustment = 0i32;
6504
6505 for selection in self.selections.all::<usize>(cx) {
6506 let selection_is_empty = selection.is_empty();
6507
6508 let (start, end) = if selection_is_empty {
6509 let word_range = movement::surrounding_word(
6510 &display_map,
6511 selection.start.to_display_point(&display_map),
6512 );
6513 let start = word_range.start.to_offset(&display_map, Bias::Left);
6514 let end = word_range.end.to_offset(&display_map, Bias::Left);
6515 (start, end)
6516 } else {
6517 (selection.start, selection.end)
6518 };
6519
6520 let text = buffer.text_for_range(start..end).collect::<String>();
6521 let old_length = text.len() as i32;
6522 let text = callback(&text);
6523
6524 new_selections.push(Selection {
6525 start: (start as i32 - selection_adjustment) as usize,
6526 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6527 goal: SelectionGoal::None,
6528 ..selection
6529 });
6530
6531 selection_adjustment += old_length - text.len() as i32;
6532
6533 edits.push((start..end, text));
6534 }
6535
6536 self.transact(cx, |this, cx| {
6537 this.buffer.update(cx, |buffer, cx| {
6538 buffer.edit(edits, None, cx);
6539 });
6540
6541 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6542 s.select(new_selections);
6543 });
6544
6545 this.request_autoscroll(Autoscroll::fit(), cx);
6546 });
6547 }
6548
6549 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6550 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6551 let buffer = &display_map.buffer_snapshot;
6552 let selections = self.selections.all::<Point>(cx);
6553
6554 let mut edits = Vec::new();
6555 let mut selections_iter = selections.iter().peekable();
6556 while let Some(selection) = selections_iter.next() {
6557 // Avoid duplicating the same lines twice.
6558 let mut rows = selection.spanned_rows(false, &display_map);
6559
6560 while let Some(next_selection) = selections_iter.peek() {
6561 let next_rows = next_selection.spanned_rows(false, &display_map);
6562 if next_rows.start < rows.end {
6563 rows.end = next_rows.end;
6564 selections_iter.next().unwrap();
6565 } else {
6566 break;
6567 }
6568 }
6569
6570 // Copy the text from the selected row region and splice it either at the start
6571 // or end of the region.
6572 let start = Point::new(rows.start.0, 0);
6573 let end = Point::new(
6574 rows.end.previous_row().0,
6575 buffer.line_len(rows.end.previous_row()),
6576 );
6577 let text = buffer
6578 .text_for_range(start..end)
6579 .chain(Some("\n"))
6580 .collect::<String>();
6581 let insert_location = if upwards {
6582 Point::new(rows.end.0, 0)
6583 } else {
6584 start
6585 };
6586 edits.push((insert_location..insert_location, text));
6587 }
6588
6589 self.transact(cx, |this, cx| {
6590 this.buffer.update(cx, |buffer, cx| {
6591 buffer.edit(edits, None, cx);
6592 });
6593
6594 this.request_autoscroll(Autoscroll::fit(), cx);
6595 });
6596 }
6597
6598 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6599 self.duplicate_line(true, cx);
6600 }
6601
6602 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6603 self.duplicate_line(false, cx);
6604 }
6605
6606 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6607 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6608 let buffer = self.buffer.read(cx).snapshot(cx);
6609
6610 let mut edits = Vec::new();
6611 let mut unfold_ranges = Vec::new();
6612 let mut refold_ranges = Vec::new();
6613
6614 let selections = self.selections.all::<Point>(cx);
6615 let mut selections = selections.iter().peekable();
6616 let mut contiguous_row_selections = Vec::new();
6617 let mut new_selections = Vec::new();
6618
6619 while let Some(selection) = selections.next() {
6620 // Find all the selections that span a contiguous row range
6621 let (start_row, end_row) = consume_contiguous_rows(
6622 &mut contiguous_row_selections,
6623 selection,
6624 &display_map,
6625 &mut selections,
6626 );
6627
6628 // Move the text spanned by the row range to be before the line preceding the row range
6629 if start_row.0 > 0 {
6630 let range_to_move = Point::new(
6631 start_row.previous_row().0,
6632 buffer.line_len(start_row.previous_row()),
6633 )
6634 ..Point::new(
6635 end_row.previous_row().0,
6636 buffer.line_len(end_row.previous_row()),
6637 );
6638 let insertion_point = display_map
6639 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6640 .0;
6641
6642 // Don't move lines across excerpts
6643 if buffer
6644 .excerpt_boundaries_in_range((
6645 Bound::Excluded(insertion_point),
6646 Bound::Included(range_to_move.end),
6647 ))
6648 .next()
6649 .is_none()
6650 {
6651 let text = buffer
6652 .text_for_range(range_to_move.clone())
6653 .flat_map(|s| s.chars())
6654 .skip(1)
6655 .chain(['\n'])
6656 .collect::<String>();
6657
6658 edits.push((
6659 buffer.anchor_after(range_to_move.start)
6660 ..buffer.anchor_before(range_to_move.end),
6661 String::new(),
6662 ));
6663 let insertion_anchor = buffer.anchor_after(insertion_point);
6664 edits.push((insertion_anchor..insertion_anchor, text));
6665
6666 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6667
6668 // Move selections up
6669 new_selections.extend(contiguous_row_selections.drain(..).map(
6670 |mut selection| {
6671 selection.start.row -= row_delta;
6672 selection.end.row -= row_delta;
6673 selection
6674 },
6675 ));
6676
6677 // Move folds up
6678 unfold_ranges.push(range_to_move.clone());
6679 for fold in display_map.folds_in_range(
6680 buffer.anchor_before(range_to_move.start)
6681 ..buffer.anchor_after(range_to_move.end),
6682 ) {
6683 let mut start = fold.range.start.to_point(&buffer);
6684 let mut end = fold.range.end.to_point(&buffer);
6685 start.row -= row_delta;
6686 end.row -= row_delta;
6687 refold_ranges.push((start..end, fold.placeholder.clone()));
6688 }
6689 }
6690 }
6691
6692 // If we didn't move line(s), preserve the existing selections
6693 new_selections.append(&mut contiguous_row_selections);
6694 }
6695
6696 self.transact(cx, |this, cx| {
6697 this.unfold_ranges(unfold_ranges, true, true, cx);
6698 this.buffer.update(cx, |buffer, cx| {
6699 for (range, text) in edits {
6700 buffer.edit([(range, text)], None, cx);
6701 }
6702 });
6703 this.fold_ranges(refold_ranges, true, cx);
6704 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6705 s.select(new_selections);
6706 })
6707 });
6708 }
6709
6710 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6711 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6712 let buffer = self.buffer.read(cx).snapshot(cx);
6713
6714 let mut edits = Vec::new();
6715 let mut unfold_ranges = Vec::new();
6716 let mut refold_ranges = Vec::new();
6717
6718 let selections = self.selections.all::<Point>(cx);
6719 let mut selections = selections.iter().peekable();
6720 let mut contiguous_row_selections = Vec::new();
6721 let mut new_selections = Vec::new();
6722
6723 while let Some(selection) = selections.next() {
6724 // Find all the selections that span a contiguous row range
6725 let (start_row, end_row) = consume_contiguous_rows(
6726 &mut contiguous_row_selections,
6727 selection,
6728 &display_map,
6729 &mut selections,
6730 );
6731
6732 // Move the text spanned by the row range to be after the last line of the row range
6733 if end_row.0 <= buffer.max_point().row {
6734 let range_to_move =
6735 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6736 let insertion_point = display_map
6737 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6738 .0;
6739
6740 // Don't move lines across excerpt boundaries
6741 if buffer
6742 .excerpt_boundaries_in_range((
6743 Bound::Excluded(range_to_move.start),
6744 Bound::Included(insertion_point),
6745 ))
6746 .next()
6747 .is_none()
6748 {
6749 let mut text = String::from("\n");
6750 text.extend(buffer.text_for_range(range_to_move.clone()));
6751 text.pop(); // Drop trailing newline
6752 edits.push((
6753 buffer.anchor_after(range_to_move.start)
6754 ..buffer.anchor_before(range_to_move.end),
6755 String::new(),
6756 ));
6757 let insertion_anchor = buffer.anchor_after(insertion_point);
6758 edits.push((insertion_anchor..insertion_anchor, text));
6759
6760 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6761
6762 // Move selections down
6763 new_selections.extend(contiguous_row_selections.drain(..).map(
6764 |mut selection| {
6765 selection.start.row += row_delta;
6766 selection.end.row += row_delta;
6767 selection
6768 },
6769 ));
6770
6771 // Move folds down
6772 unfold_ranges.push(range_to_move.clone());
6773 for fold in display_map.folds_in_range(
6774 buffer.anchor_before(range_to_move.start)
6775 ..buffer.anchor_after(range_to_move.end),
6776 ) {
6777 let mut start = fold.range.start.to_point(&buffer);
6778 let mut end = fold.range.end.to_point(&buffer);
6779 start.row += row_delta;
6780 end.row += row_delta;
6781 refold_ranges.push((start..end, fold.placeholder.clone()));
6782 }
6783 }
6784 }
6785
6786 // If we didn't move line(s), preserve the existing selections
6787 new_selections.append(&mut contiguous_row_selections);
6788 }
6789
6790 self.transact(cx, |this, cx| {
6791 this.unfold_ranges(unfold_ranges, true, true, cx);
6792 this.buffer.update(cx, |buffer, cx| {
6793 for (range, text) in edits {
6794 buffer.edit([(range, text)], None, cx);
6795 }
6796 });
6797 this.fold_ranges(refold_ranges, true, cx);
6798 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6799 });
6800 }
6801
6802 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6803 let text_layout_details = &self.text_layout_details(cx);
6804 self.transact(cx, |this, cx| {
6805 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6806 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6807 let line_mode = s.line_mode;
6808 s.move_with(|display_map, selection| {
6809 if !selection.is_empty() || line_mode {
6810 return;
6811 }
6812
6813 let mut head = selection.head();
6814 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6815 if head.column() == display_map.line_len(head.row()) {
6816 transpose_offset = display_map
6817 .buffer_snapshot
6818 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6819 }
6820
6821 if transpose_offset == 0 {
6822 return;
6823 }
6824
6825 *head.column_mut() += 1;
6826 head = display_map.clip_point(head, Bias::Right);
6827 let goal = SelectionGoal::HorizontalPosition(
6828 display_map
6829 .x_for_display_point(head, text_layout_details)
6830 .into(),
6831 );
6832 selection.collapse_to(head, goal);
6833
6834 let transpose_start = display_map
6835 .buffer_snapshot
6836 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6837 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6838 let transpose_end = display_map
6839 .buffer_snapshot
6840 .clip_offset(transpose_offset + 1, Bias::Right);
6841 if let Some(ch) =
6842 display_map.buffer_snapshot.chars_at(transpose_start).next()
6843 {
6844 edits.push((transpose_start..transpose_offset, String::new()));
6845 edits.push((transpose_end..transpose_end, ch.to_string()));
6846 }
6847 }
6848 });
6849 edits
6850 });
6851 this.buffer
6852 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6853 let selections = this.selections.all::<usize>(cx);
6854 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6855 s.select(selections);
6856 });
6857 });
6858 }
6859
6860 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6861 self.rewrap_impl(true, cx)
6862 }
6863
6864 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6865 let buffer = self.buffer.read(cx).snapshot(cx);
6866 let selections = self.selections.all::<Point>(cx);
6867 let mut selections = selections.iter().peekable();
6868
6869 let mut edits = Vec::new();
6870 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6871
6872 while let Some(selection) = selections.next() {
6873 let mut start_row = selection.start.row;
6874 let mut end_row = selection.end.row;
6875
6876 // Skip selections that overlap with a range that has already been rewrapped.
6877 let selection_range = start_row..end_row;
6878 if rewrapped_row_ranges
6879 .iter()
6880 .any(|range| range.overlaps(&selection_range))
6881 {
6882 continue;
6883 }
6884
6885 let mut should_rewrap = !only_text;
6886
6887 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6888 match language_scope.language_name().0.as_ref() {
6889 "Markdown" | "Plain Text" => {
6890 should_rewrap = true;
6891 }
6892 _ => {}
6893 }
6894 }
6895
6896 // Since not all lines in the selection may be at the same indent
6897 // level, choose the indent size that is the most common between all
6898 // of the lines.
6899 //
6900 // If there is a tie, we use the deepest indent.
6901 let (indent_size, indent_end) = {
6902 let mut indent_size_occurrences = HashMap::default();
6903 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6904
6905 for row in start_row..=end_row {
6906 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6907 rows_by_indent_size.entry(indent).or_default().push(row);
6908 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6909 }
6910
6911 let indent_size = indent_size_occurrences
6912 .into_iter()
6913 .max_by_key(|(indent, count)| (*count, indent.len))
6914 .map(|(indent, _)| indent)
6915 .unwrap_or_default();
6916 let row = rows_by_indent_size[&indent_size][0];
6917 let indent_end = Point::new(row, indent_size.len);
6918
6919 (indent_size, indent_end)
6920 };
6921
6922 let mut line_prefix = indent_size.chars().collect::<String>();
6923
6924 if let Some(comment_prefix) =
6925 buffer
6926 .language_scope_at(selection.head())
6927 .and_then(|language| {
6928 language
6929 .line_comment_prefixes()
6930 .iter()
6931 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6932 .cloned()
6933 })
6934 {
6935 line_prefix.push_str(&comment_prefix);
6936 should_rewrap = true;
6937 }
6938
6939 if selection.is_empty() {
6940 'expand_upwards: while start_row > 0 {
6941 let prev_row = start_row - 1;
6942 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6943 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6944 {
6945 start_row = prev_row;
6946 } else {
6947 break 'expand_upwards;
6948 }
6949 }
6950
6951 'expand_downwards: while end_row < buffer.max_point().row {
6952 let next_row = end_row + 1;
6953 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6954 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6955 {
6956 end_row = next_row;
6957 } else {
6958 break 'expand_downwards;
6959 }
6960 }
6961 }
6962
6963 if !should_rewrap {
6964 continue;
6965 }
6966
6967 let start = Point::new(start_row, 0);
6968 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6969 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6970 let Some(lines_without_prefixes) = selection_text
6971 .lines()
6972 .map(|line| {
6973 line.strip_prefix(&line_prefix)
6974 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6975 .ok_or_else(|| {
6976 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6977 })
6978 })
6979 .collect::<Result<Vec<_>, _>>()
6980 .log_err()
6981 else {
6982 continue;
6983 };
6984
6985 let unwrapped_text = lines_without_prefixes.join(" ");
6986 let wrap_column = buffer
6987 .settings_at(Point::new(start_row, 0), cx)
6988 .preferred_line_length as usize;
6989 let mut wrapped_text = String::new();
6990 let mut current_line = line_prefix.clone();
6991 for word in unwrapped_text.split_whitespace() {
6992 if current_line.len() + word.len() >= wrap_column {
6993 wrapped_text.push_str(¤t_line);
6994 wrapped_text.push('\n');
6995 current_line.truncate(line_prefix.len());
6996 }
6997
6998 if current_line.len() > line_prefix.len() {
6999 current_line.push(' ');
7000 }
7001
7002 current_line.push_str(word);
7003 }
7004
7005 if !current_line.is_empty() {
7006 wrapped_text.push_str(¤t_line);
7007 }
7008
7009 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
7010 let mut offset = start.to_offset(&buffer);
7011 let mut moved_since_edit = true;
7012
7013 for change in diff.iter_all_changes() {
7014 let value = change.value();
7015 match change.tag() {
7016 ChangeTag::Equal => {
7017 offset += value.len();
7018 moved_since_edit = true;
7019 }
7020 ChangeTag::Delete => {
7021 let start = buffer.anchor_after(offset);
7022 let end = buffer.anchor_before(offset + value.len());
7023
7024 if moved_since_edit {
7025 edits.push((start..end, String::new()));
7026 } else {
7027 edits.last_mut().unwrap().0.end = end;
7028 }
7029
7030 offset += value.len();
7031 moved_since_edit = false;
7032 }
7033 ChangeTag::Insert => {
7034 if moved_since_edit {
7035 let anchor = buffer.anchor_after(offset);
7036 edits.push((anchor..anchor, value.to_string()));
7037 } else {
7038 edits.last_mut().unwrap().1.push_str(value);
7039 }
7040
7041 moved_since_edit = false;
7042 }
7043 }
7044 }
7045
7046 rewrapped_row_ranges.push(start_row..=end_row);
7047 }
7048
7049 self.buffer
7050 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7051 }
7052
7053 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7054 let mut text = String::new();
7055 let buffer = self.buffer.read(cx).snapshot(cx);
7056 let mut selections = self.selections.all::<Point>(cx);
7057 let mut clipboard_selections = Vec::with_capacity(selections.len());
7058 {
7059 let max_point = buffer.max_point();
7060 let mut is_first = true;
7061 for selection in &mut selections {
7062 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7063 if is_entire_line {
7064 selection.start = Point::new(selection.start.row, 0);
7065 if !selection.is_empty() && selection.end.column == 0 {
7066 selection.end = cmp::min(max_point, selection.end);
7067 } else {
7068 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7069 }
7070 selection.goal = SelectionGoal::None;
7071 }
7072 if is_first {
7073 is_first = false;
7074 } else {
7075 text += "\n";
7076 }
7077 let mut len = 0;
7078 for chunk in buffer.text_for_range(selection.start..selection.end) {
7079 text.push_str(chunk);
7080 len += chunk.len();
7081 }
7082 clipboard_selections.push(ClipboardSelection {
7083 len,
7084 is_entire_line,
7085 first_line_indent: buffer
7086 .indent_size_for_line(MultiBufferRow(selection.start.row))
7087 .len,
7088 });
7089 }
7090 }
7091
7092 self.transact(cx, |this, cx| {
7093 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7094 s.select(selections);
7095 });
7096 this.insert("", cx);
7097 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7098 text,
7099 clipboard_selections,
7100 ));
7101 });
7102 }
7103
7104 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7105 let selections = self.selections.all::<Point>(cx);
7106 let buffer = self.buffer.read(cx).read(cx);
7107 let mut text = String::new();
7108
7109 let mut clipboard_selections = Vec::with_capacity(selections.len());
7110 {
7111 let max_point = buffer.max_point();
7112 let mut is_first = true;
7113 for selection in selections.iter() {
7114 let mut start = selection.start;
7115 let mut end = selection.end;
7116 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7117 if is_entire_line {
7118 start = Point::new(start.row, 0);
7119 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7120 }
7121 if is_first {
7122 is_first = false;
7123 } else {
7124 text += "\n";
7125 }
7126 let mut len = 0;
7127 for chunk in buffer.text_for_range(start..end) {
7128 text.push_str(chunk);
7129 len += chunk.len();
7130 }
7131 clipboard_selections.push(ClipboardSelection {
7132 len,
7133 is_entire_line,
7134 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7135 });
7136 }
7137 }
7138
7139 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7140 text,
7141 clipboard_selections,
7142 ));
7143 }
7144
7145 pub fn do_paste(
7146 &mut self,
7147 text: &String,
7148 clipboard_selections: Option<Vec<ClipboardSelection>>,
7149 handle_entire_lines: bool,
7150 cx: &mut ViewContext<Self>,
7151 ) {
7152 if self.read_only(cx) {
7153 return;
7154 }
7155
7156 let clipboard_text = Cow::Borrowed(text);
7157
7158 self.transact(cx, |this, cx| {
7159 if let Some(mut clipboard_selections) = clipboard_selections {
7160 let old_selections = this.selections.all::<usize>(cx);
7161 let all_selections_were_entire_line =
7162 clipboard_selections.iter().all(|s| s.is_entire_line);
7163 let first_selection_indent_column =
7164 clipboard_selections.first().map(|s| s.first_line_indent);
7165 if clipboard_selections.len() != old_selections.len() {
7166 clipboard_selections.drain(..);
7167 }
7168
7169 this.buffer.update(cx, |buffer, cx| {
7170 let snapshot = buffer.read(cx);
7171 let mut start_offset = 0;
7172 let mut edits = Vec::new();
7173 let mut original_indent_columns = Vec::new();
7174 for (ix, selection) in old_selections.iter().enumerate() {
7175 let to_insert;
7176 let entire_line;
7177 let original_indent_column;
7178 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7179 let end_offset = start_offset + clipboard_selection.len;
7180 to_insert = &clipboard_text[start_offset..end_offset];
7181 entire_line = clipboard_selection.is_entire_line;
7182 start_offset = end_offset + 1;
7183 original_indent_column = Some(clipboard_selection.first_line_indent);
7184 } else {
7185 to_insert = clipboard_text.as_str();
7186 entire_line = all_selections_were_entire_line;
7187 original_indent_column = first_selection_indent_column
7188 }
7189
7190 // If the corresponding selection was empty when this slice of the
7191 // clipboard text was written, then the entire line containing the
7192 // selection was copied. If this selection is also currently empty,
7193 // then paste the line before the current line of the buffer.
7194 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7195 let column = selection.start.to_point(&snapshot).column as usize;
7196 let line_start = selection.start - column;
7197 line_start..line_start
7198 } else {
7199 selection.range()
7200 };
7201
7202 edits.push((range, to_insert));
7203 original_indent_columns.extend(original_indent_column);
7204 }
7205 drop(snapshot);
7206
7207 buffer.edit(
7208 edits,
7209 Some(AutoindentMode::Block {
7210 original_indent_columns,
7211 }),
7212 cx,
7213 );
7214 });
7215
7216 let selections = this.selections.all::<usize>(cx);
7217 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7218 } else {
7219 this.insert(&clipboard_text, cx);
7220 }
7221 });
7222 }
7223
7224 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7225 if let Some(item) = cx.read_from_clipboard() {
7226 let entries = item.entries();
7227
7228 match entries.first() {
7229 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7230 // of all the pasted entries.
7231 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7232 .do_paste(
7233 clipboard_string.text(),
7234 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7235 true,
7236 cx,
7237 ),
7238 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7239 }
7240 }
7241 }
7242
7243 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7244 if self.read_only(cx) {
7245 return;
7246 }
7247
7248 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7249 if let Some((selections, _)) =
7250 self.selection_history.transaction(transaction_id).cloned()
7251 {
7252 self.change_selections(None, cx, |s| {
7253 s.select_anchors(selections.to_vec());
7254 });
7255 }
7256 self.request_autoscroll(Autoscroll::fit(), cx);
7257 self.unmark_text(cx);
7258 self.refresh_inline_completion(true, false, cx);
7259 cx.emit(EditorEvent::Edited { transaction_id });
7260 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7261 }
7262 }
7263
7264 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7265 if self.read_only(cx) {
7266 return;
7267 }
7268
7269 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7270 if let Some((_, Some(selections))) =
7271 self.selection_history.transaction(transaction_id).cloned()
7272 {
7273 self.change_selections(None, cx, |s| {
7274 s.select_anchors(selections.to_vec());
7275 });
7276 }
7277 self.request_autoscroll(Autoscroll::fit(), cx);
7278 self.unmark_text(cx);
7279 self.refresh_inline_completion(true, false, cx);
7280 cx.emit(EditorEvent::Edited { transaction_id });
7281 }
7282 }
7283
7284 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7285 self.buffer
7286 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7287 }
7288
7289 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7290 self.buffer
7291 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7292 }
7293
7294 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7295 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7296 let line_mode = s.line_mode;
7297 s.move_with(|map, selection| {
7298 let cursor = if selection.is_empty() && !line_mode {
7299 movement::left(map, selection.start)
7300 } else {
7301 selection.start
7302 };
7303 selection.collapse_to(cursor, SelectionGoal::None);
7304 });
7305 })
7306 }
7307
7308 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7309 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7310 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7311 })
7312 }
7313
7314 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7315 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7316 let line_mode = s.line_mode;
7317 s.move_with(|map, selection| {
7318 let cursor = if selection.is_empty() && !line_mode {
7319 movement::right(map, selection.end)
7320 } else {
7321 selection.end
7322 };
7323 selection.collapse_to(cursor, SelectionGoal::None)
7324 });
7325 })
7326 }
7327
7328 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7329 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7330 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7331 })
7332 }
7333
7334 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7335 if self.take_rename(true, cx).is_some() {
7336 return;
7337 }
7338
7339 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7340 cx.propagate();
7341 return;
7342 }
7343
7344 let text_layout_details = &self.text_layout_details(cx);
7345 let selection_count = self.selections.count();
7346 let first_selection = self.selections.first_anchor();
7347
7348 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7349 let line_mode = s.line_mode;
7350 s.move_with(|map, selection| {
7351 if !selection.is_empty() && !line_mode {
7352 selection.goal = SelectionGoal::None;
7353 }
7354 let (cursor, goal) = movement::up(
7355 map,
7356 selection.start,
7357 selection.goal,
7358 false,
7359 text_layout_details,
7360 );
7361 selection.collapse_to(cursor, goal);
7362 });
7363 });
7364
7365 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7366 {
7367 cx.propagate();
7368 }
7369 }
7370
7371 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7372 if self.take_rename(true, cx).is_some() {
7373 return;
7374 }
7375
7376 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7377 cx.propagate();
7378 return;
7379 }
7380
7381 let text_layout_details = &self.text_layout_details(cx);
7382
7383 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7384 let line_mode = s.line_mode;
7385 s.move_with(|map, selection| {
7386 if !selection.is_empty() && !line_mode {
7387 selection.goal = SelectionGoal::None;
7388 }
7389 let (cursor, goal) = movement::up_by_rows(
7390 map,
7391 selection.start,
7392 action.lines,
7393 selection.goal,
7394 false,
7395 text_layout_details,
7396 );
7397 selection.collapse_to(cursor, goal);
7398 });
7399 })
7400 }
7401
7402 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7403 if self.take_rename(true, cx).is_some() {
7404 return;
7405 }
7406
7407 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7408 cx.propagate();
7409 return;
7410 }
7411
7412 let text_layout_details = &self.text_layout_details(cx);
7413
7414 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7415 let line_mode = s.line_mode;
7416 s.move_with(|map, selection| {
7417 if !selection.is_empty() && !line_mode {
7418 selection.goal = SelectionGoal::None;
7419 }
7420 let (cursor, goal) = movement::down_by_rows(
7421 map,
7422 selection.start,
7423 action.lines,
7424 selection.goal,
7425 false,
7426 text_layout_details,
7427 );
7428 selection.collapse_to(cursor, goal);
7429 });
7430 })
7431 }
7432
7433 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7434 let text_layout_details = &self.text_layout_details(cx);
7435 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7436 s.move_heads_with(|map, head, goal| {
7437 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7438 })
7439 })
7440 }
7441
7442 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7443 let text_layout_details = &self.text_layout_details(cx);
7444 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7445 s.move_heads_with(|map, head, goal| {
7446 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7447 })
7448 })
7449 }
7450
7451 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7452 let Some(row_count) = self.visible_row_count() else {
7453 return;
7454 };
7455
7456 let text_layout_details = &self.text_layout_details(cx);
7457
7458 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7459 s.move_heads_with(|map, head, goal| {
7460 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7461 })
7462 })
7463 }
7464
7465 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7466 if self.take_rename(true, cx).is_some() {
7467 return;
7468 }
7469
7470 if self
7471 .context_menu
7472 .write()
7473 .as_mut()
7474 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7475 .unwrap_or(false)
7476 {
7477 return;
7478 }
7479
7480 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7481 cx.propagate();
7482 return;
7483 }
7484
7485 let Some(row_count) = self.visible_row_count() else {
7486 return;
7487 };
7488
7489 let autoscroll = if action.center_cursor {
7490 Autoscroll::center()
7491 } else {
7492 Autoscroll::fit()
7493 };
7494
7495 let text_layout_details = &self.text_layout_details(cx);
7496
7497 self.change_selections(Some(autoscroll), cx, |s| {
7498 let line_mode = s.line_mode;
7499 s.move_with(|map, selection| {
7500 if !selection.is_empty() && !line_mode {
7501 selection.goal = SelectionGoal::None;
7502 }
7503 let (cursor, goal) = movement::up_by_rows(
7504 map,
7505 selection.end,
7506 row_count,
7507 selection.goal,
7508 false,
7509 text_layout_details,
7510 );
7511 selection.collapse_to(cursor, goal);
7512 });
7513 });
7514 }
7515
7516 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7517 let text_layout_details = &self.text_layout_details(cx);
7518 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7519 s.move_heads_with(|map, head, goal| {
7520 movement::up(map, head, goal, false, text_layout_details)
7521 })
7522 })
7523 }
7524
7525 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7526 self.take_rename(true, cx);
7527
7528 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7529 cx.propagate();
7530 return;
7531 }
7532
7533 let text_layout_details = &self.text_layout_details(cx);
7534 let selection_count = self.selections.count();
7535 let first_selection = self.selections.first_anchor();
7536
7537 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7538 let line_mode = s.line_mode;
7539 s.move_with(|map, selection| {
7540 if !selection.is_empty() && !line_mode {
7541 selection.goal = SelectionGoal::None;
7542 }
7543 let (cursor, goal) = movement::down(
7544 map,
7545 selection.end,
7546 selection.goal,
7547 false,
7548 text_layout_details,
7549 );
7550 selection.collapse_to(cursor, goal);
7551 });
7552 });
7553
7554 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7555 {
7556 cx.propagate();
7557 }
7558 }
7559
7560 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7561 let Some(row_count) = self.visible_row_count() else {
7562 return;
7563 };
7564
7565 let text_layout_details = &self.text_layout_details(cx);
7566
7567 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7568 s.move_heads_with(|map, head, goal| {
7569 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7570 })
7571 })
7572 }
7573
7574 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7575 if self.take_rename(true, cx).is_some() {
7576 return;
7577 }
7578
7579 if self
7580 .context_menu
7581 .write()
7582 .as_mut()
7583 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7584 .unwrap_or(false)
7585 {
7586 return;
7587 }
7588
7589 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7590 cx.propagate();
7591 return;
7592 }
7593
7594 let Some(row_count) = self.visible_row_count() else {
7595 return;
7596 };
7597
7598 let autoscroll = if action.center_cursor {
7599 Autoscroll::center()
7600 } else {
7601 Autoscroll::fit()
7602 };
7603
7604 let text_layout_details = &self.text_layout_details(cx);
7605 self.change_selections(Some(autoscroll), cx, |s| {
7606 let line_mode = s.line_mode;
7607 s.move_with(|map, selection| {
7608 if !selection.is_empty() && !line_mode {
7609 selection.goal = SelectionGoal::None;
7610 }
7611 let (cursor, goal) = movement::down_by_rows(
7612 map,
7613 selection.end,
7614 row_count,
7615 selection.goal,
7616 false,
7617 text_layout_details,
7618 );
7619 selection.collapse_to(cursor, goal);
7620 });
7621 });
7622 }
7623
7624 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7625 let text_layout_details = &self.text_layout_details(cx);
7626 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7627 s.move_heads_with(|map, head, goal| {
7628 movement::down(map, head, goal, false, text_layout_details)
7629 })
7630 });
7631 }
7632
7633 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7634 if let Some(context_menu) = self.context_menu.write().as_mut() {
7635 context_menu.select_first(self.project.as_ref(), cx);
7636 }
7637 }
7638
7639 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7640 if let Some(context_menu) = self.context_menu.write().as_mut() {
7641 context_menu.select_prev(self.project.as_ref(), cx);
7642 }
7643 }
7644
7645 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7646 if let Some(context_menu) = self.context_menu.write().as_mut() {
7647 context_menu.select_next(self.project.as_ref(), cx);
7648 }
7649 }
7650
7651 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7652 if let Some(context_menu) = self.context_menu.write().as_mut() {
7653 context_menu.select_last(self.project.as_ref(), cx);
7654 }
7655 }
7656
7657 pub fn move_to_previous_word_start(
7658 &mut self,
7659 _: &MoveToPreviousWordStart,
7660 cx: &mut ViewContext<Self>,
7661 ) {
7662 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7663 s.move_cursors_with(|map, head, _| {
7664 (
7665 movement::previous_word_start(map, head),
7666 SelectionGoal::None,
7667 )
7668 });
7669 })
7670 }
7671
7672 pub fn move_to_previous_subword_start(
7673 &mut self,
7674 _: &MoveToPreviousSubwordStart,
7675 cx: &mut ViewContext<Self>,
7676 ) {
7677 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7678 s.move_cursors_with(|map, head, _| {
7679 (
7680 movement::previous_subword_start(map, head),
7681 SelectionGoal::None,
7682 )
7683 });
7684 })
7685 }
7686
7687 pub fn select_to_previous_word_start(
7688 &mut self,
7689 _: &SelectToPreviousWordStart,
7690 cx: &mut ViewContext<Self>,
7691 ) {
7692 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7693 s.move_heads_with(|map, head, _| {
7694 (
7695 movement::previous_word_start(map, head),
7696 SelectionGoal::None,
7697 )
7698 });
7699 })
7700 }
7701
7702 pub fn select_to_previous_subword_start(
7703 &mut self,
7704 _: &SelectToPreviousSubwordStart,
7705 cx: &mut ViewContext<Self>,
7706 ) {
7707 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7708 s.move_heads_with(|map, head, _| {
7709 (
7710 movement::previous_subword_start(map, head),
7711 SelectionGoal::None,
7712 )
7713 });
7714 })
7715 }
7716
7717 pub fn delete_to_previous_word_start(
7718 &mut self,
7719 action: &DeleteToPreviousWordStart,
7720 cx: &mut ViewContext<Self>,
7721 ) {
7722 self.transact(cx, |this, cx| {
7723 this.select_autoclose_pair(cx);
7724 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7725 let line_mode = s.line_mode;
7726 s.move_with(|map, selection| {
7727 if selection.is_empty() && !line_mode {
7728 let cursor = if action.ignore_newlines {
7729 movement::previous_word_start(map, selection.head())
7730 } else {
7731 movement::previous_word_start_or_newline(map, selection.head())
7732 };
7733 selection.set_head(cursor, SelectionGoal::None);
7734 }
7735 });
7736 });
7737 this.insert("", cx);
7738 });
7739 }
7740
7741 pub fn delete_to_previous_subword_start(
7742 &mut self,
7743 _: &DeleteToPreviousSubwordStart,
7744 cx: &mut ViewContext<Self>,
7745 ) {
7746 self.transact(cx, |this, cx| {
7747 this.select_autoclose_pair(cx);
7748 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7749 let line_mode = s.line_mode;
7750 s.move_with(|map, selection| {
7751 if selection.is_empty() && !line_mode {
7752 let cursor = movement::previous_subword_start(map, selection.head());
7753 selection.set_head(cursor, SelectionGoal::None);
7754 }
7755 });
7756 });
7757 this.insert("", cx);
7758 });
7759 }
7760
7761 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7762 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7763 s.move_cursors_with(|map, head, _| {
7764 (movement::next_word_end(map, head), SelectionGoal::None)
7765 });
7766 })
7767 }
7768
7769 pub fn move_to_next_subword_end(
7770 &mut self,
7771 _: &MoveToNextSubwordEnd,
7772 cx: &mut ViewContext<Self>,
7773 ) {
7774 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7775 s.move_cursors_with(|map, head, _| {
7776 (movement::next_subword_end(map, head), SelectionGoal::None)
7777 });
7778 })
7779 }
7780
7781 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7782 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7783 s.move_heads_with(|map, head, _| {
7784 (movement::next_word_end(map, head), SelectionGoal::None)
7785 });
7786 })
7787 }
7788
7789 pub fn select_to_next_subword_end(
7790 &mut self,
7791 _: &SelectToNextSubwordEnd,
7792 cx: &mut ViewContext<Self>,
7793 ) {
7794 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7795 s.move_heads_with(|map, head, _| {
7796 (movement::next_subword_end(map, head), SelectionGoal::None)
7797 });
7798 })
7799 }
7800
7801 pub fn delete_to_next_word_end(
7802 &mut self,
7803 action: &DeleteToNextWordEnd,
7804 cx: &mut ViewContext<Self>,
7805 ) {
7806 self.transact(cx, |this, cx| {
7807 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7808 let line_mode = s.line_mode;
7809 s.move_with(|map, selection| {
7810 if selection.is_empty() && !line_mode {
7811 let cursor = if action.ignore_newlines {
7812 movement::next_word_end(map, selection.head())
7813 } else {
7814 movement::next_word_end_or_newline(map, selection.head())
7815 };
7816 selection.set_head(cursor, SelectionGoal::None);
7817 }
7818 });
7819 });
7820 this.insert("", cx);
7821 });
7822 }
7823
7824 pub fn delete_to_next_subword_end(
7825 &mut self,
7826 _: &DeleteToNextSubwordEnd,
7827 cx: &mut ViewContext<Self>,
7828 ) {
7829 self.transact(cx, |this, cx| {
7830 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7831 s.move_with(|map, selection| {
7832 if selection.is_empty() {
7833 let cursor = movement::next_subword_end(map, selection.head());
7834 selection.set_head(cursor, SelectionGoal::None);
7835 }
7836 });
7837 });
7838 this.insert("", cx);
7839 });
7840 }
7841
7842 pub fn move_to_beginning_of_line(
7843 &mut self,
7844 action: &MoveToBeginningOfLine,
7845 cx: &mut ViewContext<Self>,
7846 ) {
7847 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7848 s.move_cursors_with(|map, head, _| {
7849 (
7850 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7851 SelectionGoal::None,
7852 )
7853 });
7854 })
7855 }
7856
7857 pub fn select_to_beginning_of_line(
7858 &mut self,
7859 action: &SelectToBeginningOfLine,
7860 cx: &mut ViewContext<Self>,
7861 ) {
7862 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7863 s.move_heads_with(|map, head, _| {
7864 (
7865 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7866 SelectionGoal::None,
7867 )
7868 });
7869 });
7870 }
7871
7872 pub fn delete_to_beginning_of_line(
7873 &mut self,
7874 _: &DeleteToBeginningOfLine,
7875 cx: &mut ViewContext<Self>,
7876 ) {
7877 self.transact(cx, |this, cx| {
7878 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7879 s.move_with(|_, selection| {
7880 selection.reversed = true;
7881 });
7882 });
7883
7884 this.select_to_beginning_of_line(
7885 &SelectToBeginningOfLine {
7886 stop_at_soft_wraps: false,
7887 },
7888 cx,
7889 );
7890 this.backspace(&Backspace, cx);
7891 });
7892 }
7893
7894 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7895 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7896 s.move_cursors_with(|map, head, _| {
7897 (
7898 movement::line_end(map, head, action.stop_at_soft_wraps),
7899 SelectionGoal::None,
7900 )
7901 });
7902 })
7903 }
7904
7905 pub fn select_to_end_of_line(
7906 &mut self,
7907 action: &SelectToEndOfLine,
7908 cx: &mut ViewContext<Self>,
7909 ) {
7910 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7911 s.move_heads_with(|map, head, _| {
7912 (
7913 movement::line_end(map, head, action.stop_at_soft_wraps),
7914 SelectionGoal::None,
7915 )
7916 });
7917 })
7918 }
7919
7920 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7921 self.transact(cx, |this, cx| {
7922 this.select_to_end_of_line(
7923 &SelectToEndOfLine {
7924 stop_at_soft_wraps: false,
7925 },
7926 cx,
7927 );
7928 this.delete(&Delete, cx);
7929 });
7930 }
7931
7932 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7933 self.transact(cx, |this, cx| {
7934 this.select_to_end_of_line(
7935 &SelectToEndOfLine {
7936 stop_at_soft_wraps: false,
7937 },
7938 cx,
7939 );
7940 this.cut(&Cut, cx);
7941 });
7942 }
7943
7944 pub fn move_to_start_of_paragraph(
7945 &mut self,
7946 _: &MoveToStartOfParagraph,
7947 cx: &mut ViewContext<Self>,
7948 ) {
7949 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7950 cx.propagate();
7951 return;
7952 }
7953
7954 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7955 s.move_with(|map, selection| {
7956 selection.collapse_to(
7957 movement::start_of_paragraph(map, selection.head(), 1),
7958 SelectionGoal::None,
7959 )
7960 });
7961 })
7962 }
7963
7964 pub fn move_to_end_of_paragraph(
7965 &mut self,
7966 _: &MoveToEndOfParagraph,
7967 cx: &mut ViewContext<Self>,
7968 ) {
7969 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7970 cx.propagate();
7971 return;
7972 }
7973
7974 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7975 s.move_with(|map, selection| {
7976 selection.collapse_to(
7977 movement::end_of_paragraph(map, selection.head(), 1),
7978 SelectionGoal::None,
7979 )
7980 });
7981 })
7982 }
7983
7984 pub fn select_to_start_of_paragraph(
7985 &mut self,
7986 _: &SelectToStartOfParagraph,
7987 cx: &mut ViewContext<Self>,
7988 ) {
7989 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7990 cx.propagate();
7991 return;
7992 }
7993
7994 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7995 s.move_heads_with(|map, head, _| {
7996 (
7997 movement::start_of_paragraph(map, head, 1),
7998 SelectionGoal::None,
7999 )
8000 });
8001 })
8002 }
8003
8004 pub fn select_to_end_of_paragraph(
8005 &mut self,
8006 _: &SelectToEndOfParagraph,
8007 cx: &mut ViewContext<Self>,
8008 ) {
8009 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8010 cx.propagate();
8011 return;
8012 }
8013
8014 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8015 s.move_heads_with(|map, head, _| {
8016 (
8017 movement::end_of_paragraph(map, head, 1),
8018 SelectionGoal::None,
8019 )
8020 });
8021 })
8022 }
8023
8024 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8025 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8026 cx.propagate();
8027 return;
8028 }
8029
8030 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8031 s.select_ranges(vec![0..0]);
8032 });
8033 }
8034
8035 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8036 let mut selection = self.selections.last::<Point>(cx);
8037 selection.set_head(Point::zero(), SelectionGoal::None);
8038
8039 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8040 s.select(vec![selection]);
8041 });
8042 }
8043
8044 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8045 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8046 cx.propagate();
8047 return;
8048 }
8049
8050 let cursor = self.buffer.read(cx).read(cx).len();
8051 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8052 s.select_ranges(vec![cursor..cursor])
8053 });
8054 }
8055
8056 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8057 self.nav_history = nav_history;
8058 }
8059
8060 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8061 self.nav_history.as_ref()
8062 }
8063
8064 fn push_to_nav_history(
8065 &mut self,
8066 cursor_anchor: Anchor,
8067 new_position: Option<Point>,
8068 cx: &mut ViewContext<Self>,
8069 ) {
8070 if let Some(nav_history) = self.nav_history.as_mut() {
8071 let buffer = self.buffer.read(cx).read(cx);
8072 let cursor_position = cursor_anchor.to_point(&buffer);
8073 let scroll_state = self.scroll_manager.anchor();
8074 let scroll_top_row = scroll_state.top_row(&buffer);
8075 drop(buffer);
8076
8077 if let Some(new_position) = new_position {
8078 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8079 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8080 return;
8081 }
8082 }
8083
8084 nav_history.push(
8085 Some(NavigationData {
8086 cursor_anchor,
8087 cursor_position,
8088 scroll_anchor: scroll_state,
8089 scroll_top_row,
8090 }),
8091 cx,
8092 );
8093 }
8094 }
8095
8096 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8097 let buffer = self.buffer.read(cx).snapshot(cx);
8098 let mut selection = self.selections.first::<usize>(cx);
8099 selection.set_head(buffer.len(), SelectionGoal::None);
8100 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8101 s.select(vec![selection]);
8102 });
8103 }
8104
8105 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8106 let end = self.buffer.read(cx).read(cx).len();
8107 self.change_selections(None, cx, |s| {
8108 s.select_ranges(vec![0..end]);
8109 });
8110 }
8111
8112 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8113 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8114 let mut selections = self.selections.all::<Point>(cx);
8115 let max_point = display_map.buffer_snapshot.max_point();
8116 for selection in &mut selections {
8117 let rows = selection.spanned_rows(true, &display_map);
8118 selection.start = Point::new(rows.start.0, 0);
8119 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8120 selection.reversed = false;
8121 }
8122 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8123 s.select(selections);
8124 });
8125 }
8126
8127 pub fn split_selection_into_lines(
8128 &mut self,
8129 _: &SplitSelectionIntoLines,
8130 cx: &mut ViewContext<Self>,
8131 ) {
8132 let mut to_unfold = Vec::new();
8133 let mut new_selection_ranges = Vec::new();
8134 {
8135 let selections = self.selections.all::<Point>(cx);
8136 let buffer = self.buffer.read(cx).read(cx);
8137 for selection in selections {
8138 for row in selection.start.row..selection.end.row {
8139 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8140 new_selection_ranges.push(cursor..cursor);
8141 }
8142 new_selection_ranges.push(selection.end..selection.end);
8143 to_unfold.push(selection.start..selection.end);
8144 }
8145 }
8146 self.unfold_ranges(to_unfold, true, true, cx);
8147 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8148 s.select_ranges(new_selection_ranges);
8149 });
8150 }
8151
8152 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8153 self.add_selection(true, cx);
8154 }
8155
8156 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8157 self.add_selection(false, cx);
8158 }
8159
8160 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8161 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8162 let mut selections = self.selections.all::<Point>(cx);
8163 let text_layout_details = self.text_layout_details(cx);
8164 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8165 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8166 let range = oldest_selection.display_range(&display_map).sorted();
8167
8168 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8169 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8170 let positions = start_x.min(end_x)..start_x.max(end_x);
8171
8172 selections.clear();
8173 let mut stack = Vec::new();
8174 for row in range.start.row().0..=range.end.row().0 {
8175 if let Some(selection) = self.selections.build_columnar_selection(
8176 &display_map,
8177 DisplayRow(row),
8178 &positions,
8179 oldest_selection.reversed,
8180 &text_layout_details,
8181 ) {
8182 stack.push(selection.id);
8183 selections.push(selection);
8184 }
8185 }
8186
8187 if above {
8188 stack.reverse();
8189 }
8190
8191 AddSelectionsState { above, stack }
8192 });
8193
8194 let last_added_selection = *state.stack.last().unwrap();
8195 let mut new_selections = Vec::new();
8196 if above == state.above {
8197 let end_row = if above {
8198 DisplayRow(0)
8199 } else {
8200 display_map.max_point().row()
8201 };
8202
8203 'outer: for selection in selections {
8204 if selection.id == last_added_selection {
8205 let range = selection.display_range(&display_map).sorted();
8206 debug_assert_eq!(range.start.row(), range.end.row());
8207 let mut row = range.start.row();
8208 let positions =
8209 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8210 px(start)..px(end)
8211 } else {
8212 let start_x =
8213 display_map.x_for_display_point(range.start, &text_layout_details);
8214 let end_x =
8215 display_map.x_for_display_point(range.end, &text_layout_details);
8216 start_x.min(end_x)..start_x.max(end_x)
8217 };
8218
8219 while row != end_row {
8220 if above {
8221 row.0 -= 1;
8222 } else {
8223 row.0 += 1;
8224 }
8225
8226 if let Some(new_selection) = self.selections.build_columnar_selection(
8227 &display_map,
8228 row,
8229 &positions,
8230 selection.reversed,
8231 &text_layout_details,
8232 ) {
8233 state.stack.push(new_selection.id);
8234 if above {
8235 new_selections.push(new_selection);
8236 new_selections.push(selection);
8237 } else {
8238 new_selections.push(selection);
8239 new_selections.push(new_selection);
8240 }
8241
8242 continue 'outer;
8243 }
8244 }
8245 }
8246
8247 new_selections.push(selection);
8248 }
8249 } else {
8250 new_selections = selections;
8251 new_selections.retain(|s| s.id != last_added_selection);
8252 state.stack.pop();
8253 }
8254
8255 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8256 s.select(new_selections);
8257 });
8258 if state.stack.len() > 1 {
8259 self.add_selections_state = Some(state);
8260 }
8261 }
8262
8263 pub fn select_next_match_internal(
8264 &mut self,
8265 display_map: &DisplaySnapshot,
8266 replace_newest: bool,
8267 autoscroll: Option<Autoscroll>,
8268 cx: &mut ViewContext<Self>,
8269 ) -> Result<()> {
8270 fn select_next_match_ranges(
8271 this: &mut Editor,
8272 range: Range<usize>,
8273 replace_newest: bool,
8274 auto_scroll: Option<Autoscroll>,
8275 cx: &mut ViewContext<Editor>,
8276 ) {
8277 this.unfold_ranges([range.clone()], false, true, cx);
8278 this.change_selections(auto_scroll, cx, |s| {
8279 if replace_newest {
8280 s.delete(s.newest_anchor().id);
8281 }
8282 s.insert_range(range.clone());
8283 });
8284 }
8285
8286 let buffer = &display_map.buffer_snapshot;
8287 let mut selections = self.selections.all::<usize>(cx);
8288 if let Some(mut select_next_state) = self.select_next_state.take() {
8289 let query = &select_next_state.query;
8290 if !select_next_state.done {
8291 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8292 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8293 let mut next_selected_range = None;
8294
8295 let bytes_after_last_selection =
8296 buffer.bytes_in_range(last_selection.end..buffer.len());
8297 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8298 let query_matches = query
8299 .stream_find_iter(bytes_after_last_selection)
8300 .map(|result| (last_selection.end, result))
8301 .chain(
8302 query
8303 .stream_find_iter(bytes_before_first_selection)
8304 .map(|result| (0, result)),
8305 );
8306
8307 for (start_offset, query_match) in query_matches {
8308 let query_match = query_match.unwrap(); // can only fail due to I/O
8309 let offset_range =
8310 start_offset + query_match.start()..start_offset + query_match.end();
8311 let display_range = offset_range.start.to_display_point(display_map)
8312 ..offset_range.end.to_display_point(display_map);
8313
8314 if !select_next_state.wordwise
8315 || (!movement::is_inside_word(display_map, display_range.start)
8316 && !movement::is_inside_word(display_map, display_range.end))
8317 {
8318 // TODO: This is n^2, because we might check all the selections
8319 if !selections
8320 .iter()
8321 .any(|selection| selection.range().overlaps(&offset_range))
8322 {
8323 next_selected_range = Some(offset_range);
8324 break;
8325 }
8326 }
8327 }
8328
8329 if let Some(next_selected_range) = next_selected_range {
8330 select_next_match_ranges(
8331 self,
8332 next_selected_range,
8333 replace_newest,
8334 autoscroll,
8335 cx,
8336 );
8337 } else {
8338 select_next_state.done = true;
8339 }
8340 }
8341
8342 self.select_next_state = Some(select_next_state);
8343 } else {
8344 let mut only_carets = true;
8345 let mut same_text_selected = true;
8346 let mut selected_text = None;
8347
8348 let mut selections_iter = selections.iter().peekable();
8349 while let Some(selection) = selections_iter.next() {
8350 if selection.start != selection.end {
8351 only_carets = false;
8352 }
8353
8354 if same_text_selected {
8355 if selected_text.is_none() {
8356 selected_text =
8357 Some(buffer.text_for_range(selection.range()).collect::<String>());
8358 }
8359
8360 if let Some(next_selection) = selections_iter.peek() {
8361 if next_selection.range().len() == selection.range().len() {
8362 let next_selected_text = buffer
8363 .text_for_range(next_selection.range())
8364 .collect::<String>();
8365 if Some(next_selected_text) != selected_text {
8366 same_text_selected = false;
8367 selected_text = None;
8368 }
8369 } else {
8370 same_text_selected = false;
8371 selected_text = None;
8372 }
8373 }
8374 }
8375 }
8376
8377 if only_carets {
8378 for selection in &mut selections {
8379 let word_range = movement::surrounding_word(
8380 display_map,
8381 selection.start.to_display_point(display_map),
8382 );
8383 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8384 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8385 selection.goal = SelectionGoal::None;
8386 selection.reversed = false;
8387 select_next_match_ranges(
8388 self,
8389 selection.start..selection.end,
8390 replace_newest,
8391 autoscroll,
8392 cx,
8393 );
8394 }
8395
8396 if selections.len() == 1 {
8397 let selection = selections
8398 .last()
8399 .expect("ensured that there's only one selection");
8400 let query = buffer
8401 .text_for_range(selection.start..selection.end)
8402 .collect::<String>();
8403 let is_empty = query.is_empty();
8404 let select_state = SelectNextState {
8405 query: AhoCorasick::new(&[query])?,
8406 wordwise: true,
8407 done: is_empty,
8408 };
8409 self.select_next_state = Some(select_state);
8410 } else {
8411 self.select_next_state = None;
8412 }
8413 } else if let Some(selected_text) = selected_text {
8414 self.select_next_state = Some(SelectNextState {
8415 query: AhoCorasick::new(&[selected_text])?,
8416 wordwise: false,
8417 done: false,
8418 });
8419 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8420 }
8421 }
8422 Ok(())
8423 }
8424
8425 pub fn select_all_matches(
8426 &mut self,
8427 _action: &SelectAllMatches,
8428 cx: &mut ViewContext<Self>,
8429 ) -> Result<()> {
8430 self.push_to_selection_history();
8431 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8432
8433 self.select_next_match_internal(&display_map, false, None, cx)?;
8434 let Some(select_next_state) = self.select_next_state.as_mut() else {
8435 return Ok(());
8436 };
8437 if select_next_state.done {
8438 return Ok(());
8439 }
8440
8441 let mut new_selections = self.selections.all::<usize>(cx);
8442
8443 let buffer = &display_map.buffer_snapshot;
8444 let query_matches = select_next_state
8445 .query
8446 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8447
8448 for query_match in query_matches {
8449 let query_match = query_match.unwrap(); // can only fail due to I/O
8450 let offset_range = query_match.start()..query_match.end();
8451 let display_range = offset_range.start.to_display_point(&display_map)
8452 ..offset_range.end.to_display_point(&display_map);
8453
8454 if !select_next_state.wordwise
8455 || (!movement::is_inside_word(&display_map, display_range.start)
8456 && !movement::is_inside_word(&display_map, display_range.end))
8457 {
8458 self.selections.change_with(cx, |selections| {
8459 new_selections.push(Selection {
8460 id: selections.new_selection_id(),
8461 start: offset_range.start,
8462 end: offset_range.end,
8463 reversed: false,
8464 goal: SelectionGoal::None,
8465 });
8466 });
8467 }
8468 }
8469
8470 new_selections.sort_by_key(|selection| selection.start);
8471 let mut ix = 0;
8472 while ix + 1 < new_selections.len() {
8473 let current_selection = &new_selections[ix];
8474 let next_selection = &new_selections[ix + 1];
8475 if current_selection.range().overlaps(&next_selection.range()) {
8476 if current_selection.id < next_selection.id {
8477 new_selections.remove(ix + 1);
8478 } else {
8479 new_selections.remove(ix);
8480 }
8481 } else {
8482 ix += 1;
8483 }
8484 }
8485
8486 select_next_state.done = true;
8487 self.unfold_ranges(
8488 new_selections.iter().map(|selection| selection.range()),
8489 false,
8490 false,
8491 cx,
8492 );
8493 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8494 selections.select(new_selections)
8495 });
8496
8497 Ok(())
8498 }
8499
8500 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8501 self.push_to_selection_history();
8502 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8503 self.select_next_match_internal(
8504 &display_map,
8505 action.replace_newest,
8506 Some(Autoscroll::newest()),
8507 cx,
8508 )?;
8509 Ok(())
8510 }
8511
8512 pub fn select_previous(
8513 &mut self,
8514 action: &SelectPrevious,
8515 cx: &mut ViewContext<Self>,
8516 ) -> Result<()> {
8517 self.push_to_selection_history();
8518 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8519 let buffer = &display_map.buffer_snapshot;
8520 let mut selections = self.selections.all::<usize>(cx);
8521 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8522 let query = &select_prev_state.query;
8523 if !select_prev_state.done {
8524 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8525 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8526 let mut next_selected_range = None;
8527 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8528 let bytes_before_last_selection =
8529 buffer.reversed_bytes_in_range(0..last_selection.start);
8530 let bytes_after_first_selection =
8531 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8532 let query_matches = query
8533 .stream_find_iter(bytes_before_last_selection)
8534 .map(|result| (last_selection.start, result))
8535 .chain(
8536 query
8537 .stream_find_iter(bytes_after_first_selection)
8538 .map(|result| (buffer.len(), result)),
8539 );
8540 for (end_offset, query_match) in query_matches {
8541 let query_match = query_match.unwrap(); // can only fail due to I/O
8542 let offset_range =
8543 end_offset - query_match.end()..end_offset - query_match.start();
8544 let display_range = offset_range.start.to_display_point(&display_map)
8545 ..offset_range.end.to_display_point(&display_map);
8546
8547 if !select_prev_state.wordwise
8548 || (!movement::is_inside_word(&display_map, display_range.start)
8549 && !movement::is_inside_word(&display_map, display_range.end))
8550 {
8551 next_selected_range = Some(offset_range);
8552 break;
8553 }
8554 }
8555
8556 if let Some(next_selected_range) = next_selected_range {
8557 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8558 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8559 if action.replace_newest {
8560 s.delete(s.newest_anchor().id);
8561 }
8562 s.insert_range(next_selected_range);
8563 });
8564 } else {
8565 select_prev_state.done = true;
8566 }
8567 }
8568
8569 self.select_prev_state = Some(select_prev_state);
8570 } else {
8571 let mut only_carets = true;
8572 let mut same_text_selected = true;
8573 let mut selected_text = None;
8574
8575 let mut selections_iter = selections.iter().peekable();
8576 while let Some(selection) = selections_iter.next() {
8577 if selection.start != selection.end {
8578 only_carets = false;
8579 }
8580
8581 if same_text_selected {
8582 if selected_text.is_none() {
8583 selected_text =
8584 Some(buffer.text_for_range(selection.range()).collect::<String>());
8585 }
8586
8587 if let Some(next_selection) = selections_iter.peek() {
8588 if next_selection.range().len() == selection.range().len() {
8589 let next_selected_text = buffer
8590 .text_for_range(next_selection.range())
8591 .collect::<String>();
8592 if Some(next_selected_text) != selected_text {
8593 same_text_selected = false;
8594 selected_text = None;
8595 }
8596 } else {
8597 same_text_selected = false;
8598 selected_text = None;
8599 }
8600 }
8601 }
8602 }
8603
8604 if only_carets {
8605 for selection in &mut selections {
8606 let word_range = movement::surrounding_word(
8607 &display_map,
8608 selection.start.to_display_point(&display_map),
8609 );
8610 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8611 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8612 selection.goal = SelectionGoal::None;
8613 selection.reversed = false;
8614 }
8615 if selections.len() == 1 {
8616 let selection = selections
8617 .last()
8618 .expect("ensured that there's only one selection");
8619 let query = buffer
8620 .text_for_range(selection.start..selection.end)
8621 .collect::<String>();
8622 let is_empty = query.is_empty();
8623 let select_state = SelectNextState {
8624 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8625 wordwise: true,
8626 done: is_empty,
8627 };
8628 self.select_prev_state = Some(select_state);
8629 } else {
8630 self.select_prev_state = None;
8631 }
8632
8633 self.unfold_ranges(
8634 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8635 false,
8636 true,
8637 cx,
8638 );
8639 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8640 s.select(selections);
8641 });
8642 } else if let Some(selected_text) = selected_text {
8643 self.select_prev_state = Some(SelectNextState {
8644 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8645 wordwise: false,
8646 done: false,
8647 });
8648 self.select_previous(action, cx)?;
8649 }
8650 }
8651 Ok(())
8652 }
8653
8654 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8655 let text_layout_details = &self.text_layout_details(cx);
8656 self.transact(cx, |this, cx| {
8657 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8658 let mut edits = Vec::new();
8659 let mut selection_edit_ranges = Vec::new();
8660 let mut last_toggled_row = None;
8661 let snapshot = this.buffer.read(cx).read(cx);
8662 let empty_str: Arc<str> = Arc::default();
8663 let mut suffixes_inserted = Vec::new();
8664
8665 fn comment_prefix_range(
8666 snapshot: &MultiBufferSnapshot,
8667 row: MultiBufferRow,
8668 comment_prefix: &str,
8669 comment_prefix_whitespace: &str,
8670 ) -> Range<Point> {
8671 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8672
8673 let mut line_bytes = snapshot
8674 .bytes_in_range(start..snapshot.max_point())
8675 .flatten()
8676 .copied();
8677
8678 // If this line currently begins with the line comment prefix, then record
8679 // the range containing the prefix.
8680 if line_bytes
8681 .by_ref()
8682 .take(comment_prefix.len())
8683 .eq(comment_prefix.bytes())
8684 {
8685 // Include any whitespace that matches the comment prefix.
8686 let matching_whitespace_len = line_bytes
8687 .zip(comment_prefix_whitespace.bytes())
8688 .take_while(|(a, b)| a == b)
8689 .count() as u32;
8690 let end = Point::new(
8691 start.row,
8692 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8693 );
8694 start..end
8695 } else {
8696 start..start
8697 }
8698 }
8699
8700 fn comment_suffix_range(
8701 snapshot: &MultiBufferSnapshot,
8702 row: MultiBufferRow,
8703 comment_suffix: &str,
8704 comment_suffix_has_leading_space: bool,
8705 ) -> Range<Point> {
8706 let end = Point::new(row.0, snapshot.line_len(row));
8707 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8708
8709 let mut line_end_bytes = snapshot
8710 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8711 .flatten()
8712 .copied();
8713
8714 let leading_space_len = if suffix_start_column > 0
8715 && line_end_bytes.next() == Some(b' ')
8716 && comment_suffix_has_leading_space
8717 {
8718 1
8719 } else {
8720 0
8721 };
8722
8723 // If this line currently begins with the line comment prefix, then record
8724 // the range containing the prefix.
8725 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8726 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8727 start..end
8728 } else {
8729 end..end
8730 }
8731 }
8732
8733 // TODO: Handle selections that cross excerpts
8734 for selection in &mut selections {
8735 let start_column = snapshot
8736 .indent_size_for_line(MultiBufferRow(selection.start.row))
8737 .len;
8738 let language = if let Some(language) =
8739 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8740 {
8741 language
8742 } else {
8743 continue;
8744 };
8745
8746 selection_edit_ranges.clear();
8747
8748 // If multiple selections contain a given row, avoid processing that
8749 // row more than once.
8750 let mut start_row = MultiBufferRow(selection.start.row);
8751 if last_toggled_row == Some(start_row) {
8752 start_row = start_row.next_row();
8753 }
8754 let end_row =
8755 if selection.end.row > selection.start.row && selection.end.column == 0 {
8756 MultiBufferRow(selection.end.row - 1)
8757 } else {
8758 MultiBufferRow(selection.end.row)
8759 };
8760 last_toggled_row = Some(end_row);
8761
8762 if start_row > end_row {
8763 continue;
8764 }
8765
8766 // If the language has line comments, toggle those.
8767 let full_comment_prefixes = language.line_comment_prefixes();
8768 if !full_comment_prefixes.is_empty() {
8769 let first_prefix = full_comment_prefixes
8770 .first()
8771 .expect("prefixes is non-empty");
8772 let prefix_trimmed_lengths = full_comment_prefixes
8773 .iter()
8774 .map(|p| p.trim_end_matches(' ').len())
8775 .collect::<SmallVec<[usize; 4]>>();
8776
8777 let mut all_selection_lines_are_comments = true;
8778
8779 for row in start_row.0..=end_row.0 {
8780 let row = MultiBufferRow(row);
8781 if start_row < end_row && snapshot.is_line_blank(row) {
8782 continue;
8783 }
8784
8785 let prefix_range = full_comment_prefixes
8786 .iter()
8787 .zip(prefix_trimmed_lengths.iter().copied())
8788 .map(|(prefix, trimmed_prefix_len)| {
8789 comment_prefix_range(
8790 snapshot.deref(),
8791 row,
8792 &prefix[..trimmed_prefix_len],
8793 &prefix[trimmed_prefix_len..],
8794 )
8795 })
8796 .max_by_key(|range| range.end.column - range.start.column)
8797 .expect("prefixes is non-empty");
8798
8799 if prefix_range.is_empty() {
8800 all_selection_lines_are_comments = false;
8801 }
8802
8803 selection_edit_ranges.push(prefix_range);
8804 }
8805
8806 if all_selection_lines_are_comments {
8807 edits.extend(
8808 selection_edit_ranges
8809 .iter()
8810 .cloned()
8811 .map(|range| (range, empty_str.clone())),
8812 );
8813 } else {
8814 let min_column = selection_edit_ranges
8815 .iter()
8816 .map(|range| range.start.column)
8817 .min()
8818 .unwrap_or(0);
8819 edits.extend(selection_edit_ranges.iter().map(|range| {
8820 let position = Point::new(range.start.row, min_column);
8821 (position..position, first_prefix.clone())
8822 }));
8823 }
8824 } else if let Some((full_comment_prefix, comment_suffix)) =
8825 language.block_comment_delimiters()
8826 {
8827 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8828 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8829 let prefix_range = comment_prefix_range(
8830 snapshot.deref(),
8831 start_row,
8832 comment_prefix,
8833 comment_prefix_whitespace,
8834 );
8835 let suffix_range = comment_suffix_range(
8836 snapshot.deref(),
8837 end_row,
8838 comment_suffix.trim_start_matches(' '),
8839 comment_suffix.starts_with(' '),
8840 );
8841
8842 if prefix_range.is_empty() || suffix_range.is_empty() {
8843 edits.push((
8844 prefix_range.start..prefix_range.start,
8845 full_comment_prefix.clone(),
8846 ));
8847 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8848 suffixes_inserted.push((end_row, comment_suffix.len()));
8849 } else {
8850 edits.push((prefix_range, empty_str.clone()));
8851 edits.push((suffix_range, empty_str.clone()));
8852 }
8853 } else {
8854 continue;
8855 }
8856 }
8857
8858 drop(snapshot);
8859 this.buffer.update(cx, |buffer, cx| {
8860 buffer.edit(edits, None, cx);
8861 });
8862
8863 // Adjust selections so that they end before any comment suffixes that
8864 // were inserted.
8865 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8866 let mut selections = this.selections.all::<Point>(cx);
8867 let snapshot = this.buffer.read(cx).read(cx);
8868 for selection in &mut selections {
8869 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8870 match row.cmp(&MultiBufferRow(selection.end.row)) {
8871 Ordering::Less => {
8872 suffixes_inserted.next();
8873 continue;
8874 }
8875 Ordering::Greater => break,
8876 Ordering::Equal => {
8877 if selection.end.column == snapshot.line_len(row) {
8878 if selection.is_empty() {
8879 selection.start.column -= suffix_len as u32;
8880 }
8881 selection.end.column -= suffix_len as u32;
8882 }
8883 break;
8884 }
8885 }
8886 }
8887 }
8888
8889 drop(snapshot);
8890 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8891
8892 let selections = this.selections.all::<Point>(cx);
8893 let selections_on_single_row = selections.windows(2).all(|selections| {
8894 selections[0].start.row == selections[1].start.row
8895 && selections[0].end.row == selections[1].end.row
8896 && selections[0].start.row == selections[0].end.row
8897 });
8898 let selections_selecting = selections
8899 .iter()
8900 .any(|selection| selection.start != selection.end);
8901 let advance_downwards = action.advance_downwards
8902 && selections_on_single_row
8903 && !selections_selecting
8904 && !matches!(this.mode, EditorMode::SingleLine { .. });
8905
8906 if advance_downwards {
8907 let snapshot = this.buffer.read(cx).snapshot(cx);
8908
8909 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8910 s.move_cursors_with(|display_snapshot, display_point, _| {
8911 let mut point = display_point.to_point(display_snapshot);
8912 point.row += 1;
8913 point = snapshot.clip_point(point, Bias::Left);
8914 let display_point = point.to_display_point(display_snapshot);
8915 let goal = SelectionGoal::HorizontalPosition(
8916 display_snapshot
8917 .x_for_display_point(display_point, text_layout_details)
8918 .into(),
8919 );
8920 (display_point, goal)
8921 })
8922 });
8923 }
8924 });
8925 }
8926
8927 pub fn select_enclosing_symbol(
8928 &mut self,
8929 _: &SelectEnclosingSymbol,
8930 cx: &mut ViewContext<Self>,
8931 ) {
8932 let buffer = self.buffer.read(cx).snapshot(cx);
8933 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8934
8935 fn update_selection(
8936 selection: &Selection<usize>,
8937 buffer_snap: &MultiBufferSnapshot,
8938 ) -> Option<Selection<usize>> {
8939 let cursor = selection.head();
8940 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8941 for symbol in symbols.iter().rev() {
8942 let start = symbol.range.start.to_offset(buffer_snap);
8943 let end = symbol.range.end.to_offset(buffer_snap);
8944 let new_range = start..end;
8945 if start < selection.start || end > selection.end {
8946 return Some(Selection {
8947 id: selection.id,
8948 start: new_range.start,
8949 end: new_range.end,
8950 goal: SelectionGoal::None,
8951 reversed: selection.reversed,
8952 });
8953 }
8954 }
8955 None
8956 }
8957
8958 let mut selected_larger_symbol = false;
8959 let new_selections = old_selections
8960 .iter()
8961 .map(|selection| match update_selection(selection, &buffer) {
8962 Some(new_selection) => {
8963 if new_selection.range() != selection.range() {
8964 selected_larger_symbol = true;
8965 }
8966 new_selection
8967 }
8968 None => selection.clone(),
8969 })
8970 .collect::<Vec<_>>();
8971
8972 if selected_larger_symbol {
8973 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8974 s.select(new_selections);
8975 });
8976 }
8977 }
8978
8979 pub fn select_larger_syntax_node(
8980 &mut self,
8981 _: &SelectLargerSyntaxNode,
8982 cx: &mut ViewContext<Self>,
8983 ) {
8984 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8985 let buffer = self.buffer.read(cx).snapshot(cx);
8986 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8987
8988 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8989 let mut selected_larger_node = false;
8990 let new_selections = old_selections
8991 .iter()
8992 .map(|selection| {
8993 let old_range = selection.start..selection.end;
8994 let mut new_range = old_range.clone();
8995 while let Some(containing_range) =
8996 buffer.range_for_syntax_ancestor(new_range.clone())
8997 {
8998 new_range = containing_range;
8999 if !display_map.intersects_fold(new_range.start)
9000 && !display_map.intersects_fold(new_range.end)
9001 {
9002 break;
9003 }
9004 }
9005
9006 selected_larger_node |= new_range != old_range;
9007 Selection {
9008 id: selection.id,
9009 start: new_range.start,
9010 end: new_range.end,
9011 goal: SelectionGoal::None,
9012 reversed: selection.reversed,
9013 }
9014 })
9015 .collect::<Vec<_>>();
9016
9017 if selected_larger_node {
9018 stack.push(old_selections);
9019 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9020 s.select(new_selections);
9021 });
9022 }
9023 self.select_larger_syntax_node_stack = stack;
9024 }
9025
9026 pub fn select_smaller_syntax_node(
9027 &mut self,
9028 _: &SelectSmallerSyntaxNode,
9029 cx: &mut ViewContext<Self>,
9030 ) {
9031 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9032 if let Some(selections) = stack.pop() {
9033 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9034 s.select(selections.to_vec());
9035 });
9036 }
9037 self.select_larger_syntax_node_stack = stack;
9038 }
9039
9040 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9041 if !EditorSettings::get_global(cx).gutter.runnables {
9042 self.clear_tasks();
9043 return Task::ready(());
9044 }
9045 let project = self.project.clone();
9046 cx.spawn(|this, mut cx| async move {
9047 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9048 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9049 }) else {
9050 return;
9051 };
9052
9053 let Some(project) = project else {
9054 return;
9055 };
9056
9057 let hide_runnables = project
9058 .update(&mut cx, |project, cx| {
9059 // Do not display any test indicators in non-dev server remote projects.
9060 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9061 })
9062 .unwrap_or(true);
9063 if hide_runnables {
9064 return;
9065 }
9066 let new_rows =
9067 cx.background_executor()
9068 .spawn({
9069 let snapshot = display_snapshot.clone();
9070 async move {
9071 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9072 }
9073 })
9074 .await;
9075 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9076
9077 this.update(&mut cx, |this, _| {
9078 this.clear_tasks();
9079 for (key, value) in rows {
9080 this.insert_tasks(key, value);
9081 }
9082 })
9083 .ok();
9084 })
9085 }
9086 fn fetch_runnable_ranges(
9087 snapshot: &DisplaySnapshot,
9088 range: Range<Anchor>,
9089 ) -> Vec<language::RunnableRange> {
9090 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9091 }
9092
9093 fn runnable_rows(
9094 project: Model<Project>,
9095 snapshot: DisplaySnapshot,
9096 runnable_ranges: Vec<RunnableRange>,
9097 mut cx: AsyncWindowContext,
9098 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9099 runnable_ranges
9100 .into_iter()
9101 .filter_map(|mut runnable| {
9102 let tasks = cx
9103 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9104 .ok()?;
9105 if tasks.is_empty() {
9106 return None;
9107 }
9108
9109 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9110
9111 let row = snapshot
9112 .buffer_snapshot
9113 .buffer_line_for_row(MultiBufferRow(point.row))?
9114 .1
9115 .start
9116 .row;
9117
9118 let context_range =
9119 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9120 Some((
9121 (runnable.buffer_id, row),
9122 RunnableTasks {
9123 templates: tasks,
9124 offset: MultiBufferOffset(runnable.run_range.start),
9125 context_range,
9126 column: point.column,
9127 extra_variables: runnable.extra_captures,
9128 },
9129 ))
9130 })
9131 .collect()
9132 }
9133
9134 fn templates_with_tags(
9135 project: &Model<Project>,
9136 runnable: &mut Runnable,
9137 cx: &WindowContext<'_>,
9138 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9139 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9140 let (worktree_id, file) = project
9141 .buffer_for_id(runnable.buffer, cx)
9142 .and_then(|buffer| buffer.read(cx).file())
9143 .map(|file| (file.worktree_id(cx), file.clone()))
9144 .unzip();
9145
9146 (
9147 project.task_store().read(cx).task_inventory().cloned(),
9148 worktree_id,
9149 file,
9150 )
9151 });
9152
9153 let tags = mem::take(&mut runnable.tags);
9154 let mut tags: Vec<_> = tags
9155 .into_iter()
9156 .flat_map(|tag| {
9157 let tag = tag.0.clone();
9158 inventory
9159 .as_ref()
9160 .into_iter()
9161 .flat_map(|inventory| {
9162 inventory.read(cx).list_tasks(
9163 file.clone(),
9164 Some(runnable.language.clone()),
9165 worktree_id,
9166 cx,
9167 )
9168 })
9169 .filter(move |(_, template)| {
9170 template.tags.iter().any(|source_tag| source_tag == &tag)
9171 })
9172 })
9173 .sorted_by_key(|(kind, _)| kind.to_owned())
9174 .collect();
9175 if let Some((leading_tag_source, _)) = tags.first() {
9176 // Strongest source wins; if we have worktree tag binding, prefer that to
9177 // global and language bindings;
9178 // if we have a global binding, prefer that to language binding.
9179 let first_mismatch = tags
9180 .iter()
9181 .position(|(tag_source, _)| tag_source != leading_tag_source);
9182 if let Some(index) = first_mismatch {
9183 tags.truncate(index);
9184 }
9185 }
9186
9187 tags
9188 }
9189
9190 pub fn move_to_enclosing_bracket(
9191 &mut self,
9192 _: &MoveToEnclosingBracket,
9193 cx: &mut ViewContext<Self>,
9194 ) {
9195 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9196 s.move_offsets_with(|snapshot, selection| {
9197 let Some(enclosing_bracket_ranges) =
9198 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9199 else {
9200 return;
9201 };
9202
9203 let mut best_length = usize::MAX;
9204 let mut best_inside = false;
9205 let mut best_in_bracket_range = false;
9206 let mut best_destination = None;
9207 for (open, close) in enclosing_bracket_ranges {
9208 let close = close.to_inclusive();
9209 let length = close.end() - open.start;
9210 let inside = selection.start >= open.end && selection.end <= *close.start();
9211 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9212 || close.contains(&selection.head());
9213
9214 // If best is next to a bracket and current isn't, skip
9215 if !in_bracket_range && best_in_bracket_range {
9216 continue;
9217 }
9218
9219 // Prefer smaller lengths unless best is inside and current isn't
9220 if length > best_length && (best_inside || !inside) {
9221 continue;
9222 }
9223
9224 best_length = length;
9225 best_inside = inside;
9226 best_in_bracket_range = in_bracket_range;
9227 best_destination = Some(
9228 if close.contains(&selection.start) && close.contains(&selection.end) {
9229 if inside {
9230 open.end
9231 } else {
9232 open.start
9233 }
9234 } else if inside {
9235 *close.start()
9236 } else {
9237 *close.end()
9238 },
9239 );
9240 }
9241
9242 if let Some(destination) = best_destination {
9243 selection.collapse_to(destination, SelectionGoal::None);
9244 }
9245 })
9246 });
9247 }
9248
9249 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9250 self.end_selection(cx);
9251 self.selection_history.mode = SelectionHistoryMode::Undoing;
9252 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9253 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9254 self.select_next_state = entry.select_next_state;
9255 self.select_prev_state = entry.select_prev_state;
9256 self.add_selections_state = entry.add_selections_state;
9257 self.request_autoscroll(Autoscroll::newest(), cx);
9258 }
9259 self.selection_history.mode = SelectionHistoryMode::Normal;
9260 }
9261
9262 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9263 self.end_selection(cx);
9264 self.selection_history.mode = SelectionHistoryMode::Redoing;
9265 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9266 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9267 self.select_next_state = entry.select_next_state;
9268 self.select_prev_state = entry.select_prev_state;
9269 self.add_selections_state = entry.add_selections_state;
9270 self.request_autoscroll(Autoscroll::newest(), cx);
9271 }
9272 self.selection_history.mode = SelectionHistoryMode::Normal;
9273 }
9274
9275 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9276 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9277 }
9278
9279 pub fn expand_excerpts_down(
9280 &mut self,
9281 action: &ExpandExcerptsDown,
9282 cx: &mut ViewContext<Self>,
9283 ) {
9284 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9285 }
9286
9287 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9288 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9289 }
9290
9291 pub fn expand_excerpts_for_direction(
9292 &mut self,
9293 lines: u32,
9294 direction: ExpandExcerptDirection,
9295 cx: &mut ViewContext<Self>,
9296 ) {
9297 let selections = self.selections.disjoint_anchors();
9298
9299 let lines = if lines == 0 {
9300 EditorSettings::get_global(cx).expand_excerpt_lines
9301 } else {
9302 lines
9303 };
9304
9305 self.buffer.update(cx, |buffer, cx| {
9306 buffer.expand_excerpts(
9307 selections
9308 .iter()
9309 .map(|selection| selection.head().excerpt_id)
9310 .dedup(),
9311 lines,
9312 direction,
9313 cx,
9314 )
9315 })
9316 }
9317
9318 pub fn expand_excerpt(
9319 &mut self,
9320 excerpt: ExcerptId,
9321 direction: ExpandExcerptDirection,
9322 cx: &mut ViewContext<Self>,
9323 ) {
9324 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9325 self.buffer.update(cx, |buffer, cx| {
9326 buffer.expand_excerpts([excerpt], lines, direction, cx)
9327 })
9328 }
9329
9330 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9331 self.go_to_diagnostic_impl(Direction::Next, cx)
9332 }
9333
9334 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9335 self.go_to_diagnostic_impl(Direction::Prev, cx)
9336 }
9337
9338 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9339 let buffer = self.buffer.read(cx).snapshot(cx);
9340 let selection = self.selections.newest::<usize>(cx);
9341
9342 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9343 if direction == Direction::Next {
9344 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9345 let (group_id, jump_to) = popover.activation_info();
9346 if self.activate_diagnostics(group_id, cx) {
9347 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9348 let mut new_selection = s.newest_anchor().clone();
9349 new_selection.collapse_to(jump_to, SelectionGoal::None);
9350 s.select_anchors(vec![new_selection.clone()]);
9351 });
9352 }
9353 return;
9354 }
9355 }
9356
9357 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9358 active_diagnostics
9359 .primary_range
9360 .to_offset(&buffer)
9361 .to_inclusive()
9362 });
9363 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9364 if active_primary_range.contains(&selection.head()) {
9365 *active_primary_range.start()
9366 } else {
9367 selection.head()
9368 }
9369 } else {
9370 selection.head()
9371 };
9372 let snapshot = self.snapshot(cx);
9373 loop {
9374 let diagnostics = if direction == Direction::Prev {
9375 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9376 } else {
9377 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9378 }
9379 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9380 let group = diagnostics
9381 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9382 // be sorted in a stable way
9383 // skip until we are at current active diagnostic, if it exists
9384 .skip_while(|entry| {
9385 (match direction {
9386 Direction::Prev => entry.range.start >= search_start,
9387 Direction::Next => entry.range.start <= search_start,
9388 }) && self
9389 .active_diagnostics
9390 .as_ref()
9391 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9392 })
9393 .find_map(|entry| {
9394 if entry.diagnostic.is_primary
9395 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9396 && !entry.range.is_empty()
9397 // if we match with the active diagnostic, skip it
9398 && Some(entry.diagnostic.group_id)
9399 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9400 {
9401 Some((entry.range, entry.diagnostic.group_id))
9402 } else {
9403 None
9404 }
9405 });
9406
9407 if let Some((primary_range, group_id)) = group {
9408 if self.activate_diagnostics(group_id, cx) {
9409 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9410 s.select(vec![Selection {
9411 id: selection.id,
9412 start: primary_range.start,
9413 end: primary_range.start,
9414 reversed: false,
9415 goal: SelectionGoal::None,
9416 }]);
9417 });
9418 }
9419 break;
9420 } else {
9421 // Cycle around to the start of the buffer, potentially moving back to the start of
9422 // the currently active diagnostic.
9423 active_primary_range.take();
9424 if direction == Direction::Prev {
9425 if search_start == buffer.len() {
9426 break;
9427 } else {
9428 search_start = buffer.len();
9429 }
9430 } else if search_start == 0 {
9431 break;
9432 } else {
9433 search_start = 0;
9434 }
9435 }
9436 }
9437 }
9438
9439 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9440 let snapshot = self
9441 .display_map
9442 .update(cx, |display_map, cx| display_map.snapshot(cx));
9443 let selection = self.selections.newest::<Point>(cx);
9444 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9445 }
9446
9447 fn go_to_hunk_after_position(
9448 &mut self,
9449 snapshot: &DisplaySnapshot,
9450 position: Point,
9451 cx: &mut ViewContext<'_, Editor>,
9452 ) -> Option<MultiBufferDiffHunk> {
9453 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9454 snapshot,
9455 position,
9456 false,
9457 snapshot
9458 .buffer_snapshot
9459 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9460 cx,
9461 ) {
9462 return Some(hunk);
9463 }
9464
9465 let wrapped_point = Point::zero();
9466 self.go_to_next_hunk_in_direction(
9467 snapshot,
9468 wrapped_point,
9469 true,
9470 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9471 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9472 ),
9473 cx,
9474 )
9475 }
9476
9477 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9478 let snapshot = self
9479 .display_map
9480 .update(cx, |display_map, cx| display_map.snapshot(cx));
9481 let selection = self.selections.newest::<Point>(cx);
9482
9483 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9484 }
9485
9486 fn go_to_hunk_before_position(
9487 &mut self,
9488 snapshot: &DisplaySnapshot,
9489 position: Point,
9490 cx: &mut ViewContext<'_, Editor>,
9491 ) -> Option<MultiBufferDiffHunk> {
9492 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9493 snapshot,
9494 position,
9495 false,
9496 snapshot
9497 .buffer_snapshot
9498 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9499 cx,
9500 ) {
9501 return Some(hunk);
9502 }
9503
9504 let wrapped_point = snapshot.buffer_snapshot.max_point();
9505 self.go_to_next_hunk_in_direction(
9506 snapshot,
9507 wrapped_point,
9508 true,
9509 snapshot
9510 .buffer_snapshot
9511 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9512 cx,
9513 )
9514 }
9515
9516 fn go_to_next_hunk_in_direction(
9517 &mut self,
9518 snapshot: &DisplaySnapshot,
9519 initial_point: Point,
9520 is_wrapped: bool,
9521 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9522 cx: &mut ViewContext<Editor>,
9523 ) -> Option<MultiBufferDiffHunk> {
9524 let display_point = initial_point.to_display_point(snapshot);
9525 let mut hunks = hunks
9526 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9527 .filter(|(display_hunk, _)| {
9528 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9529 })
9530 .dedup();
9531
9532 if let Some((display_hunk, hunk)) = hunks.next() {
9533 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9534 let row = display_hunk.start_display_row();
9535 let point = DisplayPoint::new(row, 0);
9536 s.select_display_ranges([point..point]);
9537 });
9538
9539 Some(hunk)
9540 } else {
9541 None
9542 }
9543 }
9544
9545 pub fn go_to_definition(
9546 &mut self,
9547 _: &GoToDefinition,
9548 cx: &mut ViewContext<Self>,
9549 ) -> Task<Result<Navigated>> {
9550 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9551 cx.spawn(|editor, mut cx| async move {
9552 if definition.await? == Navigated::Yes {
9553 return Ok(Navigated::Yes);
9554 }
9555 match editor.update(&mut cx, |editor, cx| {
9556 editor.find_all_references(&FindAllReferences, cx)
9557 })? {
9558 Some(references) => references.await,
9559 None => Ok(Navigated::No),
9560 }
9561 })
9562 }
9563
9564 pub fn go_to_declaration(
9565 &mut self,
9566 _: &GoToDeclaration,
9567 cx: &mut ViewContext<Self>,
9568 ) -> Task<Result<Navigated>> {
9569 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9570 }
9571
9572 pub fn go_to_declaration_split(
9573 &mut self,
9574 _: &GoToDeclaration,
9575 cx: &mut ViewContext<Self>,
9576 ) -> Task<Result<Navigated>> {
9577 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9578 }
9579
9580 pub fn go_to_implementation(
9581 &mut self,
9582 _: &GoToImplementation,
9583 cx: &mut ViewContext<Self>,
9584 ) -> Task<Result<Navigated>> {
9585 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9586 }
9587
9588 pub fn go_to_implementation_split(
9589 &mut self,
9590 _: &GoToImplementationSplit,
9591 cx: &mut ViewContext<Self>,
9592 ) -> Task<Result<Navigated>> {
9593 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9594 }
9595
9596 pub fn go_to_type_definition(
9597 &mut self,
9598 _: &GoToTypeDefinition,
9599 cx: &mut ViewContext<Self>,
9600 ) -> Task<Result<Navigated>> {
9601 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9602 }
9603
9604 pub fn go_to_definition_split(
9605 &mut self,
9606 _: &GoToDefinitionSplit,
9607 cx: &mut ViewContext<Self>,
9608 ) -> Task<Result<Navigated>> {
9609 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9610 }
9611
9612 pub fn go_to_type_definition_split(
9613 &mut self,
9614 _: &GoToTypeDefinitionSplit,
9615 cx: &mut ViewContext<Self>,
9616 ) -> Task<Result<Navigated>> {
9617 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9618 }
9619
9620 fn go_to_definition_of_kind(
9621 &mut self,
9622 kind: GotoDefinitionKind,
9623 split: bool,
9624 cx: &mut ViewContext<Self>,
9625 ) -> Task<Result<Navigated>> {
9626 let Some(workspace) = self.workspace() else {
9627 return Task::ready(Ok(Navigated::No));
9628 };
9629 let buffer = self.buffer.read(cx);
9630 let head = self.selections.newest::<usize>(cx).head();
9631 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9632 text_anchor
9633 } else {
9634 return Task::ready(Ok(Navigated::No));
9635 };
9636
9637 let project = workspace.read(cx).project().clone();
9638 let definitions = project.update(cx, |project, cx| match kind {
9639 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9640 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9641 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9642 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9643 });
9644
9645 cx.spawn(|editor, mut cx| async move {
9646 let definitions = definitions.await?;
9647 let navigated = editor
9648 .update(&mut cx, |editor, cx| {
9649 editor.navigate_to_hover_links(
9650 Some(kind),
9651 definitions
9652 .into_iter()
9653 .filter(|location| {
9654 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9655 })
9656 .map(HoverLink::Text)
9657 .collect::<Vec<_>>(),
9658 split,
9659 cx,
9660 )
9661 })?
9662 .await?;
9663 anyhow::Ok(navigated)
9664 })
9665 }
9666
9667 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9668 let position = self.selections.newest_anchor().head();
9669 let Some((buffer, buffer_position)) =
9670 self.buffer.read(cx).text_anchor_for_position(position, cx)
9671 else {
9672 return;
9673 };
9674
9675 cx.spawn(|editor, mut cx| async move {
9676 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9677 editor.update(&mut cx, |_, cx| {
9678 cx.open_url(&url);
9679 })
9680 } else {
9681 Ok(())
9682 }
9683 })
9684 .detach();
9685 }
9686
9687 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9688 let Some(workspace) = self.workspace() else {
9689 return;
9690 };
9691
9692 let position = self.selections.newest_anchor().head();
9693
9694 let Some((buffer, buffer_position)) =
9695 self.buffer.read(cx).text_anchor_for_position(position, cx)
9696 else {
9697 return;
9698 };
9699
9700 let Some(project) = self.project.clone() else {
9701 return;
9702 };
9703
9704 cx.spawn(|_, mut cx| async move {
9705 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9706
9707 if let Some((_, path)) = result {
9708 workspace
9709 .update(&mut cx, |workspace, cx| {
9710 workspace.open_resolved_path(path, cx)
9711 })?
9712 .await?;
9713 }
9714 anyhow::Ok(())
9715 })
9716 .detach();
9717 }
9718
9719 pub(crate) fn navigate_to_hover_links(
9720 &mut self,
9721 kind: Option<GotoDefinitionKind>,
9722 mut definitions: Vec<HoverLink>,
9723 split: bool,
9724 cx: &mut ViewContext<Editor>,
9725 ) -> Task<Result<Navigated>> {
9726 // If there is one definition, just open it directly
9727 if definitions.len() == 1 {
9728 let definition = definitions.pop().unwrap();
9729
9730 enum TargetTaskResult {
9731 Location(Option<Location>),
9732 AlreadyNavigated,
9733 }
9734
9735 let target_task = match definition {
9736 HoverLink::Text(link) => {
9737 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9738 }
9739 HoverLink::InlayHint(lsp_location, server_id) => {
9740 let computation = self.compute_target_location(lsp_location, server_id, cx);
9741 cx.background_executor().spawn(async move {
9742 let location = computation.await?;
9743 Ok(TargetTaskResult::Location(location))
9744 })
9745 }
9746 HoverLink::Url(url) => {
9747 cx.open_url(&url);
9748 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9749 }
9750 HoverLink::File(path) => {
9751 if let Some(workspace) = self.workspace() {
9752 cx.spawn(|_, mut cx| async move {
9753 workspace
9754 .update(&mut cx, |workspace, cx| {
9755 workspace.open_resolved_path(path, cx)
9756 })?
9757 .await
9758 .map(|_| TargetTaskResult::AlreadyNavigated)
9759 })
9760 } else {
9761 Task::ready(Ok(TargetTaskResult::Location(None)))
9762 }
9763 }
9764 };
9765 cx.spawn(|editor, mut cx| async move {
9766 let target = match target_task.await.context("target resolution task")? {
9767 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9768 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9769 TargetTaskResult::Location(Some(target)) => target,
9770 };
9771
9772 editor.update(&mut cx, |editor, cx| {
9773 let Some(workspace) = editor.workspace() else {
9774 return Navigated::No;
9775 };
9776 let pane = workspace.read(cx).active_pane().clone();
9777
9778 let range = target.range.to_offset(target.buffer.read(cx));
9779 let range = editor.range_for_match(&range);
9780
9781 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9782 let buffer = target.buffer.read(cx);
9783 let range = check_multiline_range(buffer, range);
9784 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9785 s.select_ranges([range]);
9786 });
9787 } else {
9788 cx.window_context().defer(move |cx| {
9789 let target_editor: View<Self> =
9790 workspace.update(cx, |workspace, cx| {
9791 let pane = if split {
9792 workspace.adjacent_pane(cx)
9793 } else {
9794 workspace.active_pane().clone()
9795 };
9796
9797 workspace.open_project_item(
9798 pane,
9799 target.buffer.clone(),
9800 true,
9801 true,
9802 cx,
9803 )
9804 });
9805 target_editor.update(cx, |target_editor, cx| {
9806 // When selecting a definition in a different buffer, disable the nav history
9807 // to avoid creating a history entry at the previous cursor location.
9808 pane.update(cx, |pane, _| pane.disable_history());
9809 let buffer = target.buffer.read(cx);
9810 let range = check_multiline_range(buffer, range);
9811 target_editor.change_selections(
9812 Some(Autoscroll::focused()),
9813 cx,
9814 |s| {
9815 s.select_ranges([range]);
9816 },
9817 );
9818 pane.update(cx, |pane, _| pane.enable_history());
9819 });
9820 });
9821 }
9822 Navigated::Yes
9823 })
9824 })
9825 } else if !definitions.is_empty() {
9826 cx.spawn(|editor, mut cx| async move {
9827 let (title, location_tasks, workspace) = editor
9828 .update(&mut cx, |editor, cx| {
9829 let tab_kind = match kind {
9830 Some(GotoDefinitionKind::Implementation) => "Implementations",
9831 _ => "Definitions",
9832 };
9833 let title = definitions
9834 .iter()
9835 .find_map(|definition| match definition {
9836 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9837 let buffer = origin.buffer.read(cx);
9838 format!(
9839 "{} for {}",
9840 tab_kind,
9841 buffer
9842 .text_for_range(origin.range.clone())
9843 .collect::<String>()
9844 )
9845 }),
9846 HoverLink::InlayHint(_, _) => None,
9847 HoverLink::Url(_) => None,
9848 HoverLink::File(_) => None,
9849 })
9850 .unwrap_or(tab_kind.to_string());
9851 let location_tasks = definitions
9852 .into_iter()
9853 .map(|definition| match definition {
9854 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9855 HoverLink::InlayHint(lsp_location, server_id) => {
9856 editor.compute_target_location(lsp_location, server_id, cx)
9857 }
9858 HoverLink::Url(_) => Task::ready(Ok(None)),
9859 HoverLink::File(_) => Task::ready(Ok(None)),
9860 })
9861 .collect::<Vec<_>>();
9862 (title, location_tasks, editor.workspace().clone())
9863 })
9864 .context("location tasks preparation")?;
9865
9866 let locations = future::join_all(location_tasks)
9867 .await
9868 .into_iter()
9869 .filter_map(|location| location.transpose())
9870 .collect::<Result<_>>()
9871 .context("location tasks")?;
9872
9873 let Some(workspace) = workspace else {
9874 return Ok(Navigated::No);
9875 };
9876 let opened = workspace
9877 .update(&mut cx, |workspace, cx| {
9878 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9879 })
9880 .ok();
9881
9882 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9883 })
9884 } else {
9885 Task::ready(Ok(Navigated::No))
9886 }
9887 }
9888
9889 fn compute_target_location(
9890 &self,
9891 lsp_location: lsp::Location,
9892 server_id: LanguageServerId,
9893 cx: &mut ViewContext<Editor>,
9894 ) -> Task<anyhow::Result<Option<Location>>> {
9895 let Some(project) = self.project.clone() else {
9896 return Task::Ready(Some(Ok(None)));
9897 };
9898
9899 cx.spawn(move |editor, mut cx| async move {
9900 let location_task = editor.update(&mut cx, |editor, cx| {
9901 project.update(cx, |project, cx| {
9902 let language_server_name =
9903 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9904 project
9905 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9906 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9907 });
9908 language_server_name.map(|language_server_name| {
9909 project.open_local_buffer_via_lsp(
9910 lsp_location.uri.clone(),
9911 server_id,
9912 language_server_name,
9913 cx,
9914 )
9915 })
9916 })
9917 })?;
9918 let location = match location_task {
9919 Some(task) => Some({
9920 let target_buffer_handle = task.await.context("open local buffer")?;
9921 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9922 let target_start = target_buffer
9923 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9924 let target_end = target_buffer
9925 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9926 target_buffer.anchor_after(target_start)
9927 ..target_buffer.anchor_before(target_end)
9928 })?;
9929 Location {
9930 buffer: target_buffer_handle,
9931 range,
9932 }
9933 }),
9934 None => None,
9935 };
9936 Ok(location)
9937 })
9938 }
9939
9940 pub fn find_all_references(
9941 &mut self,
9942 _: &FindAllReferences,
9943 cx: &mut ViewContext<Self>,
9944 ) -> Option<Task<Result<Navigated>>> {
9945 let multi_buffer = self.buffer.read(cx);
9946 let selection = self.selections.newest::<usize>(cx);
9947 let head = selection.head();
9948
9949 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9950 let head_anchor = multi_buffer_snapshot.anchor_at(
9951 head,
9952 if head < selection.tail() {
9953 Bias::Right
9954 } else {
9955 Bias::Left
9956 },
9957 );
9958
9959 match self
9960 .find_all_references_task_sources
9961 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9962 {
9963 Ok(_) => {
9964 log::info!(
9965 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9966 );
9967 return None;
9968 }
9969 Err(i) => {
9970 self.find_all_references_task_sources.insert(i, head_anchor);
9971 }
9972 }
9973
9974 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9975 let workspace = self.workspace()?;
9976 let project = workspace.read(cx).project().clone();
9977 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9978 Some(cx.spawn(|editor, mut cx| async move {
9979 let _cleanup = defer({
9980 let mut cx = cx.clone();
9981 move || {
9982 let _ = editor.update(&mut cx, |editor, _| {
9983 if let Ok(i) =
9984 editor
9985 .find_all_references_task_sources
9986 .binary_search_by(|anchor| {
9987 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9988 })
9989 {
9990 editor.find_all_references_task_sources.remove(i);
9991 }
9992 });
9993 }
9994 });
9995
9996 let locations = references.await?;
9997 if locations.is_empty() {
9998 return anyhow::Ok(Navigated::No);
9999 }
10000
10001 workspace.update(&mut cx, |workspace, cx| {
10002 let title = locations
10003 .first()
10004 .as_ref()
10005 .map(|location| {
10006 let buffer = location.buffer.read(cx);
10007 format!(
10008 "References to `{}`",
10009 buffer
10010 .text_for_range(location.range.clone())
10011 .collect::<String>()
10012 )
10013 })
10014 .unwrap();
10015 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10016 Navigated::Yes
10017 })
10018 }))
10019 }
10020
10021 /// Opens a multibuffer with the given project locations in it
10022 pub fn open_locations_in_multibuffer(
10023 workspace: &mut Workspace,
10024 mut locations: Vec<Location>,
10025 title: String,
10026 split: bool,
10027 cx: &mut ViewContext<Workspace>,
10028 ) {
10029 // If there are multiple definitions, open them in a multibuffer
10030 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10031 let mut locations = locations.into_iter().peekable();
10032 let mut ranges_to_highlight = Vec::new();
10033 let capability = workspace.project().read(cx).capability();
10034
10035 let excerpt_buffer = cx.new_model(|cx| {
10036 let mut multibuffer = MultiBuffer::new(capability);
10037 while let Some(location) = locations.next() {
10038 let buffer = location.buffer.read(cx);
10039 let mut ranges_for_buffer = Vec::new();
10040 let range = location.range.to_offset(buffer);
10041 ranges_for_buffer.push(range.clone());
10042
10043 while let Some(next_location) = locations.peek() {
10044 if next_location.buffer == location.buffer {
10045 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10046 locations.next();
10047 } else {
10048 break;
10049 }
10050 }
10051
10052 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10053 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10054 location.buffer.clone(),
10055 ranges_for_buffer,
10056 DEFAULT_MULTIBUFFER_CONTEXT,
10057 cx,
10058 ))
10059 }
10060
10061 multibuffer.with_title(title)
10062 });
10063
10064 let editor = cx.new_view(|cx| {
10065 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10066 });
10067 editor.update(cx, |editor, cx| {
10068 if let Some(first_range) = ranges_to_highlight.first() {
10069 editor.change_selections(None, cx, |selections| {
10070 selections.clear_disjoint();
10071 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10072 });
10073 }
10074 editor.highlight_background::<Self>(
10075 &ranges_to_highlight,
10076 |theme| theme.editor_highlighted_line_background,
10077 cx,
10078 );
10079 });
10080
10081 let item = Box::new(editor);
10082 let item_id = item.item_id();
10083
10084 if split {
10085 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10086 } else {
10087 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10088 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10089 pane.close_current_preview_item(cx)
10090 } else {
10091 None
10092 }
10093 });
10094 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10095 }
10096 workspace.active_pane().update(cx, |pane, cx| {
10097 pane.set_preview_item_id(Some(item_id), cx);
10098 });
10099 }
10100
10101 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10102 use language::ToOffset as _;
10103
10104 let project = self.project.clone()?;
10105 let selection = self.selections.newest_anchor().clone();
10106 let (cursor_buffer, cursor_buffer_position) = self
10107 .buffer
10108 .read(cx)
10109 .text_anchor_for_position(selection.head(), cx)?;
10110 let (tail_buffer, cursor_buffer_position_end) = self
10111 .buffer
10112 .read(cx)
10113 .text_anchor_for_position(selection.tail(), cx)?;
10114 if tail_buffer != cursor_buffer {
10115 return None;
10116 }
10117
10118 let snapshot = cursor_buffer.read(cx).snapshot();
10119 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10120 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10121 let prepare_rename = project.update(cx, |project, cx| {
10122 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
10123 });
10124 drop(snapshot);
10125
10126 Some(cx.spawn(|this, mut cx| async move {
10127 let rename_range = if let Some(range) = prepare_rename.await? {
10128 Some(range)
10129 } else {
10130 this.update(&mut cx, |this, cx| {
10131 let buffer = this.buffer.read(cx).snapshot(cx);
10132 let mut buffer_highlights = this
10133 .document_highlights_for_position(selection.head(), &buffer)
10134 .filter(|highlight| {
10135 highlight.start.excerpt_id == selection.head().excerpt_id
10136 && highlight.end.excerpt_id == selection.head().excerpt_id
10137 });
10138 buffer_highlights
10139 .next()
10140 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10141 })?
10142 };
10143 if let Some(rename_range) = rename_range {
10144 this.update(&mut cx, |this, cx| {
10145 let snapshot = cursor_buffer.read(cx).snapshot();
10146 let rename_buffer_range = rename_range.to_offset(&snapshot);
10147 let cursor_offset_in_rename_range =
10148 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10149 let cursor_offset_in_rename_range_end =
10150 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10151
10152 this.take_rename(false, cx);
10153 let buffer = this.buffer.read(cx).read(cx);
10154 let cursor_offset = selection.head().to_offset(&buffer);
10155 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10156 let rename_end = rename_start + rename_buffer_range.len();
10157 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10158 let mut old_highlight_id = None;
10159 let old_name: Arc<str> = buffer
10160 .chunks(rename_start..rename_end, true)
10161 .map(|chunk| {
10162 if old_highlight_id.is_none() {
10163 old_highlight_id = chunk.syntax_highlight_id;
10164 }
10165 chunk.text
10166 })
10167 .collect::<String>()
10168 .into();
10169
10170 drop(buffer);
10171
10172 // Position the selection in the rename editor so that it matches the current selection.
10173 this.show_local_selections = false;
10174 let rename_editor = cx.new_view(|cx| {
10175 let mut editor = Editor::single_line(cx);
10176 editor.buffer.update(cx, |buffer, cx| {
10177 buffer.edit([(0..0, old_name.clone())], None, cx)
10178 });
10179 let rename_selection_range = match cursor_offset_in_rename_range
10180 .cmp(&cursor_offset_in_rename_range_end)
10181 {
10182 Ordering::Equal => {
10183 editor.select_all(&SelectAll, cx);
10184 return editor;
10185 }
10186 Ordering::Less => {
10187 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10188 }
10189 Ordering::Greater => {
10190 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10191 }
10192 };
10193 if rename_selection_range.end > old_name.len() {
10194 editor.select_all(&SelectAll, cx);
10195 } else {
10196 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10197 s.select_ranges([rename_selection_range]);
10198 });
10199 }
10200 editor
10201 });
10202 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10203 if e == &EditorEvent::Focused {
10204 cx.emit(EditorEvent::FocusedIn)
10205 }
10206 })
10207 .detach();
10208
10209 let write_highlights =
10210 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10211 let read_highlights =
10212 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10213 let ranges = write_highlights
10214 .iter()
10215 .flat_map(|(_, ranges)| ranges.iter())
10216 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10217 .cloned()
10218 .collect();
10219
10220 this.highlight_text::<Rename>(
10221 ranges,
10222 HighlightStyle {
10223 fade_out: Some(0.6),
10224 ..Default::default()
10225 },
10226 cx,
10227 );
10228 let rename_focus_handle = rename_editor.focus_handle(cx);
10229 cx.focus(&rename_focus_handle);
10230 let block_id = this.insert_blocks(
10231 [BlockProperties {
10232 style: BlockStyle::Flex,
10233 position: range.start,
10234 height: 1,
10235 render: Box::new({
10236 let rename_editor = rename_editor.clone();
10237 move |cx: &mut BlockContext| {
10238 let mut text_style = cx.editor_style.text.clone();
10239 if let Some(highlight_style) = old_highlight_id
10240 .and_then(|h| h.style(&cx.editor_style.syntax))
10241 {
10242 text_style = text_style.highlight(highlight_style);
10243 }
10244 div()
10245 .pl(cx.anchor_x)
10246 .child(EditorElement::new(
10247 &rename_editor,
10248 EditorStyle {
10249 background: cx.theme().system().transparent,
10250 local_player: cx.editor_style.local_player,
10251 text: text_style,
10252 scrollbar_width: cx.editor_style.scrollbar_width,
10253 syntax: cx.editor_style.syntax.clone(),
10254 status: cx.editor_style.status.clone(),
10255 inlay_hints_style: HighlightStyle {
10256 font_weight: Some(FontWeight::BOLD),
10257 ..make_inlay_hints_style(cx)
10258 },
10259 suggestions_style: HighlightStyle {
10260 color: Some(cx.theme().status().predictive),
10261 ..HighlightStyle::default()
10262 },
10263 ..EditorStyle::default()
10264 },
10265 ))
10266 .into_any_element()
10267 }
10268 }),
10269 disposition: BlockDisposition::Below,
10270 priority: 0,
10271 }],
10272 Some(Autoscroll::fit()),
10273 cx,
10274 )[0];
10275 this.pending_rename = Some(RenameState {
10276 range,
10277 old_name,
10278 editor: rename_editor,
10279 block_id,
10280 });
10281 })?;
10282 }
10283
10284 Ok(())
10285 }))
10286 }
10287
10288 pub fn confirm_rename(
10289 &mut self,
10290 _: &ConfirmRename,
10291 cx: &mut ViewContext<Self>,
10292 ) -> Option<Task<Result<()>>> {
10293 let rename = self.take_rename(false, cx)?;
10294 let workspace = self.workspace()?;
10295 let (start_buffer, start) = self
10296 .buffer
10297 .read(cx)
10298 .text_anchor_for_position(rename.range.start, cx)?;
10299 let (end_buffer, end) = self
10300 .buffer
10301 .read(cx)
10302 .text_anchor_for_position(rename.range.end, cx)?;
10303 if start_buffer != end_buffer {
10304 return None;
10305 }
10306
10307 let buffer = start_buffer;
10308 let range = start..end;
10309 let old_name = rename.old_name;
10310 let new_name = rename.editor.read(cx).text(cx);
10311
10312 let rename = workspace
10313 .read(cx)
10314 .project()
10315 .clone()
10316 .update(cx, |project, cx| {
10317 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10318 });
10319 let workspace = workspace.downgrade();
10320
10321 Some(cx.spawn(|editor, mut cx| async move {
10322 let project_transaction = rename.await?;
10323 Self::open_project_transaction(
10324 &editor,
10325 workspace,
10326 project_transaction,
10327 format!("Rename: {} → {}", old_name, new_name),
10328 cx.clone(),
10329 )
10330 .await?;
10331
10332 editor.update(&mut cx, |editor, cx| {
10333 editor.refresh_document_highlights(cx);
10334 })?;
10335 Ok(())
10336 }))
10337 }
10338
10339 fn take_rename(
10340 &mut self,
10341 moving_cursor: bool,
10342 cx: &mut ViewContext<Self>,
10343 ) -> Option<RenameState> {
10344 let rename = self.pending_rename.take()?;
10345 if rename.editor.focus_handle(cx).is_focused(cx) {
10346 cx.focus(&self.focus_handle);
10347 }
10348
10349 self.remove_blocks(
10350 [rename.block_id].into_iter().collect(),
10351 Some(Autoscroll::fit()),
10352 cx,
10353 );
10354 self.clear_highlights::<Rename>(cx);
10355 self.show_local_selections = true;
10356
10357 if moving_cursor {
10358 let rename_editor = rename.editor.read(cx);
10359 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10360
10361 // Update the selection to match the position of the selection inside
10362 // the rename editor.
10363 let snapshot = self.buffer.read(cx).read(cx);
10364 let rename_range = rename.range.to_offset(&snapshot);
10365 let cursor_in_editor = snapshot
10366 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10367 .min(rename_range.end);
10368 drop(snapshot);
10369
10370 self.change_selections(None, cx, |s| {
10371 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10372 });
10373 } else {
10374 self.refresh_document_highlights(cx);
10375 }
10376
10377 Some(rename)
10378 }
10379
10380 pub fn pending_rename(&self) -> Option<&RenameState> {
10381 self.pending_rename.as_ref()
10382 }
10383
10384 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10385 let project = match &self.project {
10386 Some(project) => project.clone(),
10387 None => return None,
10388 };
10389
10390 Some(self.perform_format(project, FormatTrigger::Manual, cx))
10391 }
10392
10393 fn perform_format(
10394 &mut self,
10395 project: Model<Project>,
10396 trigger: FormatTrigger,
10397 cx: &mut ViewContext<Self>,
10398 ) -> Task<Result<()>> {
10399 let buffer = self.buffer().clone();
10400 let mut buffers = buffer.read(cx).all_buffers();
10401 if trigger == FormatTrigger::Save {
10402 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10403 }
10404
10405 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10406 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10407
10408 cx.spawn(|_, mut cx| async move {
10409 let transaction = futures::select_biased! {
10410 () = timeout => {
10411 log::warn!("timed out waiting for formatting");
10412 None
10413 }
10414 transaction = format.log_err().fuse() => transaction,
10415 };
10416
10417 buffer
10418 .update(&mut cx, |buffer, cx| {
10419 if let Some(transaction) = transaction {
10420 if !buffer.is_singleton() {
10421 buffer.push_transaction(&transaction.0, cx);
10422 }
10423 }
10424
10425 cx.notify();
10426 })
10427 .ok();
10428
10429 Ok(())
10430 })
10431 }
10432
10433 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10434 if let Some(project) = self.project.clone() {
10435 self.buffer.update(cx, |multi_buffer, cx| {
10436 project.update(cx, |project, cx| {
10437 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10438 });
10439 })
10440 }
10441 }
10442
10443 fn cancel_language_server_work(
10444 &mut self,
10445 _: &CancelLanguageServerWork,
10446 cx: &mut ViewContext<Self>,
10447 ) {
10448 if let Some(project) = self.project.clone() {
10449 self.buffer.update(cx, |multi_buffer, cx| {
10450 project.update(cx, |project, cx| {
10451 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10452 });
10453 })
10454 }
10455 }
10456
10457 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10458 cx.show_character_palette();
10459 }
10460
10461 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10462 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10463 let buffer = self.buffer.read(cx).snapshot(cx);
10464 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10465 let is_valid = buffer
10466 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10467 .any(|entry| {
10468 entry.diagnostic.is_primary
10469 && !entry.range.is_empty()
10470 && entry.range.start == primary_range_start
10471 && entry.diagnostic.message == active_diagnostics.primary_message
10472 });
10473
10474 if is_valid != active_diagnostics.is_valid {
10475 active_diagnostics.is_valid = is_valid;
10476 let mut new_styles = HashMap::default();
10477 for (block_id, diagnostic) in &active_diagnostics.blocks {
10478 new_styles.insert(
10479 *block_id,
10480 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10481 );
10482 }
10483 self.display_map.update(cx, |display_map, _cx| {
10484 display_map.replace_blocks(new_styles)
10485 });
10486 }
10487 }
10488 }
10489
10490 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10491 self.dismiss_diagnostics(cx);
10492 let snapshot = self.snapshot(cx);
10493 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10494 let buffer = self.buffer.read(cx).snapshot(cx);
10495
10496 let mut primary_range = None;
10497 let mut primary_message = None;
10498 let mut group_end = Point::zero();
10499 let diagnostic_group = buffer
10500 .diagnostic_group::<MultiBufferPoint>(group_id)
10501 .filter_map(|entry| {
10502 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10503 && (entry.range.start.row == entry.range.end.row
10504 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10505 {
10506 return None;
10507 }
10508 if entry.range.end > group_end {
10509 group_end = entry.range.end;
10510 }
10511 if entry.diagnostic.is_primary {
10512 primary_range = Some(entry.range.clone());
10513 primary_message = Some(entry.diagnostic.message.clone());
10514 }
10515 Some(entry)
10516 })
10517 .collect::<Vec<_>>();
10518 let primary_range = primary_range?;
10519 let primary_message = primary_message?;
10520 let primary_range =
10521 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10522
10523 let blocks = display_map
10524 .insert_blocks(
10525 diagnostic_group.iter().map(|entry| {
10526 let diagnostic = entry.diagnostic.clone();
10527 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10528 BlockProperties {
10529 style: BlockStyle::Fixed,
10530 position: buffer.anchor_after(entry.range.start),
10531 height: message_height,
10532 render: diagnostic_block_renderer(diagnostic, None, true, true),
10533 disposition: BlockDisposition::Below,
10534 priority: 0,
10535 }
10536 }),
10537 cx,
10538 )
10539 .into_iter()
10540 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10541 .collect();
10542
10543 Some(ActiveDiagnosticGroup {
10544 primary_range,
10545 primary_message,
10546 group_id,
10547 blocks,
10548 is_valid: true,
10549 })
10550 });
10551 self.active_diagnostics.is_some()
10552 }
10553
10554 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10555 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10556 self.display_map.update(cx, |display_map, cx| {
10557 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10558 });
10559 cx.notify();
10560 }
10561 }
10562
10563 pub fn set_selections_from_remote(
10564 &mut self,
10565 selections: Vec<Selection<Anchor>>,
10566 pending_selection: Option<Selection<Anchor>>,
10567 cx: &mut ViewContext<Self>,
10568 ) {
10569 let old_cursor_position = self.selections.newest_anchor().head();
10570 self.selections.change_with(cx, |s| {
10571 s.select_anchors(selections);
10572 if let Some(pending_selection) = pending_selection {
10573 s.set_pending(pending_selection, SelectMode::Character);
10574 } else {
10575 s.clear_pending();
10576 }
10577 });
10578 self.selections_did_change(false, &old_cursor_position, true, cx);
10579 }
10580
10581 fn push_to_selection_history(&mut self) {
10582 self.selection_history.push(SelectionHistoryEntry {
10583 selections: self.selections.disjoint_anchors(),
10584 select_next_state: self.select_next_state.clone(),
10585 select_prev_state: self.select_prev_state.clone(),
10586 add_selections_state: self.add_selections_state.clone(),
10587 });
10588 }
10589
10590 pub fn transact(
10591 &mut self,
10592 cx: &mut ViewContext<Self>,
10593 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10594 ) -> Option<TransactionId> {
10595 self.start_transaction_at(Instant::now(), cx);
10596 update(self, cx);
10597 self.end_transaction_at(Instant::now(), cx)
10598 }
10599
10600 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10601 self.end_selection(cx);
10602 if let Some(tx_id) = self
10603 .buffer
10604 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10605 {
10606 self.selection_history
10607 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10608 cx.emit(EditorEvent::TransactionBegun {
10609 transaction_id: tx_id,
10610 })
10611 }
10612 }
10613
10614 fn end_transaction_at(
10615 &mut self,
10616 now: Instant,
10617 cx: &mut ViewContext<Self>,
10618 ) -> Option<TransactionId> {
10619 if let Some(transaction_id) = self
10620 .buffer
10621 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10622 {
10623 if let Some((_, end_selections)) =
10624 self.selection_history.transaction_mut(transaction_id)
10625 {
10626 *end_selections = Some(self.selections.disjoint_anchors());
10627 } else {
10628 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10629 }
10630
10631 cx.emit(EditorEvent::Edited { transaction_id });
10632 Some(transaction_id)
10633 } else {
10634 None
10635 }
10636 }
10637
10638 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10639 let selection = self.selections.newest::<Point>(cx);
10640
10641 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10642 let range = if selection.is_empty() {
10643 let point = selection.head().to_display_point(&display_map);
10644 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10645 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10646 .to_point(&display_map);
10647 start..end
10648 } else {
10649 selection.range()
10650 };
10651 if display_map.folds_in_range(range).next().is_some() {
10652 self.unfold_lines(&Default::default(), cx)
10653 } else {
10654 self.fold(&Default::default(), cx)
10655 }
10656 }
10657
10658 pub fn toggle_fold_recursive(
10659 &mut self,
10660 _: &actions::ToggleFoldRecursive,
10661 cx: &mut ViewContext<Self>,
10662 ) {
10663 let selection = self.selections.newest::<Point>(cx);
10664
10665 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10666 let range = if selection.is_empty() {
10667 let point = selection.head().to_display_point(&display_map);
10668 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10669 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10670 .to_point(&display_map);
10671 start..end
10672 } else {
10673 selection.range()
10674 };
10675 if display_map.folds_in_range(range).next().is_some() {
10676 self.unfold_recursive(&Default::default(), cx)
10677 } else {
10678 self.fold_recursive(&Default::default(), cx)
10679 }
10680 }
10681
10682 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10683 let mut fold_ranges = Vec::new();
10684 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10685 let selections = self.selections.all_adjusted(cx);
10686
10687 for selection in selections {
10688 let range = selection.range().sorted();
10689 let buffer_start_row = range.start.row;
10690
10691 if range.start.row != range.end.row {
10692 let mut found = false;
10693 let mut row = range.start.row;
10694 while row <= range.end.row {
10695 if let Some((foldable_range, fold_text)) =
10696 { display_map.foldable_range(MultiBufferRow(row)) }
10697 {
10698 found = true;
10699 row = foldable_range.end.row + 1;
10700 fold_ranges.push((foldable_range, fold_text));
10701 } else {
10702 row += 1
10703 }
10704 }
10705 if found {
10706 continue;
10707 }
10708 }
10709
10710 for row in (0..=range.start.row).rev() {
10711 if let Some((foldable_range, fold_text)) =
10712 display_map.foldable_range(MultiBufferRow(row))
10713 {
10714 if foldable_range.end.row >= buffer_start_row {
10715 fold_ranges.push((foldable_range, fold_text));
10716 if row <= range.start.row {
10717 break;
10718 }
10719 }
10720 }
10721 }
10722 }
10723
10724 self.fold_ranges(fold_ranges, true, cx);
10725 }
10726
10727 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10728 let mut fold_ranges = Vec::new();
10729 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10730
10731 for row in 0..display_map.max_buffer_row().0 {
10732 if let Some((foldable_range, fold_text)) =
10733 display_map.foldable_range(MultiBufferRow(row))
10734 {
10735 fold_ranges.push((foldable_range, fold_text));
10736 }
10737 }
10738
10739 self.fold_ranges(fold_ranges, true, cx);
10740 }
10741
10742 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10743 let mut fold_ranges = Vec::new();
10744 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10745 let selections = self.selections.all_adjusted(cx);
10746
10747 for selection in selections {
10748 let range = selection.range().sorted();
10749 let buffer_start_row = range.start.row;
10750
10751 if range.start.row != range.end.row {
10752 let mut found = false;
10753 for row in range.start.row..=range.end.row {
10754 if let Some((foldable_range, fold_text)) =
10755 { display_map.foldable_range(MultiBufferRow(row)) }
10756 {
10757 found = true;
10758 fold_ranges.push((foldable_range, fold_text));
10759 }
10760 }
10761 if found {
10762 continue;
10763 }
10764 }
10765
10766 for row in (0..=range.start.row).rev() {
10767 if let Some((foldable_range, fold_text)) =
10768 display_map.foldable_range(MultiBufferRow(row))
10769 {
10770 if foldable_range.end.row >= buffer_start_row {
10771 fold_ranges.push((foldable_range, fold_text));
10772 } else {
10773 break;
10774 }
10775 }
10776 }
10777 }
10778
10779 self.fold_ranges(fold_ranges, true, cx);
10780 }
10781
10782 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10783 let buffer_row = fold_at.buffer_row;
10784 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10785
10786 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10787 let autoscroll = self
10788 .selections
10789 .all::<Point>(cx)
10790 .iter()
10791 .any(|selection| fold_range.overlaps(&selection.range()));
10792
10793 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10794 }
10795 }
10796
10797 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10798 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10799 let buffer = &display_map.buffer_snapshot;
10800 let selections = self.selections.all::<Point>(cx);
10801 let ranges = selections
10802 .iter()
10803 .map(|s| {
10804 let range = s.display_range(&display_map).sorted();
10805 let mut start = range.start.to_point(&display_map);
10806 let mut end = range.end.to_point(&display_map);
10807 start.column = 0;
10808 end.column = buffer.line_len(MultiBufferRow(end.row));
10809 start..end
10810 })
10811 .collect::<Vec<_>>();
10812
10813 self.unfold_ranges(ranges, true, true, cx);
10814 }
10815
10816 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10817 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10818 let selections = self.selections.all::<Point>(cx);
10819 let ranges = selections
10820 .iter()
10821 .map(|s| {
10822 let mut range = s.display_range(&display_map).sorted();
10823 *range.start.column_mut() = 0;
10824 *range.end.column_mut() = display_map.line_len(range.end.row());
10825 let start = range.start.to_point(&display_map);
10826 let end = range.end.to_point(&display_map);
10827 start..end
10828 })
10829 .collect::<Vec<_>>();
10830
10831 self.unfold_ranges(ranges, true, true, cx);
10832 }
10833
10834 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10835 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10836
10837 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10838 ..Point::new(
10839 unfold_at.buffer_row.0,
10840 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10841 );
10842
10843 let autoscroll = self
10844 .selections
10845 .all::<Point>(cx)
10846 .iter()
10847 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10848
10849 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10850 }
10851
10852 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10853 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10854 self.unfold_ranges(
10855 [Point::zero()..display_map.max_point().to_point(&display_map)],
10856 true,
10857 true,
10858 cx,
10859 );
10860 }
10861
10862 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10863 let selections = self.selections.all::<Point>(cx);
10864 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10865 let line_mode = self.selections.line_mode;
10866 let ranges = selections.into_iter().map(|s| {
10867 if line_mode {
10868 let start = Point::new(s.start.row, 0);
10869 let end = Point::new(
10870 s.end.row,
10871 display_map
10872 .buffer_snapshot
10873 .line_len(MultiBufferRow(s.end.row)),
10874 );
10875 (start..end, display_map.fold_placeholder.clone())
10876 } else {
10877 (s.start..s.end, display_map.fold_placeholder.clone())
10878 }
10879 });
10880 self.fold_ranges(ranges, true, cx);
10881 }
10882
10883 pub fn fold_ranges<T: ToOffset + Clone>(
10884 &mut self,
10885 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10886 auto_scroll: bool,
10887 cx: &mut ViewContext<Self>,
10888 ) {
10889 let mut fold_ranges = Vec::new();
10890 let mut buffers_affected = HashMap::default();
10891 let multi_buffer = self.buffer().read(cx);
10892 for (fold_range, fold_text) in ranges {
10893 if let Some((_, buffer, _)) =
10894 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10895 {
10896 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10897 };
10898 fold_ranges.push((fold_range, fold_text));
10899 }
10900
10901 let mut ranges = fold_ranges.into_iter().peekable();
10902 if ranges.peek().is_some() {
10903 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10904
10905 if auto_scroll {
10906 self.request_autoscroll(Autoscroll::fit(), cx);
10907 }
10908
10909 for buffer in buffers_affected.into_values() {
10910 self.sync_expanded_diff_hunks(buffer, cx);
10911 }
10912
10913 cx.notify();
10914
10915 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10916 // Clear diagnostics block when folding a range that contains it.
10917 let snapshot = self.snapshot(cx);
10918 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10919 drop(snapshot);
10920 self.active_diagnostics = Some(active_diagnostics);
10921 self.dismiss_diagnostics(cx);
10922 } else {
10923 self.active_diagnostics = Some(active_diagnostics);
10924 }
10925 }
10926
10927 self.scrollbar_marker_state.dirty = true;
10928 }
10929 }
10930
10931 pub fn unfold_ranges<T: ToOffset + Clone>(
10932 &mut self,
10933 ranges: impl IntoIterator<Item = Range<T>>,
10934 inclusive: bool,
10935 auto_scroll: bool,
10936 cx: &mut ViewContext<Self>,
10937 ) {
10938 let mut unfold_ranges = Vec::new();
10939 let mut buffers_affected = HashMap::default();
10940 let multi_buffer = self.buffer().read(cx);
10941 for range in ranges {
10942 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10943 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10944 };
10945 unfold_ranges.push(range);
10946 }
10947
10948 let mut ranges = unfold_ranges.into_iter().peekable();
10949 if ranges.peek().is_some() {
10950 self.display_map
10951 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10952 if auto_scroll {
10953 self.request_autoscroll(Autoscroll::fit(), cx);
10954 }
10955
10956 for buffer in buffers_affected.into_values() {
10957 self.sync_expanded_diff_hunks(buffer, cx);
10958 }
10959
10960 cx.notify();
10961 self.scrollbar_marker_state.dirty = true;
10962 self.active_indent_guides_state.dirty = true;
10963 }
10964 }
10965
10966 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10967 self.display_map.read(cx).fold_placeholder.clone()
10968 }
10969
10970 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10971 if hovered != self.gutter_hovered {
10972 self.gutter_hovered = hovered;
10973 cx.notify();
10974 }
10975 }
10976
10977 pub fn insert_blocks(
10978 &mut self,
10979 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10980 autoscroll: Option<Autoscroll>,
10981 cx: &mut ViewContext<Self>,
10982 ) -> Vec<CustomBlockId> {
10983 let blocks = self
10984 .display_map
10985 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10986 if let Some(autoscroll) = autoscroll {
10987 self.request_autoscroll(autoscroll, cx);
10988 }
10989 cx.notify();
10990 blocks
10991 }
10992
10993 pub fn resize_blocks(
10994 &mut self,
10995 heights: HashMap<CustomBlockId, u32>,
10996 autoscroll: Option<Autoscroll>,
10997 cx: &mut ViewContext<Self>,
10998 ) {
10999 self.display_map
11000 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
11001 if let Some(autoscroll) = autoscroll {
11002 self.request_autoscroll(autoscroll, cx);
11003 }
11004 cx.notify();
11005 }
11006
11007 pub fn replace_blocks(
11008 &mut self,
11009 renderers: HashMap<CustomBlockId, RenderBlock>,
11010 autoscroll: Option<Autoscroll>,
11011 cx: &mut ViewContext<Self>,
11012 ) {
11013 self.display_map
11014 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11015 if let Some(autoscroll) = autoscroll {
11016 self.request_autoscroll(autoscroll, cx);
11017 }
11018 cx.notify();
11019 }
11020
11021 pub fn remove_blocks(
11022 &mut self,
11023 block_ids: HashSet<CustomBlockId>,
11024 autoscroll: Option<Autoscroll>,
11025 cx: &mut ViewContext<Self>,
11026 ) {
11027 self.display_map.update(cx, |display_map, cx| {
11028 display_map.remove_blocks(block_ids, cx)
11029 });
11030 if let Some(autoscroll) = autoscroll {
11031 self.request_autoscroll(autoscroll, cx);
11032 }
11033 cx.notify();
11034 }
11035
11036 pub fn row_for_block(
11037 &self,
11038 block_id: CustomBlockId,
11039 cx: &mut ViewContext<Self>,
11040 ) -> Option<DisplayRow> {
11041 self.display_map
11042 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11043 }
11044
11045 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11046 self.focused_block = Some(focused_block);
11047 }
11048
11049 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11050 self.focused_block.take()
11051 }
11052
11053 pub fn insert_creases(
11054 &mut self,
11055 creases: impl IntoIterator<Item = Crease>,
11056 cx: &mut ViewContext<Self>,
11057 ) -> Vec<CreaseId> {
11058 self.display_map
11059 .update(cx, |map, cx| map.insert_creases(creases, cx))
11060 }
11061
11062 pub fn remove_creases(
11063 &mut self,
11064 ids: impl IntoIterator<Item = CreaseId>,
11065 cx: &mut ViewContext<Self>,
11066 ) {
11067 self.display_map
11068 .update(cx, |map, cx| map.remove_creases(ids, cx));
11069 }
11070
11071 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11072 self.display_map
11073 .update(cx, |map, cx| map.snapshot(cx))
11074 .longest_row()
11075 }
11076
11077 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11078 self.display_map
11079 .update(cx, |map, cx| map.snapshot(cx))
11080 .max_point()
11081 }
11082
11083 pub fn text(&self, cx: &AppContext) -> String {
11084 self.buffer.read(cx).read(cx).text()
11085 }
11086
11087 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11088 let text = self.text(cx);
11089 let text = text.trim();
11090
11091 if text.is_empty() {
11092 return None;
11093 }
11094
11095 Some(text.to_string())
11096 }
11097
11098 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11099 self.transact(cx, |this, cx| {
11100 this.buffer
11101 .read(cx)
11102 .as_singleton()
11103 .expect("you can only call set_text on editors for singleton buffers")
11104 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11105 });
11106 }
11107
11108 pub fn display_text(&self, cx: &mut AppContext) -> String {
11109 self.display_map
11110 .update(cx, |map, cx| map.snapshot(cx))
11111 .text()
11112 }
11113
11114 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11115 let mut wrap_guides = smallvec::smallvec![];
11116
11117 if self.show_wrap_guides == Some(false) {
11118 return wrap_guides;
11119 }
11120
11121 let settings = self.buffer.read(cx).settings_at(0, cx);
11122 if settings.show_wrap_guides {
11123 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11124 wrap_guides.push((soft_wrap as usize, true));
11125 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11126 wrap_guides.push((soft_wrap as usize, true));
11127 }
11128 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11129 }
11130
11131 wrap_guides
11132 }
11133
11134 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11135 let settings = self.buffer.read(cx).settings_at(0, cx);
11136 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11137 match mode {
11138 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11139 SoftWrap::None
11140 }
11141 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11142 language_settings::SoftWrap::PreferredLineLength => {
11143 SoftWrap::Column(settings.preferred_line_length)
11144 }
11145 language_settings::SoftWrap::Bounded => {
11146 SoftWrap::Bounded(settings.preferred_line_length)
11147 }
11148 }
11149 }
11150
11151 pub fn set_soft_wrap_mode(
11152 &mut self,
11153 mode: language_settings::SoftWrap,
11154 cx: &mut ViewContext<Self>,
11155 ) {
11156 self.soft_wrap_mode_override = Some(mode);
11157 cx.notify();
11158 }
11159
11160 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11161 let rem_size = cx.rem_size();
11162 self.display_map.update(cx, |map, cx| {
11163 map.set_font(
11164 style.text.font(),
11165 style.text.font_size.to_pixels(rem_size),
11166 cx,
11167 )
11168 });
11169 self.style = Some(style);
11170 }
11171
11172 pub fn style(&self) -> Option<&EditorStyle> {
11173 self.style.as_ref()
11174 }
11175
11176 // Called by the element. This method is not designed to be called outside of the editor
11177 // element's layout code because it does not notify when rewrapping is computed synchronously.
11178 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11179 self.display_map
11180 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11181 }
11182
11183 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11184 if self.soft_wrap_mode_override.is_some() {
11185 self.soft_wrap_mode_override.take();
11186 } else {
11187 let soft_wrap = match self.soft_wrap_mode(cx) {
11188 SoftWrap::GitDiff => return,
11189 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11190 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11191 language_settings::SoftWrap::None
11192 }
11193 };
11194 self.soft_wrap_mode_override = Some(soft_wrap);
11195 }
11196 cx.notify();
11197 }
11198
11199 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11200 let Some(workspace) = self.workspace() else {
11201 return;
11202 };
11203 let fs = workspace.read(cx).app_state().fs.clone();
11204 let current_show = TabBarSettings::get_global(cx).show;
11205 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11206 setting.show = Some(!current_show);
11207 });
11208 }
11209
11210 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11211 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11212 self.buffer
11213 .read(cx)
11214 .settings_at(0, cx)
11215 .indent_guides
11216 .enabled
11217 });
11218 self.show_indent_guides = Some(!currently_enabled);
11219 cx.notify();
11220 }
11221
11222 fn should_show_indent_guides(&self) -> Option<bool> {
11223 self.show_indent_guides
11224 }
11225
11226 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11227 let mut editor_settings = EditorSettings::get_global(cx).clone();
11228 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11229 EditorSettings::override_global(editor_settings, cx);
11230 }
11231
11232 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11233 self.use_relative_line_numbers
11234 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11235 }
11236
11237 pub fn toggle_relative_line_numbers(
11238 &mut self,
11239 _: &ToggleRelativeLineNumbers,
11240 cx: &mut ViewContext<Self>,
11241 ) {
11242 let is_relative = self.should_use_relative_line_numbers(cx);
11243 self.set_relative_line_number(Some(!is_relative), cx)
11244 }
11245
11246 pub fn set_relative_line_number(
11247 &mut self,
11248 is_relative: Option<bool>,
11249 cx: &mut ViewContext<Self>,
11250 ) {
11251 self.use_relative_line_numbers = is_relative;
11252 cx.notify();
11253 }
11254
11255 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11256 self.show_gutter = show_gutter;
11257 cx.notify();
11258 }
11259
11260 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11261 self.show_line_numbers = Some(show_line_numbers);
11262 cx.notify();
11263 }
11264
11265 pub fn set_show_git_diff_gutter(
11266 &mut self,
11267 show_git_diff_gutter: bool,
11268 cx: &mut ViewContext<Self>,
11269 ) {
11270 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11271 cx.notify();
11272 }
11273
11274 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11275 self.show_code_actions = Some(show_code_actions);
11276 cx.notify();
11277 }
11278
11279 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11280 self.show_runnables = Some(show_runnables);
11281 cx.notify();
11282 }
11283
11284 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11285 if self.display_map.read(cx).masked != masked {
11286 self.display_map.update(cx, |map, _| map.masked = masked);
11287 }
11288 cx.notify()
11289 }
11290
11291 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11292 self.show_wrap_guides = Some(show_wrap_guides);
11293 cx.notify();
11294 }
11295
11296 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11297 self.show_indent_guides = Some(show_indent_guides);
11298 cx.notify();
11299 }
11300
11301 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11302 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11303 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11304 if let Some(dir) = file.abs_path(cx).parent() {
11305 return Some(dir.to_owned());
11306 }
11307 }
11308
11309 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11310 return Some(project_path.path.to_path_buf());
11311 }
11312 }
11313
11314 None
11315 }
11316
11317 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11318 self.active_excerpt(cx)?
11319 .1
11320 .read(cx)
11321 .file()
11322 .and_then(|f| f.as_local())
11323 }
11324
11325 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11326 if let Some(target) = self.target_file(cx) {
11327 cx.reveal_path(&target.abs_path(cx));
11328 }
11329 }
11330
11331 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11332 if let Some(file) = self.target_file(cx) {
11333 if let Some(path) = file.abs_path(cx).to_str() {
11334 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11335 }
11336 }
11337 }
11338
11339 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11340 if let Some(file) = self.target_file(cx) {
11341 if let Some(path) = file.path().to_str() {
11342 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11343 }
11344 }
11345 }
11346
11347 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11348 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11349
11350 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11351 self.start_git_blame(true, cx);
11352 }
11353
11354 cx.notify();
11355 }
11356
11357 pub fn toggle_git_blame_inline(
11358 &mut self,
11359 _: &ToggleGitBlameInline,
11360 cx: &mut ViewContext<Self>,
11361 ) {
11362 self.toggle_git_blame_inline_internal(true, cx);
11363 cx.notify();
11364 }
11365
11366 pub fn git_blame_inline_enabled(&self) -> bool {
11367 self.git_blame_inline_enabled
11368 }
11369
11370 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11371 self.show_selection_menu = self
11372 .show_selection_menu
11373 .map(|show_selections_menu| !show_selections_menu)
11374 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11375
11376 cx.notify();
11377 }
11378
11379 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11380 self.show_selection_menu
11381 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11382 }
11383
11384 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11385 if let Some(project) = self.project.as_ref() {
11386 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11387 return;
11388 };
11389
11390 if buffer.read(cx).file().is_none() {
11391 return;
11392 }
11393
11394 let focused = self.focus_handle(cx).contains_focused(cx);
11395
11396 let project = project.clone();
11397 let blame =
11398 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11399 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11400 self.blame = Some(blame);
11401 }
11402 }
11403
11404 fn toggle_git_blame_inline_internal(
11405 &mut self,
11406 user_triggered: bool,
11407 cx: &mut ViewContext<Self>,
11408 ) {
11409 if self.git_blame_inline_enabled {
11410 self.git_blame_inline_enabled = false;
11411 self.show_git_blame_inline = false;
11412 self.show_git_blame_inline_delay_task.take();
11413 } else {
11414 self.git_blame_inline_enabled = true;
11415 self.start_git_blame_inline(user_triggered, cx);
11416 }
11417
11418 cx.notify();
11419 }
11420
11421 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11422 self.start_git_blame(user_triggered, cx);
11423
11424 if ProjectSettings::get_global(cx)
11425 .git
11426 .inline_blame_delay()
11427 .is_some()
11428 {
11429 self.start_inline_blame_timer(cx);
11430 } else {
11431 self.show_git_blame_inline = true
11432 }
11433 }
11434
11435 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11436 self.blame.as_ref()
11437 }
11438
11439 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11440 self.show_git_blame_gutter && self.has_blame_entries(cx)
11441 }
11442
11443 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11444 self.show_git_blame_inline
11445 && self.focus_handle.is_focused(cx)
11446 && !self.newest_selection_head_on_empty_line(cx)
11447 && self.has_blame_entries(cx)
11448 }
11449
11450 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11451 self.blame()
11452 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11453 }
11454
11455 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11456 let cursor_anchor = self.selections.newest_anchor().head();
11457
11458 let snapshot = self.buffer.read(cx).snapshot(cx);
11459 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11460
11461 snapshot.line_len(buffer_row) == 0
11462 }
11463
11464 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11465 let (path, selection, repo) = maybe!({
11466 let project_handle = self.project.as_ref()?.clone();
11467 let project = project_handle.read(cx);
11468
11469 let selection = self.selections.newest::<Point>(cx);
11470 let selection_range = selection.range();
11471
11472 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11473 (buffer, selection_range.start.row..selection_range.end.row)
11474 } else {
11475 let buffer_ranges = self
11476 .buffer()
11477 .read(cx)
11478 .range_to_buffer_ranges(selection_range, cx);
11479
11480 let (buffer, range, _) = if selection.reversed {
11481 buffer_ranges.first()
11482 } else {
11483 buffer_ranges.last()
11484 }?;
11485
11486 let snapshot = buffer.read(cx).snapshot();
11487 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11488 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11489 (buffer.clone(), selection)
11490 };
11491
11492 let path = buffer
11493 .read(cx)
11494 .file()?
11495 .as_local()?
11496 .path()
11497 .to_str()?
11498 .to_string();
11499 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11500 Some((path, selection, repo))
11501 })
11502 .ok_or_else(|| anyhow!("unable to open git repository"))?;
11503
11504 const REMOTE_NAME: &str = "origin";
11505 let origin_url = repo
11506 .remote_url(REMOTE_NAME)
11507 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11508 let sha = repo
11509 .head_sha()
11510 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11511
11512 let (provider, remote) =
11513 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11514 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11515
11516 Ok(provider.build_permalink(
11517 remote,
11518 BuildPermalinkParams {
11519 sha: &sha,
11520 path: &path,
11521 selection: Some(selection),
11522 },
11523 ))
11524 }
11525
11526 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11527 let permalink = self.get_permalink_to_line(cx);
11528
11529 match permalink {
11530 Ok(permalink) => {
11531 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11532 }
11533 Err(err) => {
11534 let message = format!("Failed to copy permalink: {err}");
11535
11536 Err::<(), anyhow::Error>(err).log_err();
11537
11538 if let Some(workspace) = self.workspace() {
11539 workspace.update(cx, |workspace, cx| {
11540 struct CopyPermalinkToLine;
11541
11542 workspace.show_toast(
11543 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11544 cx,
11545 )
11546 })
11547 }
11548 }
11549 }
11550 }
11551
11552 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11553 if let Some(file) = self.target_file(cx) {
11554 if let Some(path) = file.path().to_str() {
11555 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11556 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11557 }
11558 }
11559 }
11560
11561 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11562 let permalink = self.get_permalink_to_line(cx);
11563
11564 match permalink {
11565 Ok(permalink) => {
11566 cx.open_url(permalink.as_ref());
11567 }
11568 Err(err) => {
11569 let message = format!("Failed to open permalink: {err}");
11570
11571 Err::<(), anyhow::Error>(err).log_err();
11572
11573 if let Some(workspace) = self.workspace() {
11574 workspace.update(cx, |workspace, cx| {
11575 struct OpenPermalinkToLine;
11576
11577 workspace.show_toast(
11578 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11579 cx,
11580 )
11581 })
11582 }
11583 }
11584 }
11585 }
11586
11587 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11588 /// last highlight added will be used.
11589 ///
11590 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11591 pub fn highlight_rows<T: 'static>(
11592 &mut self,
11593 range: Range<Anchor>,
11594 color: Hsla,
11595 should_autoscroll: bool,
11596 cx: &mut ViewContext<Self>,
11597 ) {
11598 let snapshot = self.buffer().read(cx).snapshot(cx);
11599 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11600 let ix = row_highlights.binary_search_by(|highlight| {
11601 Ordering::Equal
11602 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11603 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11604 });
11605
11606 if let Err(mut ix) = ix {
11607 let index = post_inc(&mut self.highlight_order);
11608
11609 // If this range intersects with the preceding highlight, then merge it with
11610 // the preceding highlight. Otherwise insert a new highlight.
11611 let mut merged = false;
11612 if ix > 0 {
11613 let prev_highlight = &mut row_highlights[ix - 1];
11614 if prev_highlight
11615 .range
11616 .end
11617 .cmp(&range.start, &snapshot)
11618 .is_ge()
11619 {
11620 ix -= 1;
11621 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11622 prev_highlight.range.end = range.end;
11623 }
11624 merged = true;
11625 prev_highlight.index = index;
11626 prev_highlight.color = color;
11627 prev_highlight.should_autoscroll = should_autoscroll;
11628 }
11629 }
11630
11631 if !merged {
11632 row_highlights.insert(
11633 ix,
11634 RowHighlight {
11635 range: range.clone(),
11636 index,
11637 color,
11638 should_autoscroll,
11639 },
11640 );
11641 }
11642
11643 // If any of the following highlights intersect with this one, merge them.
11644 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11645 let highlight = &row_highlights[ix];
11646 if next_highlight
11647 .range
11648 .start
11649 .cmp(&highlight.range.end, &snapshot)
11650 .is_le()
11651 {
11652 if next_highlight
11653 .range
11654 .end
11655 .cmp(&highlight.range.end, &snapshot)
11656 .is_gt()
11657 {
11658 row_highlights[ix].range.end = next_highlight.range.end;
11659 }
11660 row_highlights.remove(ix + 1);
11661 } else {
11662 break;
11663 }
11664 }
11665 }
11666 }
11667
11668 /// Remove any highlighted row ranges of the given type that intersect the
11669 /// given ranges.
11670 pub fn remove_highlighted_rows<T: 'static>(
11671 &mut self,
11672 ranges_to_remove: Vec<Range<Anchor>>,
11673 cx: &mut ViewContext<Self>,
11674 ) {
11675 let snapshot = self.buffer().read(cx).snapshot(cx);
11676 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11677 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11678 row_highlights.retain(|highlight| {
11679 while let Some(range_to_remove) = ranges_to_remove.peek() {
11680 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11681 Ordering::Less | Ordering::Equal => {
11682 ranges_to_remove.next();
11683 }
11684 Ordering::Greater => {
11685 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11686 Ordering::Less | Ordering::Equal => {
11687 return false;
11688 }
11689 Ordering::Greater => break,
11690 }
11691 }
11692 }
11693 }
11694
11695 true
11696 })
11697 }
11698
11699 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11700 pub fn clear_row_highlights<T: 'static>(&mut self) {
11701 self.highlighted_rows.remove(&TypeId::of::<T>());
11702 }
11703
11704 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11705 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11706 self.highlighted_rows
11707 .get(&TypeId::of::<T>())
11708 .map_or(&[] as &[_], |vec| vec.as_slice())
11709 .iter()
11710 .map(|highlight| (highlight.range.clone(), highlight.color))
11711 }
11712
11713 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11714 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11715 /// Allows to ignore certain kinds of highlights.
11716 pub fn highlighted_display_rows(
11717 &mut self,
11718 cx: &mut WindowContext,
11719 ) -> BTreeMap<DisplayRow, Hsla> {
11720 let snapshot = self.snapshot(cx);
11721 let mut used_highlight_orders = HashMap::default();
11722 self.highlighted_rows
11723 .iter()
11724 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11725 .fold(
11726 BTreeMap::<DisplayRow, Hsla>::new(),
11727 |mut unique_rows, highlight| {
11728 let start = highlight.range.start.to_display_point(&snapshot);
11729 let end = highlight.range.end.to_display_point(&snapshot);
11730 let start_row = start.row().0;
11731 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11732 && end.column() == 0
11733 {
11734 end.row().0.saturating_sub(1)
11735 } else {
11736 end.row().0
11737 };
11738 for row in start_row..=end_row {
11739 let used_index =
11740 used_highlight_orders.entry(row).or_insert(highlight.index);
11741 if highlight.index >= *used_index {
11742 *used_index = highlight.index;
11743 unique_rows.insert(DisplayRow(row), highlight.color);
11744 }
11745 }
11746 unique_rows
11747 },
11748 )
11749 }
11750
11751 pub fn highlighted_display_row_for_autoscroll(
11752 &self,
11753 snapshot: &DisplaySnapshot,
11754 ) -> Option<DisplayRow> {
11755 self.highlighted_rows
11756 .values()
11757 .flat_map(|highlighted_rows| highlighted_rows.iter())
11758 .filter_map(|highlight| {
11759 if highlight.should_autoscroll {
11760 Some(highlight.range.start.to_display_point(snapshot).row())
11761 } else {
11762 None
11763 }
11764 })
11765 .min()
11766 }
11767
11768 pub fn set_search_within_ranges(
11769 &mut self,
11770 ranges: &[Range<Anchor>],
11771 cx: &mut ViewContext<Self>,
11772 ) {
11773 self.highlight_background::<SearchWithinRange>(
11774 ranges,
11775 |colors| colors.editor_document_highlight_read_background,
11776 cx,
11777 )
11778 }
11779
11780 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11781 self.breadcrumb_header = Some(new_header);
11782 }
11783
11784 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11785 self.clear_background_highlights::<SearchWithinRange>(cx);
11786 }
11787
11788 pub fn highlight_background<T: 'static>(
11789 &mut self,
11790 ranges: &[Range<Anchor>],
11791 color_fetcher: fn(&ThemeColors) -> Hsla,
11792 cx: &mut ViewContext<Self>,
11793 ) {
11794 self.background_highlights
11795 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11796 self.scrollbar_marker_state.dirty = true;
11797 cx.notify();
11798 }
11799
11800 pub fn clear_background_highlights<T: 'static>(
11801 &mut self,
11802 cx: &mut ViewContext<Self>,
11803 ) -> Option<BackgroundHighlight> {
11804 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11805 if !text_highlights.1.is_empty() {
11806 self.scrollbar_marker_state.dirty = true;
11807 cx.notify();
11808 }
11809 Some(text_highlights)
11810 }
11811
11812 pub fn highlight_gutter<T: 'static>(
11813 &mut self,
11814 ranges: &[Range<Anchor>],
11815 color_fetcher: fn(&AppContext) -> Hsla,
11816 cx: &mut ViewContext<Self>,
11817 ) {
11818 self.gutter_highlights
11819 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11820 cx.notify();
11821 }
11822
11823 pub fn clear_gutter_highlights<T: 'static>(
11824 &mut self,
11825 cx: &mut ViewContext<Self>,
11826 ) -> Option<GutterHighlight> {
11827 cx.notify();
11828 self.gutter_highlights.remove(&TypeId::of::<T>())
11829 }
11830
11831 #[cfg(feature = "test-support")]
11832 pub fn all_text_background_highlights(
11833 &mut self,
11834 cx: &mut ViewContext<Self>,
11835 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11836 let snapshot = self.snapshot(cx);
11837 let buffer = &snapshot.buffer_snapshot;
11838 let start = buffer.anchor_before(0);
11839 let end = buffer.anchor_after(buffer.len());
11840 let theme = cx.theme().colors();
11841 self.background_highlights_in_range(start..end, &snapshot, theme)
11842 }
11843
11844 #[cfg(feature = "test-support")]
11845 pub fn search_background_highlights(
11846 &mut self,
11847 cx: &mut ViewContext<Self>,
11848 ) -> Vec<Range<Point>> {
11849 let snapshot = self.buffer().read(cx).snapshot(cx);
11850
11851 let highlights = self
11852 .background_highlights
11853 .get(&TypeId::of::<items::BufferSearchHighlights>());
11854
11855 if let Some((_color, ranges)) = highlights {
11856 ranges
11857 .iter()
11858 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11859 .collect_vec()
11860 } else {
11861 vec![]
11862 }
11863 }
11864
11865 fn document_highlights_for_position<'a>(
11866 &'a self,
11867 position: Anchor,
11868 buffer: &'a MultiBufferSnapshot,
11869 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11870 let read_highlights = self
11871 .background_highlights
11872 .get(&TypeId::of::<DocumentHighlightRead>())
11873 .map(|h| &h.1);
11874 let write_highlights = self
11875 .background_highlights
11876 .get(&TypeId::of::<DocumentHighlightWrite>())
11877 .map(|h| &h.1);
11878 let left_position = position.bias_left(buffer);
11879 let right_position = position.bias_right(buffer);
11880 read_highlights
11881 .into_iter()
11882 .chain(write_highlights)
11883 .flat_map(move |ranges| {
11884 let start_ix = match ranges.binary_search_by(|probe| {
11885 let cmp = probe.end.cmp(&left_position, buffer);
11886 if cmp.is_ge() {
11887 Ordering::Greater
11888 } else {
11889 Ordering::Less
11890 }
11891 }) {
11892 Ok(i) | Err(i) => i,
11893 };
11894
11895 ranges[start_ix..]
11896 .iter()
11897 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11898 })
11899 }
11900
11901 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11902 self.background_highlights
11903 .get(&TypeId::of::<T>())
11904 .map_or(false, |(_, highlights)| !highlights.is_empty())
11905 }
11906
11907 pub fn background_highlights_in_range(
11908 &self,
11909 search_range: Range<Anchor>,
11910 display_snapshot: &DisplaySnapshot,
11911 theme: &ThemeColors,
11912 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11913 let mut results = Vec::new();
11914 for (color_fetcher, ranges) in self.background_highlights.values() {
11915 let color = color_fetcher(theme);
11916 let start_ix = match ranges.binary_search_by(|probe| {
11917 let cmp = probe
11918 .end
11919 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11920 if cmp.is_gt() {
11921 Ordering::Greater
11922 } else {
11923 Ordering::Less
11924 }
11925 }) {
11926 Ok(i) | Err(i) => i,
11927 };
11928 for range in &ranges[start_ix..] {
11929 if range
11930 .start
11931 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11932 .is_ge()
11933 {
11934 break;
11935 }
11936
11937 let start = range.start.to_display_point(display_snapshot);
11938 let end = range.end.to_display_point(display_snapshot);
11939 results.push((start..end, color))
11940 }
11941 }
11942 results
11943 }
11944
11945 pub fn background_highlight_row_ranges<T: 'static>(
11946 &self,
11947 search_range: Range<Anchor>,
11948 display_snapshot: &DisplaySnapshot,
11949 count: usize,
11950 ) -> Vec<RangeInclusive<DisplayPoint>> {
11951 let mut results = Vec::new();
11952 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11953 return vec![];
11954 };
11955
11956 let start_ix = match ranges.binary_search_by(|probe| {
11957 let cmp = probe
11958 .end
11959 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11960 if cmp.is_gt() {
11961 Ordering::Greater
11962 } else {
11963 Ordering::Less
11964 }
11965 }) {
11966 Ok(i) | Err(i) => i,
11967 };
11968 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11969 if let (Some(start_display), Some(end_display)) = (start, end) {
11970 results.push(
11971 start_display.to_display_point(display_snapshot)
11972 ..=end_display.to_display_point(display_snapshot),
11973 );
11974 }
11975 };
11976 let mut start_row: Option<Point> = None;
11977 let mut end_row: Option<Point> = None;
11978 if ranges.len() > count {
11979 return Vec::new();
11980 }
11981 for range in &ranges[start_ix..] {
11982 if range
11983 .start
11984 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11985 .is_ge()
11986 {
11987 break;
11988 }
11989 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11990 if let Some(current_row) = &end_row {
11991 if end.row == current_row.row {
11992 continue;
11993 }
11994 }
11995 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11996 if start_row.is_none() {
11997 assert_eq!(end_row, None);
11998 start_row = Some(start);
11999 end_row = Some(end);
12000 continue;
12001 }
12002 if let Some(current_end) = end_row.as_mut() {
12003 if start.row > current_end.row + 1 {
12004 push_region(start_row, end_row);
12005 start_row = Some(start);
12006 end_row = Some(end);
12007 } else {
12008 // Merge two hunks.
12009 *current_end = end;
12010 }
12011 } else {
12012 unreachable!();
12013 }
12014 }
12015 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12016 push_region(start_row, end_row);
12017 results
12018 }
12019
12020 pub fn gutter_highlights_in_range(
12021 &self,
12022 search_range: Range<Anchor>,
12023 display_snapshot: &DisplaySnapshot,
12024 cx: &AppContext,
12025 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12026 let mut results = Vec::new();
12027 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12028 let color = color_fetcher(cx);
12029 let start_ix = match ranges.binary_search_by(|probe| {
12030 let cmp = probe
12031 .end
12032 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12033 if cmp.is_gt() {
12034 Ordering::Greater
12035 } else {
12036 Ordering::Less
12037 }
12038 }) {
12039 Ok(i) | Err(i) => i,
12040 };
12041 for range in &ranges[start_ix..] {
12042 if range
12043 .start
12044 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12045 .is_ge()
12046 {
12047 break;
12048 }
12049
12050 let start = range.start.to_display_point(display_snapshot);
12051 let end = range.end.to_display_point(display_snapshot);
12052 results.push((start..end, color))
12053 }
12054 }
12055 results
12056 }
12057
12058 /// Get the text ranges corresponding to the redaction query
12059 pub fn redacted_ranges(
12060 &self,
12061 search_range: Range<Anchor>,
12062 display_snapshot: &DisplaySnapshot,
12063 cx: &WindowContext,
12064 ) -> Vec<Range<DisplayPoint>> {
12065 display_snapshot
12066 .buffer_snapshot
12067 .redacted_ranges(search_range, |file| {
12068 if let Some(file) = file {
12069 file.is_private()
12070 && EditorSettings::get(
12071 Some(SettingsLocation {
12072 worktree_id: file.worktree_id(cx),
12073 path: file.path().as_ref(),
12074 }),
12075 cx,
12076 )
12077 .redact_private_values
12078 } else {
12079 false
12080 }
12081 })
12082 .map(|range| {
12083 range.start.to_display_point(display_snapshot)
12084 ..range.end.to_display_point(display_snapshot)
12085 })
12086 .collect()
12087 }
12088
12089 pub fn highlight_text<T: 'static>(
12090 &mut self,
12091 ranges: Vec<Range<Anchor>>,
12092 style: HighlightStyle,
12093 cx: &mut ViewContext<Self>,
12094 ) {
12095 self.display_map.update(cx, |map, _| {
12096 map.highlight_text(TypeId::of::<T>(), ranges, style)
12097 });
12098 cx.notify();
12099 }
12100
12101 pub(crate) fn highlight_inlays<T: 'static>(
12102 &mut self,
12103 highlights: Vec<InlayHighlight>,
12104 style: HighlightStyle,
12105 cx: &mut ViewContext<Self>,
12106 ) {
12107 self.display_map.update(cx, |map, _| {
12108 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12109 });
12110 cx.notify();
12111 }
12112
12113 pub fn text_highlights<'a, T: 'static>(
12114 &'a self,
12115 cx: &'a AppContext,
12116 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12117 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12118 }
12119
12120 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12121 let cleared = self
12122 .display_map
12123 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12124 if cleared {
12125 cx.notify();
12126 }
12127 }
12128
12129 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12130 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12131 && self.focus_handle.is_focused(cx)
12132 }
12133
12134 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12135 self.show_cursor_when_unfocused = is_enabled;
12136 cx.notify();
12137 }
12138
12139 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12140 cx.notify();
12141 }
12142
12143 fn on_buffer_event(
12144 &mut self,
12145 multibuffer: Model<MultiBuffer>,
12146 event: &multi_buffer::Event,
12147 cx: &mut ViewContext<Self>,
12148 ) {
12149 match event {
12150 multi_buffer::Event::Edited {
12151 singleton_buffer_edited,
12152 } => {
12153 self.scrollbar_marker_state.dirty = true;
12154 self.active_indent_guides_state.dirty = true;
12155 self.refresh_active_diagnostics(cx);
12156 self.refresh_code_actions(cx);
12157 if self.has_active_inline_completion(cx) {
12158 self.update_visible_inline_completion(cx);
12159 }
12160 cx.emit(EditorEvent::BufferEdited);
12161 cx.emit(SearchEvent::MatchesInvalidated);
12162 if *singleton_buffer_edited {
12163 if let Some(project) = &self.project {
12164 let project = project.read(cx);
12165 #[allow(clippy::mutable_key_type)]
12166 let languages_affected = multibuffer
12167 .read(cx)
12168 .all_buffers()
12169 .into_iter()
12170 .filter_map(|buffer| {
12171 let buffer = buffer.read(cx);
12172 let language = buffer.language()?;
12173 if project.is_local()
12174 && project.language_servers_for_buffer(buffer, cx).count() == 0
12175 {
12176 None
12177 } else {
12178 Some(language)
12179 }
12180 })
12181 .cloned()
12182 .collect::<HashSet<_>>();
12183 if !languages_affected.is_empty() {
12184 self.refresh_inlay_hints(
12185 InlayHintRefreshReason::BufferEdited(languages_affected),
12186 cx,
12187 );
12188 }
12189 }
12190 }
12191
12192 let Some(project) = &self.project else { return };
12193 let (telemetry, is_via_ssh) = {
12194 let project = project.read(cx);
12195 let telemetry = project.client().telemetry().clone();
12196 let is_via_ssh = project.is_via_ssh();
12197 (telemetry, is_via_ssh)
12198 };
12199 refresh_linked_ranges(self, cx);
12200 telemetry.log_edit_event("editor", is_via_ssh);
12201 }
12202 multi_buffer::Event::ExcerptsAdded {
12203 buffer,
12204 predecessor,
12205 excerpts,
12206 } => {
12207 self.tasks_update_task = Some(self.refresh_runnables(cx));
12208 cx.emit(EditorEvent::ExcerptsAdded {
12209 buffer: buffer.clone(),
12210 predecessor: *predecessor,
12211 excerpts: excerpts.clone(),
12212 });
12213 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12214 }
12215 multi_buffer::Event::ExcerptsRemoved { ids } => {
12216 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12217 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12218 }
12219 multi_buffer::Event::ExcerptsEdited { ids } => {
12220 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12221 }
12222 multi_buffer::Event::ExcerptsExpanded { ids } => {
12223 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12224 }
12225 multi_buffer::Event::Reparsed(buffer_id) => {
12226 self.tasks_update_task = Some(self.refresh_runnables(cx));
12227
12228 cx.emit(EditorEvent::Reparsed(*buffer_id));
12229 }
12230 multi_buffer::Event::LanguageChanged(buffer_id) => {
12231 linked_editing_ranges::refresh_linked_ranges(self, cx);
12232 cx.emit(EditorEvent::Reparsed(*buffer_id));
12233 cx.notify();
12234 }
12235 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12236 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12237 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12238 cx.emit(EditorEvent::TitleChanged)
12239 }
12240 multi_buffer::Event::DiffBaseChanged => {
12241 self.scrollbar_marker_state.dirty = true;
12242 cx.emit(EditorEvent::DiffBaseChanged);
12243 cx.notify();
12244 }
12245 multi_buffer::Event::DiffUpdated { buffer } => {
12246 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12247 cx.notify();
12248 }
12249 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12250 multi_buffer::Event::DiagnosticsUpdated => {
12251 self.refresh_active_diagnostics(cx);
12252 self.scrollbar_marker_state.dirty = true;
12253 cx.notify();
12254 }
12255 _ => {}
12256 };
12257 }
12258
12259 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12260 cx.notify();
12261 }
12262
12263 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12264 self.tasks_update_task = Some(self.refresh_runnables(cx));
12265 self.refresh_inline_completion(true, false, cx);
12266 self.refresh_inlay_hints(
12267 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12268 self.selections.newest_anchor().head(),
12269 &self.buffer.read(cx).snapshot(cx),
12270 cx,
12271 )),
12272 cx,
12273 );
12274
12275 let old_cursor_shape = self.cursor_shape;
12276
12277 {
12278 let editor_settings = EditorSettings::get_global(cx);
12279 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12280 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12281 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12282 }
12283
12284 if old_cursor_shape != self.cursor_shape {
12285 cx.emit(EditorEvent::CursorShapeChanged);
12286 }
12287
12288 let project_settings = ProjectSettings::get_global(cx);
12289 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12290
12291 if self.mode == EditorMode::Full {
12292 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12293 if self.git_blame_inline_enabled != inline_blame_enabled {
12294 self.toggle_git_blame_inline_internal(false, cx);
12295 }
12296 }
12297
12298 cx.notify();
12299 }
12300
12301 pub fn set_searchable(&mut self, searchable: bool) {
12302 self.searchable = searchable;
12303 }
12304
12305 pub fn searchable(&self) -> bool {
12306 self.searchable
12307 }
12308
12309 fn open_proposed_changes_editor(
12310 &mut self,
12311 _: &OpenProposedChangesEditor,
12312 cx: &mut ViewContext<Self>,
12313 ) {
12314 let Some(workspace) = self.workspace() else {
12315 cx.propagate();
12316 return;
12317 };
12318
12319 let buffer = self.buffer.read(cx);
12320 let mut new_selections_by_buffer = HashMap::default();
12321 for selection in self.selections.all::<usize>(cx) {
12322 for (buffer, range, _) in
12323 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12324 {
12325 let mut range = range.to_point(buffer.read(cx));
12326 range.start.column = 0;
12327 range.end.column = buffer.read(cx).line_len(range.end.row);
12328 new_selections_by_buffer
12329 .entry(buffer)
12330 .or_insert(Vec::new())
12331 .push(range)
12332 }
12333 }
12334
12335 let proposed_changes_buffers = new_selections_by_buffer
12336 .into_iter()
12337 .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
12338 .collect::<Vec<_>>();
12339 let proposed_changes_editor = cx.new_view(|cx| {
12340 ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
12341 });
12342
12343 cx.window_context().defer(move |cx| {
12344 workspace.update(cx, |workspace, cx| {
12345 workspace.active_pane().update(cx, |pane, cx| {
12346 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12347 });
12348 });
12349 });
12350 }
12351
12352 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12353 self.open_excerpts_common(true, cx)
12354 }
12355
12356 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12357 self.open_excerpts_common(false, cx)
12358 }
12359
12360 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12361 let buffer = self.buffer.read(cx);
12362 if buffer.is_singleton() {
12363 cx.propagate();
12364 return;
12365 }
12366
12367 let Some(workspace) = self.workspace() else {
12368 cx.propagate();
12369 return;
12370 };
12371
12372 let mut new_selections_by_buffer = HashMap::default();
12373 for selection in self.selections.all::<usize>(cx) {
12374 for (buffer, mut range, _) in
12375 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12376 {
12377 if selection.reversed {
12378 mem::swap(&mut range.start, &mut range.end);
12379 }
12380 new_selections_by_buffer
12381 .entry(buffer)
12382 .or_insert(Vec::new())
12383 .push(range)
12384 }
12385 }
12386
12387 // We defer the pane interaction because we ourselves are a workspace item
12388 // and activating a new item causes the pane to call a method on us reentrantly,
12389 // which panics if we're on the stack.
12390 cx.window_context().defer(move |cx| {
12391 workspace.update(cx, |workspace, cx| {
12392 let pane = if split {
12393 workspace.adjacent_pane(cx)
12394 } else {
12395 workspace.active_pane().clone()
12396 };
12397
12398 for (buffer, ranges) in new_selections_by_buffer {
12399 let editor =
12400 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12401 editor.update(cx, |editor, cx| {
12402 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12403 s.select_ranges(ranges);
12404 });
12405 });
12406 }
12407 })
12408 });
12409 }
12410
12411 fn jump(
12412 &mut self,
12413 path: ProjectPath,
12414 position: Point,
12415 anchor: language::Anchor,
12416 offset_from_top: u32,
12417 cx: &mut ViewContext<Self>,
12418 ) {
12419 let workspace = self.workspace();
12420 cx.spawn(|_, mut cx| async move {
12421 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12422 let editor = workspace.update(&mut cx, |workspace, cx| {
12423 // Reset the preview item id before opening the new item
12424 workspace.active_pane().update(cx, |pane, cx| {
12425 pane.set_preview_item_id(None, cx);
12426 });
12427 workspace.open_path_preview(path, None, true, true, cx)
12428 })?;
12429 let editor = editor
12430 .await?
12431 .downcast::<Editor>()
12432 .ok_or_else(|| anyhow!("opened item was not an editor"))?
12433 .downgrade();
12434 editor.update(&mut cx, |editor, cx| {
12435 let buffer = editor
12436 .buffer()
12437 .read(cx)
12438 .as_singleton()
12439 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12440 let buffer = buffer.read(cx);
12441 let cursor = if buffer.can_resolve(&anchor) {
12442 language::ToPoint::to_point(&anchor, buffer)
12443 } else {
12444 buffer.clip_point(position, Bias::Left)
12445 };
12446
12447 let nav_history = editor.nav_history.take();
12448 editor.change_selections(
12449 Some(Autoscroll::top_relative(offset_from_top as usize)),
12450 cx,
12451 |s| {
12452 s.select_ranges([cursor..cursor]);
12453 },
12454 );
12455 editor.nav_history = nav_history;
12456
12457 anyhow::Ok(())
12458 })??;
12459
12460 anyhow::Ok(())
12461 })
12462 .detach_and_log_err(cx);
12463 }
12464
12465 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12466 let snapshot = self.buffer.read(cx).read(cx);
12467 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12468 Some(
12469 ranges
12470 .iter()
12471 .map(move |range| {
12472 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12473 })
12474 .collect(),
12475 )
12476 }
12477
12478 fn selection_replacement_ranges(
12479 &self,
12480 range: Range<OffsetUtf16>,
12481 cx: &AppContext,
12482 ) -> Vec<Range<OffsetUtf16>> {
12483 let selections = self.selections.all::<OffsetUtf16>(cx);
12484 let newest_selection = selections
12485 .iter()
12486 .max_by_key(|selection| selection.id)
12487 .unwrap();
12488 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12489 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12490 let snapshot = self.buffer.read(cx).read(cx);
12491 selections
12492 .into_iter()
12493 .map(|mut selection| {
12494 selection.start.0 =
12495 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12496 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12497 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12498 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12499 })
12500 .collect()
12501 }
12502
12503 fn report_editor_event(
12504 &self,
12505 operation: &'static str,
12506 file_extension: Option<String>,
12507 cx: &AppContext,
12508 ) {
12509 if cfg!(any(test, feature = "test-support")) {
12510 return;
12511 }
12512
12513 let Some(project) = &self.project else { return };
12514
12515 // If None, we are in a file without an extension
12516 let file = self
12517 .buffer
12518 .read(cx)
12519 .as_singleton()
12520 .and_then(|b| b.read(cx).file());
12521 let file_extension = file_extension.or(file
12522 .as_ref()
12523 .and_then(|file| Path::new(file.file_name(cx)).extension())
12524 .and_then(|e| e.to_str())
12525 .map(|a| a.to_string()));
12526
12527 let vim_mode = cx
12528 .global::<SettingsStore>()
12529 .raw_user_settings()
12530 .get("vim_mode")
12531 == Some(&serde_json::Value::Bool(true));
12532
12533 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12534 == language::language_settings::InlineCompletionProvider::Copilot;
12535 let copilot_enabled_for_language = self
12536 .buffer
12537 .read(cx)
12538 .settings_at(0, cx)
12539 .show_inline_completions;
12540
12541 let project = project.read(cx);
12542 let telemetry = project.client().telemetry().clone();
12543 telemetry.report_editor_event(
12544 file_extension,
12545 vim_mode,
12546 operation,
12547 copilot_enabled,
12548 copilot_enabled_for_language,
12549 project.is_via_ssh(),
12550 )
12551 }
12552
12553 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12554 /// with each line being an array of {text, highlight} objects.
12555 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12556 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12557 return;
12558 };
12559
12560 #[derive(Serialize)]
12561 struct Chunk<'a> {
12562 text: String,
12563 highlight: Option<&'a str>,
12564 }
12565
12566 let snapshot = buffer.read(cx).snapshot();
12567 let range = self
12568 .selected_text_range(false, cx)
12569 .and_then(|selection| {
12570 if selection.range.is_empty() {
12571 None
12572 } else {
12573 Some(selection.range)
12574 }
12575 })
12576 .unwrap_or_else(|| 0..snapshot.len());
12577
12578 let chunks = snapshot.chunks(range, true);
12579 let mut lines = Vec::new();
12580 let mut line: VecDeque<Chunk> = VecDeque::new();
12581
12582 let Some(style) = self.style.as_ref() else {
12583 return;
12584 };
12585
12586 for chunk in chunks {
12587 let highlight = chunk
12588 .syntax_highlight_id
12589 .and_then(|id| id.name(&style.syntax));
12590 let mut chunk_lines = chunk.text.split('\n').peekable();
12591 while let Some(text) = chunk_lines.next() {
12592 let mut merged_with_last_token = false;
12593 if let Some(last_token) = line.back_mut() {
12594 if last_token.highlight == highlight {
12595 last_token.text.push_str(text);
12596 merged_with_last_token = true;
12597 }
12598 }
12599
12600 if !merged_with_last_token {
12601 line.push_back(Chunk {
12602 text: text.into(),
12603 highlight,
12604 });
12605 }
12606
12607 if chunk_lines.peek().is_some() {
12608 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12609 line.pop_front();
12610 }
12611 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12612 line.pop_back();
12613 }
12614
12615 lines.push(mem::take(&mut line));
12616 }
12617 }
12618 }
12619
12620 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12621 return;
12622 };
12623 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12624 }
12625
12626 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12627 &self.inlay_hint_cache
12628 }
12629
12630 pub fn replay_insert_event(
12631 &mut self,
12632 text: &str,
12633 relative_utf16_range: Option<Range<isize>>,
12634 cx: &mut ViewContext<Self>,
12635 ) {
12636 if !self.input_enabled {
12637 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12638 return;
12639 }
12640 if let Some(relative_utf16_range) = relative_utf16_range {
12641 let selections = self.selections.all::<OffsetUtf16>(cx);
12642 self.change_selections(None, cx, |s| {
12643 let new_ranges = selections.into_iter().map(|range| {
12644 let start = OffsetUtf16(
12645 range
12646 .head()
12647 .0
12648 .saturating_add_signed(relative_utf16_range.start),
12649 );
12650 let end = OffsetUtf16(
12651 range
12652 .head()
12653 .0
12654 .saturating_add_signed(relative_utf16_range.end),
12655 );
12656 start..end
12657 });
12658 s.select_ranges(new_ranges);
12659 });
12660 }
12661
12662 self.handle_input(text, cx);
12663 }
12664
12665 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12666 let Some(project) = self.project.as_ref() else {
12667 return false;
12668 };
12669 let project = project.read(cx);
12670
12671 let mut supports = false;
12672 self.buffer().read(cx).for_each_buffer(|buffer| {
12673 if !supports {
12674 supports = project
12675 .language_servers_for_buffer(buffer.read(cx), cx)
12676 .any(
12677 |(_, server)| match server.capabilities().inlay_hint_provider {
12678 Some(lsp::OneOf::Left(enabled)) => enabled,
12679 Some(lsp::OneOf::Right(_)) => true,
12680 None => false,
12681 },
12682 )
12683 }
12684 });
12685 supports
12686 }
12687
12688 pub fn focus(&self, cx: &mut WindowContext) {
12689 cx.focus(&self.focus_handle)
12690 }
12691
12692 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12693 self.focus_handle.is_focused(cx)
12694 }
12695
12696 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12697 cx.emit(EditorEvent::Focused);
12698
12699 if let Some(descendant) = self
12700 .last_focused_descendant
12701 .take()
12702 .and_then(|descendant| descendant.upgrade())
12703 {
12704 cx.focus(&descendant);
12705 } else {
12706 if let Some(blame) = self.blame.as_ref() {
12707 blame.update(cx, GitBlame::focus)
12708 }
12709
12710 self.blink_manager.update(cx, BlinkManager::enable);
12711 self.show_cursor_names(cx);
12712 self.buffer.update(cx, |buffer, cx| {
12713 buffer.finalize_last_transaction(cx);
12714 if self.leader_peer_id.is_none() {
12715 buffer.set_active_selections(
12716 &self.selections.disjoint_anchors(),
12717 self.selections.line_mode,
12718 self.cursor_shape,
12719 cx,
12720 );
12721 }
12722 });
12723 }
12724 }
12725
12726 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12727 cx.emit(EditorEvent::FocusedIn)
12728 }
12729
12730 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12731 if event.blurred != self.focus_handle {
12732 self.last_focused_descendant = Some(event.blurred);
12733 }
12734 }
12735
12736 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12737 self.blink_manager.update(cx, BlinkManager::disable);
12738 self.buffer
12739 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12740
12741 if let Some(blame) = self.blame.as_ref() {
12742 blame.update(cx, GitBlame::blur)
12743 }
12744 if !self.hover_state.focused(cx) {
12745 hide_hover(self, cx);
12746 }
12747
12748 self.hide_context_menu(cx);
12749 cx.emit(EditorEvent::Blurred);
12750 cx.notify();
12751 }
12752
12753 pub fn register_action<A: Action>(
12754 &mut self,
12755 listener: impl Fn(&A, &mut WindowContext) + 'static,
12756 ) -> Subscription {
12757 let id = self.next_editor_action_id.post_inc();
12758 let listener = Arc::new(listener);
12759 self.editor_actions.borrow_mut().insert(
12760 id,
12761 Box::new(move |cx| {
12762 let cx = cx.window_context();
12763 let listener = listener.clone();
12764 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12765 let action = action.downcast_ref().unwrap();
12766 if phase == DispatchPhase::Bubble {
12767 listener(action, cx)
12768 }
12769 })
12770 }),
12771 );
12772
12773 let editor_actions = self.editor_actions.clone();
12774 Subscription::new(move || {
12775 editor_actions.borrow_mut().remove(&id);
12776 })
12777 }
12778
12779 pub fn file_header_size(&self) -> u32 {
12780 self.file_header_size
12781 }
12782
12783 pub fn revert(
12784 &mut self,
12785 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12786 cx: &mut ViewContext<Self>,
12787 ) {
12788 self.buffer().update(cx, |multi_buffer, cx| {
12789 for (buffer_id, changes) in revert_changes {
12790 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12791 buffer.update(cx, |buffer, cx| {
12792 buffer.edit(
12793 changes.into_iter().map(|(range, text)| {
12794 (range, text.to_string().map(Arc::<str>::from))
12795 }),
12796 None,
12797 cx,
12798 );
12799 });
12800 }
12801 }
12802 });
12803 self.change_selections(None, cx, |selections| selections.refresh());
12804 }
12805
12806 pub fn to_pixel_point(
12807 &mut self,
12808 source: multi_buffer::Anchor,
12809 editor_snapshot: &EditorSnapshot,
12810 cx: &mut ViewContext<Self>,
12811 ) -> Option<gpui::Point<Pixels>> {
12812 let source_point = source.to_display_point(editor_snapshot);
12813 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12814 }
12815
12816 pub fn display_to_pixel_point(
12817 &mut self,
12818 source: DisplayPoint,
12819 editor_snapshot: &EditorSnapshot,
12820 cx: &mut ViewContext<Self>,
12821 ) -> Option<gpui::Point<Pixels>> {
12822 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12823 let text_layout_details = self.text_layout_details(cx);
12824 let scroll_top = text_layout_details
12825 .scroll_anchor
12826 .scroll_position(editor_snapshot)
12827 .y;
12828
12829 if source.row().as_f32() < scroll_top.floor() {
12830 return None;
12831 }
12832 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12833 let source_y = line_height * (source.row().as_f32() - scroll_top);
12834 Some(gpui::Point::new(source_x, source_y))
12835 }
12836
12837 pub fn has_active_completions_menu(&self) -> bool {
12838 self.context_menu.read().as_ref().map_or(false, |menu| {
12839 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12840 })
12841 }
12842
12843 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12844 self.addons
12845 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12846 }
12847
12848 pub fn unregister_addon<T: Addon>(&mut self) {
12849 self.addons.remove(&std::any::TypeId::of::<T>());
12850 }
12851
12852 pub fn addon<T: Addon>(&self) -> Option<&T> {
12853 let type_id = std::any::TypeId::of::<T>();
12854 self.addons
12855 .get(&type_id)
12856 .and_then(|item| item.to_any().downcast_ref::<T>())
12857 }
12858}
12859
12860fn hunks_for_selections(
12861 multi_buffer_snapshot: &MultiBufferSnapshot,
12862 selections: &[Selection<Anchor>],
12863) -> Vec<MultiBufferDiffHunk> {
12864 let buffer_rows_for_selections = selections.iter().map(|selection| {
12865 let head = selection.head();
12866 let tail = selection.tail();
12867 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12868 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12869 if start > end {
12870 end..start
12871 } else {
12872 start..end
12873 }
12874 });
12875
12876 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12877}
12878
12879pub fn hunks_for_rows(
12880 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12881 multi_buffer_snapshot: &MultiBufferSnapshot,
12882) -> Vec<MultiBufferDiffHunk> {
12883 let mut hunks = Vec::new();
12884 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12885 HashMap::default();
12886 for selected_multi_buffer_rows in rows {
12887 let query_rows =
12888 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12889 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12890 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12891 // when the caret is just above or just below the deleted hunk.
12892 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12893 let related_to_selection = if allow_adjacent {
12894 hunk.row_range.overlaps(&query_rows)
12895 || hunk.row_range.start == query_rows.end
12896 || hunk.row_range.end == query_rows.start
12897 } else {
12898 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12899 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12900 hunk.row_range.overlaps(&selected_multi_buffer_rows)
12901 || selected_multi_buffer_rows.end == hunk.row_range.start
12902 };
12903 if related_to_selection {
12904 if !processed_buffer_rows
12905 .entry(hunk.buffer_id)
12906 .or_default()
12907 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12908 {
12909 continue;
12910 }
12911 hunks.push(hunk);
12912 }
12913 }
12914 }
12915
12916 hunks
12917}
12918
12919pub trait CollaborationHub {
12920 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12921 fn user_participant_indices<'a>(
12922 &self,
12923 cx: &'a AppContext,
12924 ) -> &'a HashMap<u64, ParticipantIndex>;
12925 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12926}
12927
12928impl CollaborationHub for Model<Project> {
12929 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12930 self.read(cx).collaborators()
12931 }
12932
12933 fn user_participant_indices<'a>(
12934 &self,
12935 cx: &'a AppContext,
12936 ) -> &'a HashMap<u64, ParticipantIndex> {
12937 self.read(cx).user_store().read(cx).participant_indices()
12938 }
12939
12940 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12941 let this = self.read(cx);
12942 let user_ids = this.collaborators().values().map(|c| c.user_id);
12943 this.user_store().read_with(cx, |user_store, cx| {
12944 user_store.participant_names(user_ids, cx)
12945 })
12946 }
12947}
12948
12949pub trait CompletionProvider {
12950 fn completions(
12951 &self,
12952 buffer: &Model<Buffer>,
12953 buffer_position: text::Anchor,
12954 trigger: CompletionContext,
12955 cx: &mut ViewContext<Editor>,
12956 ) -> Task<Result<Vec<Completion>>>;
12957
12958 fn resolve_completions(
12959 &self,
12960 buffer: Model<Buffer>,
12961 completion_indices: Vec<usize>,
12962 completions: Arc<RwLock<Box<[Completion]>>>,
12963 cx: &mut ViewContext<Editor>,
12964 ) -> Task<Result<bool>>;
12965
12966 fn apply_additional_edits_for_completion(
12967 &self,
12968 buffer: Model<Buffer>,
12969 completion: Completion,
12970 push_to_history: bool,
12971 cx: &mut ViewContext<Editor>,
12972 ) -> Task<Result<Option<language::Transaction>>>;
12973
12974 fn is_completion_trigger(
12975 &self,
12976 buffer: &Model<Buffer>,
12977 position: language::Anchor,
12978 text: &str,
12979 trigger_in_words: bool,
12980 cx: &mut ViewContext<Editor>,
12981 ) -> bool;
12982
12983 fn sort_completions(&self) -> bool {
12984 true
12985 }
12986}
12987
12988pub trait CodeActionProvider {
12989 fn code_actions(
12990 &self,
12991 buffer: &Model<Buffer>,
12992 range: Range<text::Anchor>,
12993 cx: &mut WindowContext,
12994 ) -> Task<Result<Vec<CodeAction>>>;
12995
12996 fn apply_code_action(
12997 &self,
12998 buffer_handle: Model<Buffer>,
12999 action: CodeAction,
13000 excerpt_id: ExcerptId,
13001 push_to_history: bool,
13002 cx: &mut WindowContext,
13003 ) -> Task<Result<ProjectTransaction>>;
13004}
13005
13006impl CodeActionProvider for Model<Project> {
13007 fn code_actions(
13008 &self,
13009 buffer: &Model<Buffer>,
13010 range: Range<text::Anchor>,
13011 cx: &mut WindowContext,
13012 ) -> Task<Result<Vec<CodeAction>>> {
13013 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
13014 }
13015
13016 fn apply_code_action(
13017 &self,
13018 buffer_handle: Model<Buffer>,
13019 action: CodeAction,
13020 _excerpt_id: ExcerptId,
13021 push_to_history: bool,
13022 cx: &mut WindowContext,
13023 ) -> Task<Result<ProjectTransaction>> {
13024 self.update(cx, |project, cx| {
13025 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13026 })
13027 }
13028}
13029
13030fn snippet_completions(
13031 project: &Project,
13032 buffer: &Model<Buffer>,
13033 buffer_position: text::Anchor,
13034 cx: &mut AppContext,
13035) -> Vec<Completion> {
13036 let language = buffer.read(cx).language_at(buffer_position);
13037 let language_name = language.as_ref().map(|language| language.lsp_id());
13038 let snippet_store = project.snippets().read(cx);
13039 let snippets = snippet_store.snippets_for(language_name, cx);
13040
13041 if snippets.is_empty() {
13042 return vec![];
13043 }
13044 let snapshot = buffer.read(cx).text_snapshot();
13045 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
13046
13047 let mut lines = chunks.lines();
13048 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
13049 return vec![];
13050 };
13051
13052 let scope = language.map(|language| language.default_scope());
13053 let classifier = CharClassifier::new(scope).for_completion(true);
13054 let mut last_word = line_at
13055 .chars()
13056 .rev()
13057 .take_while(|c| classifier.is_word(*c))
13058 .collect::<String>();
13059 last_word = last_word.chars().rev().collect();
13060 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13061 let to_lsp = |point: &text::Anchor| {
13062 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13063 point_to_lsp(end)
13064 };
13065 let lsp_end = to_lsp(&buffer_position);
13066 snippets
13067 .into_iter()
13068 .filter_map(|snippet| {
13069 let matching_prefix = snippet
13070 .prefix
13071 .iter()
13072 .find(|prefix| prefix.starts_with(&last_word))?;
13073 let start = as_offset - last_word.len();
13074 let start = snapshot.anchor_before(start);
13075 let range = start..buffer_position;
13076 let lsp_start = to_lsp(&start);
13077 let lsp_range = lsp::Range {
13078 start: lsp_start,
13079 end: lsp_end,
13080 };
13081 Some(Completion {
13082 old_range: range,
13083 new_text: snippet.body.clone(),
13084 label: CodeLabel {
13085 text: matching_prefix.clone(),
13086 runs: vec![],
13087 filter_range: 0..matching_prefix.len(),
13088 },
13089 server_id: LanguageServerId(usize::MAX),
13090 documentation: snippet.description.clone().map(Documentation::SingleLine),
13091 lsp_completion: lsp::CompletionItem {
13092 label: snippet.prefix.first().unwrap().clone(),
13093 kind: Some(CompletionItemKind::SNIPPET),
13094 label_details: snippet.description.as_ref().map(|description| {
13095 lsp::CompletionItemLabelDetails {
13096 detail: Some(description.clone()),
13097 description: None,
13098 }
13099 }),
13100 insert_text_format: Some(InsertTextFormat::SNIPPET),
13101 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13102 lsp::InsertReplaceEdit {
13103 new_text: snippet.body.clone(),
13104 insert: lsp_range,
13105 replace: lsp_range,
13106 },
13107 )),
13108 filter_text: Some(snippet.body.clone()),
13109 sort_text: Some(char::MAX.to_string()),
13110 ..Default::default()
13111 },
13112 confirm: None,
13113 })
13114 })
13115 .collect()
13116}
13117
13118impl CompletionProvider for Model<Project> {
13119 fn completions(
13120 &self,
13121 buffer: &Model<Buffer>,
13122 buffer_position: text::Anchor,
13123 options: CompletionContext,
13124 cx: &mut ViewContext<Editor>,
13125 ) -> Task<Result<Vec<Completion>>> {
13126 self.update(cx, |project, cx| {
13127 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13128 let project_completions = project.completions(buffer, buffer_position, options, cx);
13129 cx.background_executor().spawn(async move {
13130 let mut completions = project_completions.await?;
13131 //let snippets = snippets.into_iter().;
13132 completions.extend(snippets);
13133 Ok(completions)
13134 })
13135 })
13136 }
13137
13138 fn resolve_completions(
13139 &self,
13140 buffer: Model<Buffer>,
13141 completion_indices: Vec<usize>,
13142 completions: Arc<RwLock<Box<[Completion]>>>,
13143 cx: &mut ViewContext<Editor>,
13144 ) -> Task<Result<bool>> {
13145 self.update(cx, |project, cx| {
13146 project.resolve_completions(buffer, completion_indices, completions, cx)
13147 })
13148 }
13149
13150 fn apply_additional_edits_for_completion(
13151 &self,
13152 buffer: Model<Buffer>,
13153 completion: Completion,
13154 push_to_history: bool,
13155 cx: &mut ViewContext<Editor>,
13156 ) -> Task<Result<Option<language::Transaction>>> {
13157 self.update(cx, |project, cx| {
13158 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13159 })
13160 }
13161
13162 fn is_completion_trigger(
13163 &self,
13164 buffer: &Model<Buffer>,
13165 position: language::Anchor,
13166 text: &str,
13167 trigger_in_words: bool,
13168 cx: &mut ViewContext<Editor>,
13169 ) -> bool {
13170 if !EditorSettings::get_global(cx).show_completions_on_input {
13171 return false;
13172 }
13173
13174 let mut chars = text.chars();
13175 let char = if let Some(char) = chars.next() {
13176 char
13177 } else {
13178 return false;
13179 };
13180 if chars.next().is_some() {
13181 return false;
13182 }
13183
13184 let buffer = buffer.read(cx);
13185 let classifier = buffer
13186 .snapshot()
13187 .char_classifier_at(position)
13188 .for_completion(true);
13189 if trigger_in_words && classifier.is_word(char) {
13190 return true;
13191 }
13192
13193 buffer
13194 .completion_triggers()
13195 .iter()
13196 .any(|string| string == text)
13197 }
13198}
13199
13200fn inlay_hint_settings(
13201 location: Anchor,
13202 snapshot: &MultiBufferSnapshot,
13203 cx: &mut ViewContext<'_, Editor>,
13204) -> InlayHintSettings {
13205 let file = snapshot.file_at(location);
13206 let language = snapshot.language_at(location);
13207 let settings = all_language_settings(file, cx);
13208 settings
13209 .language(language.map(|l| l.name()).as_ref())
13210 .inlay_hints
13211}
13212
13213fn consume_contiguous_rows(
13214 contiguous_row_selections: &mut Vec<Selection<Point>>,
13215 selection: &Selection<Point>,
13216 display_map: &DisplaySnapshot,
13217 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13218) -> (MultiBufferRow, MultiBufferRow) {
13219 contiguous_row_selections.push(selection.clone());
13220 let start_row = MultiBufferRow(selection.start.row);
13221 let mut end_row = ending_row(selection, display_map);
13222
13223 while let Some(next_selection) = selections.peek() {
13224 if next_selection.start.row <= end_row.0 {
13225 end_row = ending_row(next_selection, display_map);
13226 contiguous_row_selections.push(selections.next().unwrap().clone());
13227 } else {
13228 break;
13229 }
13230 }
13231 (start_row, end_row)
13232}
13233
13234fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13235 if next_selection.end.column > 0 || next_selection.is_empty() {
13236 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13237 } else {
13238 MultiBufferRow(next_selection.end.row)
13239 }
13240}
13241
13242impl EditorSnapshot {
13243 pub fn remote_selections_in_range<'a>(
13244 &'a self,
13245 range: &'a Range<Anchor>,
13246 collaboration_hub: &dyn CollaborationHub,
13247 cx: &'a AppContext,
13248 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13249 let participant_names = collaboration_hub.user_names(cx);
13250 let participant_indices = collaboration_hub.user_participant_indices(cx);
13251 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13252 let collaborators_by_replica_id = collaborators_by_peer_id
13253 .iter()
13254 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13255 .collect::<HashMap<_, _>>();
13256 self.buffer_snapshot
13257 .selections_in_range(range, false)
13258 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13259 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13260 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13261 let user_name = participant_names.get(&collaborator.user_id).cloned();
13262 Some(RemoteSelection {
13263 replica_id,
13264 selection,
13265 cursor_shape,
13266 line_mode,
13267 participant_index,
13268 peer_id: collaborator.peer_id,
13269 user_name,
13270 })
13271 })
13272 }
13273
13274 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13275 self.display_snapshot.buffer_snapshot.language_at(position)
13276 }
13277
13278 pub fn is_focused(&self) -> bool {
13279 self.is_focused
13280 }
13281
13282 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13283 self.placeholder_text.as_ref()
13284 }
13285
13286 pub fn scroll_position(&self) -> gpui::Point<f32> {
13287 self.scroll_anchor.scroll_position(&self.display_snapshot)
13288 }
13289
13290 fn gutter_dimensions(
13291 &self,
13292 font_id: FontId,
13293 font_size: Pixels,
13294 em_width: Pixels,
13295 em_advance: Pixels,
13296 max_line_number_width: Pixels,
13297 cx: &AppContext,
13298 ) -> GutterDimensions {
13299 if !self.show_gutter {
13300 return GutterDimensions::default();
13301 }
13302 let descent = cx.text_system().descent(font_id, font_size);
13303
13304 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13305 matches!(
13306 ProjectSettings::get_global(cx).git.git_gutter,
13307 Some(GitGutterSetting::TrackedFiles)
13308 )
13309 });
13310 let gutter_settings = EditorSettings::get_global(cx).gutter;
13311 let show_line_numbers = self
13312 .show_line_numbers
13313 .unwrap_or(gutter_settings.line_numbers);
13314 let line_gutter_width = if show_line_numbers {
13315 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13316 let min_width_for_number_on_gutter = em_advance * 4.0;
13317 max_line_number_width.max(min_width_for_number_on_gutter)
13318 } else {
13319 0.0.into()
13320 };
13321
13322 let show_code_actions = self
13323 .show_code_actions
13324 .unwrap_or(gutter_settings.code_actions);
13325
13326 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13327
13328 let git_blame_entries_width =
13329 self.git_blame_gutter_max_author_length
13330 .map(|max_author_length| {
13331 // Length of the author name, but also space for the commit hash,
13332 // the spacing and the timestamp.
13333 let max_char_count = max_author_length
13334 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13335 + 7 // length of commit sha
13336 + 14 // length of max relative timestamp ("60 minutes ago")
13337 + 4; // gaps and margins
13338
13339 em_advance * max_char_count
13340 });
13341
13342 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13343 left_padding += if show_code_actions || show_runnables {
13344 em_width * 3.0
13345 } else if show_git_gutter && show_line_numbers {
13346 em_width * 2.0
13347 } else if show_git_gutter || show_line_numbers {
13348 em_width
13349 } else {
13350 px(0.)
13351 };
13352
13353 let right_padding = if gutter_settings.folds && show_line_numbers {
13354 em_width * 4.0
13355 } else if gutter_settings.folds {
13356 em_width * 3.0
13357 } else if show_line_numbers {
13358 em_width
13359 } else {
13360 px(0.)
13361 };
13362
13363 GutterDimensions {
13364 left_padding,
13365 right_padding,
13366 width: line_gutter_width + left_padding + right_padding,
13367 margin: -descent,
13368 git_blame_entries_width,
13369 }
13370 }
13371
13372 pub fn render_fold_toggle(
13373 &self,
13374 buffer_row: MultiBufferRow,
13375 row_contains_cursor: bool,
13376 editor: View<Editor>,
13377 cx: &mut WindowContext,
13378 ) -> Option<AnyElement> {
13379 let folded = self.is_line_folded(buffer_row);
13380
13381 if let Some(crease) = self
13382 .crease_snapshot
13383 .query_row(buffer_row, &self.buffer_snapshot)
13384 {
13385 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13386 if folded {
13387 editor.update(cx, |editor, cx| {
13388 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13389 });
13390 } else {
13391 editor.update(cx, |editor, cx| {
13392 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13393 });
13394 }
13395 });
13396
13397 Some((crease.render_toggle)(
13398 buffer_row,
13399 folded,
13400 toggle_callback,
13401 cx,
13402 ))
13403 } else if folded
13404 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13405 {
13406 Some(
13407 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13408 .selected(folded)
13409 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13410 if folded {
13411 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13412 } else {
13413 this.fold_at(&FoldAt { buffer_row }, cx);
13414 }
13415 }))
13416 .into_any_element(),
13417 )
13418 } else {
13419 None
13420 }
13421 }
13422
13423 pub fn render_crease_trailer(
13424 &self,
13425 buffer_row: MultiBufferRow,
13426 cx: &mut WindowContext,
13427 ) -> Option<AnyElement> {
13428 let folded = self.is_line_folded(buffer_row);
13429 let crease = self
13430 .crease_snapshot
13431 .query_row(buffer_row, &self.buffer_snapshot)?;
13432 Some((crease.render_trailer)(buffer_row, folded, cx))
13433 }
13434}
13435
13436impl Deref for EditorSnapshot {
13437 type Target = DisplaySnapshot;
13438
13439 fn deref(&self) -> &Self::Target {
13440 &self.display_snapshot
13441 }
13442}
13443
13444#[derive(Clone, Debug, PartialEq, Eq)]
13445pub enum EditorEvent {
13446 InputIgnored {
13447 text: Arc<str>,
13448 },
13449 InputHandled {
13450 utf16_range_to_replace: Option<Range<isize>>,
13451 text: Arc<str>,
13452 },
13453 ExcerptsAdded {
13454 buffer: Model<Buffer>,
13455 predecessor: ExcerptId,
13456 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13457 },
13458 ExcerptsRemoved {
13459 ids: Vec<ExcerptId>,
13460 },
13461 ExcerptsEdited {
13462 ids: Vec<ExcerptId>,
13463 },
13464 ExcerptsExpanded {
13465 ids: Vec<ExcerptId>,
13466 },
13467 BufferEdited,
13468 Edited {
13469 transaction_id: clock::Lamport,
13470 },
13471 Reparsed(BufferId),
13472 Focused,
13473 FocusedIn,
13474 Blurred,
13475 DirtyChanged,
13476 Saved,
13477 TitleChanged,
13478 DiffBaseChanged,
13479 SelectionsChanged {
13480 local: bool,
13481 },
13482 ScrollPositionChanged {
13483 local: bool,
13484 autoscroll: bool,
13485 },
13486 Closed,
13487 TransactionUndone {
13488 transaction_id: clock::Lamport,
13489 },
13490 TransactionBegun {
13491 transaction_id: clock::Lamport,
13492 },
13493 CursorShapeChanged,
13494}
13495
13496impl EventEmitter<EditorEvent> for Editor {}
13497
13498impl FocusableView for Editor {
13499 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13500 self.focus_handle.clone()
13501 }
13502}
13503
13504impl Render for Editor {
13505 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13506 let settings = ThemeSettings::get_global(cx);
13507
13508 let text_style = match self.mode {
13509 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13510 color: cx.theme().colors().editor_foreground,
13511 font_family: settings.ui_font.family.clone(),
13512 font_features: settings.ui_font.features.clone(),
13513 font_fallbacks: settings.ui_font.fallbacks.clone(),
13514 font_size: rems(0.875).into(),
13515 font_weight: settings.ui_font.weight,
13516 line_height: relative(settings.buffer_line_height.value()),
13517 ..Default::default()
13518 },
13519 EditorMode::Full => TextStyle {
13520 color: cx.theme().colors().editor_foreground,
13521 font_family: settings.buffer_font.family.clone(),
13522 font_features: settings.buffer_font.features.clone(),
13523 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13524 font_size: settings.buffer_font_size(cx).into(),
13525 font_weight: settings.buffer_font.weight,
13526 line_height: relative(settings.buffer_line_height.value()),
13527 ..Default::default()
13528 },
13529 };
13530
13531 let background = match self.mode {
13532 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13533 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13534 EditorMode::Full => cx.theme().colors().editor_background,
13535 };
13536
13537 EditorElement::new(
13538 cx.view(),
13539 EditorStyle {
13540 background,
13541 local_player: cx.theme().players().local(),
13542 text: text_style,
13543 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13544 syntax: cx.theme().syntax().clone(),
13545 status: cx.theme().status().clone(),
13546 inlay_hints_style: make_inlay_hints_style(cx),
13547 suggestions_style: HighlightStyle {
13548 color: Some(cx.theme().status().predictive),
13549 ..HighlightStyle::default()
13550 },
13551 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13552 },
13553 )
13554 }
13555}
13556
13557impl ViewInputHandler for Editor {
13558 fn text_for_range(
13559 &mut self,
13560 range_utf16: Range<usize>,
13561 cx: &mut ViewContext<Self>,
13562 ) -> Option<String> {
13563 Some(
13564 self.buffer
13565 .read(cx)
13566 .read(cx)
13567 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13568 .collect(),
13569 )
13570 }
13571
13572 fn selected_text_range(
13573 &mut self,
13574 ignore_disabled_input: bool,
13575 cx: &mut ViewContext<Self>,
13576 ) -> Option<UTF16Selection> {
13577 // Prevent the IME menu from appearing when holding down an alphabetic key
13578 // while input is disabled.
13579 if !ignore_disabled_input && !self.input_enabled {
13580 return None;
13581 }
13582
13583 let selection = self.selections.newest::<OffsetUtf16>(cx);
13584 let range = selection.range();
13585
13586 Some(UTF16Selection {
13587 range: range.start.0..range.end.0,
13588 reversed: selection.reversed,
13589 })
13590 }
13591
13592 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13593 let snapshot = self.buffer.read(cx).read(cx);
13594 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13595 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13596 }
13597
13598 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13599 self.clear_highlights::<InputComposition>(cx);
13600 self.ime_transaction.take();
13601 }
13602
13603 fn replace_text_in_range(
13604 &mut self,
13605 range_utf16: Option<Range<usize>>,
13606 text: &str,
13607 cx: &mut ViewContext<Self>,
13608 ) {
13609 if !self.input_enabled {
13610 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13611 return;
13612 }
13613
13614 self.transact(cx, |this, cx| {
13615 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13616 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13617 Some(this.selection_replacement_ranges(range_utf16, cx))
13618 } else {
13619 this.marked_text_ranges(cx)
13620 };
13621
13622 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13623 let newest_selection_id = this.selections.newest_anchor().id;
13624 this.selections
13625 .all::<OffsetUtf16>(cx)
13626 .iter()
13627 .zip(ranges_to_replace.iter())
13628 .find_map(|(selection, range)| {
13629 if selection.id == newest_selection_id {
13630 Some(
13631 (range.start.0 as isize - selection.head().0 as isize)
13632 ..(range.end.0 as isize - selection.head().0 as isize),
13633 )
13634 } else {
13635 None
13636 }
13637 })
13638 });
13639
13640 cx.emit(EditorEvent::InputHandled {
13641 utf16_range_to_replace: range_to_replace,
13642 text: text.into(),
13643 });
13644
13645 if let Some(new_selected_ranges) = new_selected_ranges {
13646 this.change_selections(None, cx, |selections| {
13647 selections.select_ranges(new_selected_ranges)
13648 });
13649 this.backspace(&Default::default(), cx);
13650 }
13651
13652 this.handle_input(text, cx);
13653 });
13654
13655 if let Some(transaction) = self.ime_transaction {
13656 self.buffer.update(cx, |buffer, cx| {
13657 buffer.group_until_transaction(transaction, cx);
13658 });
13659 }
13660
13661 self.unmark_text(cx);
13662 }
13663
13664 fn replace_and_mark_text_in_range(
13665 &mut self,
13666 range_utf16: Option<Range<usize>>,
13667 text: &str,
13668 new_selected_range_utf16: Option<Range<usize>>,
13669 cx: &mut ViewContext<Self>,
13670 ) {
13671 if !self.input_enabled {
13672 return;
13673 }
13674
13675 let transaction = self.transact(cx, |this, cx| {
13676 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13677 let snapshot = this.buffer.read(cx).read(cx);
13678 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13679 for marked_range in &mut marked_ranges {
13680 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13681 marked_range.start.0 += relative_range_utf16.start;
13682 marked_range.start =
13683 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13684 marked_range.end =
13685 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13686 }
13687 }
13688 Some(marked_ranges)
13689 } else if let Some(range_utf16) = range_utf16 {
13690 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13691 Some(this.selection_replacement_ranges(range_utf16, cx))
13692 } else {
13693 None
13694 };
13695
13696 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13697 let newest_selection_id = this.selections.newest_anchor().id;
13698 this.selections
13699 .all::<OffsetUtf16>(cx)
13700 .iter()
13701 .zip(ranges_to_replace.iter())
13702 .find_map(|(selection, range)| {
13703 if selection.id == newest_selection_id {
13704 Some(
13705 (range.start.0 as isize - selection.head().0 as isize)
13706 ..(range.end.0 as isize - selection.head().0 as isize),
13707 )
13708 } else {
13709 None
13710 }
13711 })
13712 });
13713
13714 cx.emit(EditorEvent::InputHandled {
13715 utf16_range_to_replace: range_to_replace,
13716 text: text.into(),
13717 });
13718
13719 if let Some(ranges) = ranges_to_replace {
13720 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13721 }
13722
13723 let marked_ranges = {
13724 let snapshot = this.buffer.read(cx).read(cx);
13725 this.selections
13726 .disjoint_anchors()
13727 .iter()
13728 .map(|selection| {
13729 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13730 })
13731 .collect::<Vec<_>>()
13732 };
13733
13734 if text.is_empty() {
13735 this.unmark_text(cx);
13736 } else {
13737 this.highlight_text::<InputComposition>(
13738 marked_ranges.clone(),
13739 HighlightStyle {
13740 underline: Some(UnderlineStyle {
13741 thickness: px(1.),
13742 color: None,
13743 wavy: false,
13744 }),
13745 ..Default::default()
13746 },
13747 cx,
13748 );
13749 }
13750
13751 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13752 let use_autoclose = this.use_autoclose;
13753 let use_auto_surround = this.use_auto_surround;
13754 this.set_use_autoclose(false);
13755 this.set_use_auto_surround(false);
13756 this.handle_input(text, cx);
13757 this.set_use_autoclose(use_autoclose);
13758 this.set_use_auto_surround(use_auto_surround);
13759
13760 if let Some(new_selected_range) = new_selected_range_utf16 {
13761 let snapshot = this.buffer.read(cx).read(cx);
13762 let new_selected_ranges = marked_ranges
13763 .into_iter()
13764 .map(|marked_range| {
13765 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13766 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13767 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13768 snapshot.clip_offset_utf16(new_start, Bias::Left)
13769 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13770 })
13771 .collect::<Vec<_>>();
13772
13773 drop(snapshot);
13774 this.change_selections(None, cx, |selections| {
13775 selections.select_ranges(new_selected_ranges)
13776 });
13777 }
13778 });
13779
13780 self.ime_transaction = self.ime_transaction.or(transaction);
13781 if let Some(transaction) = self.ime_transaction {
13782 self.buffer.update(cx, |buffer, cx| {
13783 buffer.group_until_transaction(transaction, cx);
13784 });
13785 }
13786
13787 if self.text_highlights::<InputComposition>(cx).is_none() {
13788 self.ime_transaction.take();
13789 }
13790 }
13791
13792 fn bounds_for_range(
13793 &mut self,
13794 range_utf16: Range<usize>,
13795 element_bounds: gpui::Bounds<Pixels>,
13796 cx: &mut ViewContext<Self>,
13797 ) -> Option<gpui::Bounds<Pixels>> {
13798 let text_layout_details = self.text_layout_details(cx);
13799 let style = &text_layout_details.editor_style;
13800 let font_id = cx.text_system().resolve_font(&style.text.font());
13801 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13802 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13803
13804 let em_width = cx
13805 .text_system()
13806 .typographic_bounds(font_id, font_size, 'm')
13807 .unwrap()
13808 .size
13809 .width;
13810
13811 let snapshot = self.snapshot(cx);
13812 let scroll_position = snapshot.scroll_position();
13813 let scroll_left = scroll_position.x * em_width;
13814
13815 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13816 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13817 + self.gutter_dimensions.width;
13818 let y = line_height * (start.row().as_f32() - scroll_position.y);
13819
13820 Some(Bounds {
13821 origin: element_bounds.origin + point(x, y),
13822 size: size(em_width, line_height),
13823 })
13824 }
13825}
13826
13827trait SelectionExt {
13828 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13829 fn spanned_rows(
13830 &self,
13831 include_end_if_at_line_start: bool,
13832 map: &DisplaySnapshot,
13833 ) -> Range<MultiBufferRow>;
13834}
13835
13836impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13837 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13838 let start = self
13839 .start
13840 .to_point(&map.buffer_snapshot)
13841 .to_display_point(map);
13842 let end = self
13843 .end
13844 .to_point(&map.buffer_snapshot)
13845 .to_display_point(map);
13846 if self.reversed {
13847 end..start
13848 } else {
13849 start..end
13850 }
13851 }
13852
13853 fn spanned_rows(
13854 &self,
13855 include_end_if_at_line_start: bool,
13856 map: &DisplaySnapshot,
13857 ) -> Range<MultiBufferRow> {
13858 let start = self.start.to_point(&map.buffer_snapshot);
13859 let mut end = self.end.to_point(&map.buffer_snapshot);
13860 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13861 end.row -= 1;
13862 }
13863
13864 let buffer_start = map.prev_line_boundary(start).0;
13865 let buffer_end = map.next_line_boundary(end).0;
13866 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13867 }
13868}
13869
13870impl<T: InvalidationRegion> InvalidationStack<T> {
13871 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13872 where
13873 S: Clone + ToOffset,
13874 {
13875 while let Some(region) = self.last() {
13876 let all_selections_inside_invalidation_ranges =
13877 if selections.len() == region.ranges().len() {
13878 selections
13879 .iter()
13880 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13881 .all(|(selection, invalidation_range)| {
13882 let head = selection.head().to_offset(buffer);
13883 invalidation_range.start <= head && invalidation_range.end >= head
13884 })
13885 } else {
13886 false
13887 };
13888
13889 if all_selections_inside_invalidation_ranges {
13890 break;
13891 } else {
13892 self.pop();
13893 }
13894 }
13895 }
13896}
13897
13898impl<T> Default for InvalidationStack<T> {
13899 fn default() -> Self {
13900 Self(Default::default())
13901 }
13902}
13903
13904impl<T> Deref for InvalidationStack<T> {
13905 type Target = Vec<T>;
13906
13907 fn deref(&self) -> &Self::Target {
13908 &self.0
13909 }
13910}
13911
13912impl<T> DerefMut for InvalidationStack<T> {
13913 fn deref_mut(&mut self) -> &mut Self::Target {
13914 &mut self.0
13915 }
13916}
13917
13918impl InvalidationRegion for SnippetState {
13919 fn ranges(&self) -> &[Range<Anchor>] {
13920 &self.ranges[self.active_index]
13921 }
13922}
13923
13924pub fn diagnostic_block_renderer(
13925 diagnostic: Diagnostic,
13926 max_message_rows: Option<u8>,
13927 allow_closing: bool,
13928 _is_valid: bool,
13929) -> RenderBlock {
13930 let (text_without_backticks, code_ranges) =
13931 highlight_diagnostic_message(&diagnostic, max_message_rows);
13932
13933 Box::new(move |cx: &mut BlockContext| {
13934 let group_id: SharedString = cx.block_id.to_string().into();
13935
13936 let mut text_style = cx.text_style().clone();
13937 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13938 let theme_settings = ThemeSettings::get_global(cx);
13939 text_style.font_family = theme_settings.buffer_font.family.clone();
13940 text_style.font_style = theme_settings.buffer_font.style;
13941 text_style.font_features = theme_settings.buffer_font.features.clone();
13942 text_style.font_weight = theme_settings.buffer_font.weight;
13943
13944 let multi_line_diagnostic = diagnostic.message.contains('\n');
13945
13946 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13947 if multi_line_diagnostic {
13948 v_flex()
13949 } else {
13950 h_flex()
13951 }
13952 .when(allow_closing, |div| {
13953 div.children(diagnostic.is_primary.then(|| {
13954 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13955 .icon_color(Color::Muted)
13956 .size(ButtonSize::Compact)
13957 .style(ButtonStyle::Transparent)
13958 .visible_on_hover(group_id.clone())
13959 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13960 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13961 }))
13962 })
13963 .child(
13964 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13965 .icon_color(Color::Muted)
13966 .size(ButtonSize::Compact)
13967 .style(ButtonStyle::Transparent)
13968 .visible_on_hover(group_id.clone())
13969 .on_click({
13970 let message = diagnostic.message.clone();
13971 move |_click, cx| {
13972 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13973 }
13974 })
13975 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13976 )
13977 };
13978
13979 let icon_size = buttons(&diagnostic, cx.block_id)
13980 .into_any_element()
13981 .layout_as_root(AvailableSpace::min_size(), cx);
13982
13983 h_flex()
13984 .id(cx.block_id)
13985 .group(group_id.clone())
13986 .relative()
13987 .size_full()
13988 .pl(cx.gutter_dimensions.width)
13989 .w(cx.max_width + cx.gutter_dimensions.width)
13990 .child(
13991 div()
13992 .flex()
13993 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13994 .flex_shrink(),
13995 )
13996 .child(buttons(&diagnostic, cx.block_id))
13997 .child(div().flex().flex_shrink_0().child(
13998 StyledText::new(text_without_backticks.clone()).with_highlights(
13999 &text_style,
14000 code_ranges.iter().map(|range| {
14001 (
14002 range.clone(),
14003 HighlightStyle {
14004 font_weight: Some(FontWeight::BOLD),
14005 ..Default::default()
14006 },
14007 )
14008 }),
14009 ),
14010 ))
14011 .into_any_element()
14012 })
14013}
14014
14015pub fn highlight_diagnostic_message(
14016 diagnostic: &Diagnostic,
14017 mut max_message_rows: Option<u8>,
14018) -> (SharedString, Vec<Range<usize>>) {
14019 let mut text_without_backticks = String::new();
14020 let mut code_ranges = Vec::new();
14021
14022 if let Some(source) = &diagnostic.source {
14023 text_without_backticks.push_str(source);
14024 code_ranges.push(0..source.len());
14025 text_without_backticks.push_str(": ");
14026 }
14027
14028 let mut prev_offset = 0;
14029 let mut in_code_block = false;
14030 let has_row_limit = max_message_rows.is_some();
14031 let mut newline_indices = diagnostic
14032 .message
14033 .match_indices('\n')
14034 .filter(|_| has_row_limit)
14035 .map(|(ix, _)| ix)
14036 .fuse()
14037 .peekable();
14038
14039 for (quote_ix, _) in diagnostic
14040 .message
14041 .match_indices('`')
14042 .chain([(diagnostic.message.len(), "")])
14043 {
14044 let mut first_newline_ix = None;
14045 let mut last_newline_ix = None;
14046 while let Some(newline_ix) = newline_indices.peek() {
14047 if *newline_ix < quote_ix {
14048 if first_newline_ix.is_none() {
14049 first_newline_ix = Some(*newline_ix);
14050 }
14051 last_newline_ix = Some(*newline_ix);
14052
14053 if let Some(rows_left) = &mut max_message_rows {
14054 if *rows_left == 0 {
14055 break;
14056 } else {
14057 *rows_left -= 1;
14058 }
14059 }
14060 let _ = newline_indices.next();
14061 } else {
14062 break;
14063 }
14064 }
14065 let prev_len = text_without_backticks.len();
14066 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14067 text_without_backticks.push_str(new_text);
14068 if in_code_block {
14069 code_ranges.push(prev_len..text_without_backticks.len());
14070 }
14071 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14072 in_code_block = !in_code_block;
14073 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14074 text_without_backticks.push_str("...");
14075 break;
14076 }
14077 }
14078
14079 (text_without_backticks.into(), code_ranges)
14080}
14081
14082fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14083 match severity {
14084 DiagnosticSeverity::ERROR => colors.error,
14085 DiagnosticSeverity::WARNING => colors.warning,
14086 DiagnosticSeverity::INFORMATION => colors.info,
14087 DiagnosticSeverity::HINT => colors.info,
14088 _ => colors.ignored,
14089 }
14090}
14091
14092pub fn styled_runs_for_code_label<'a>(
14093 label: &'a CodeLabel,
14094 syntax_theme: &'a theme::SyntaxTheme,
14095) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14096 let fade_out = HighlightStyle {
14097 fade_out: Some(0.35),
14098 ..Default::default()
14099 };
14100
14101 let mut prev_end = label.filter_range.end;
14102 label
14103 .runs
14104 .iter()
14105 .enumerate()
14106 .flat_map(move |(ix, (range, highlight_id))| {
14107 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14108 style
14109 } else {
14110 return Default::default();
14111 };
14112 let mut muted_style = style;
14113 muted_style.highlight(fade_out);
14114
14115 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14116 if range.start >= label.filter_range.end {
14117 if range.start > prev_end {
14118 runs.push((prev_end..range.start, fade_out));
14119 }
14120 runs.push((range.clone(), muted_style));
14121 } else if range.end <= label.filter_range.end {
14122 runs.push((range.clone(), style));
14123 } else {
14124 runs.push((range.start..label.filter_range.end, style));
14125 runs.push((label.filter_range.end..range.end, muted_style));
14126 }
14127 prev_end = cmp::max(prev_end, range.end);
14128
14129 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14130 runs.push((prev_end..label.text.len(), fade_out));
14131 }
14132
14133 runs
14134 })
14135}
14136
14137pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14138 let mut prev_index = 0;
14139 let mut prev_codepoint: Option<char> = None;
14140 text.char_indices()
14141 .chain([(text.len(), '\0')])
14142 .filter_map(move |(index, codepoint)| {
14143 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14144 let is_boundary = index == text.len()
14145 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14146 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14147 if is_boundary {
14148 let chunk = &text[prev_index..index];
14149 prev_index = index;
14150 Some(chunk)
14151 } else {
14152 None
14153 }
14154 })
14155}
14156
14157pub trait RangeToAnchorExt: Sized {
14158 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14159
14160 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14161 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14162 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14163 }
14164}
14165
14166impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14167 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14168 let start_offset = self.start.to_offset(snapshot);
14169 let end_offset = self.end.to_offset(snapshot);
14170 if start_offset == end_offset {
14171 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14172 } else {
14173 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14174 }
14175 }
14176}
14177
14178pub trait RowExt {
14179 fn as_f32(&self) -> f32;
14180
14181 fn next_row(&self) -> Self;
14182
14183 fn previous_row(&self) -> Self;
14184
14185 fn minus(&self, other: Self) -> u32;
14186}
14187
14188impl RowExt for DisplayRow {
14189 fn as_f32(&self) -> f32 {
14190 self.0 as f32
14191 }
14192
14193 fn next_row(&self) -> Self {
14194 Self(self.0 + 1)
14195 }
14196
14197 fn previous_row(&self) -> Self {
14198 Self(self.0.saturating_sub(1))
14199 }
14200
14201 fn minus(&self, other: Self) -> u32 {
14202 self.0 - other.0
14203 }
14204}
14205
14206impl RowExt for MultiBufferRow {
14207 fn as_f32(&self) -> f32 {
14208 self.0 as f32
14209 }
14210
14211 fn next_row(&self) -> Self {
14212 Self(self.0 + 1)
14213 }
14214
14215 fn previous_row(&self) -> Self {
14216 Self(self.0.saturating_sub(1))
14217 }
14218
14219 fn minus(&self, other: Self) -> u32 {
14220 self.0 - other.0
14221 }
14222}
14223
14224trait RowRangeExt {
14225 type Row;
14226
14227 fn len(&self) -> usize;
14228
14229 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14230}
14231
14232impl RowRangeExt for Range<MultiBufferRow> {
14233 type Row = MultiBufferRow;
14234
14235 fn len(&self) -> usize {
14236 (self.end.0 - self.start.0) as usize
14237 }
14238
14239 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14240 (self.start.0..self.end.0).map(MultiBufferRow)
14241 }
14242}
14243
14244impl RowRangeExt for Range<DisplayRow> {
14245 type Row = DisplayRow;
14246
14247 fn len(&self) -> usize {
14248 (self.end.0 - self.start.0) as usize
14249 }
14250
14251 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14252 (self.start.0..self.end.0).map(DisplayRow)
14253 }
14254}
14255
14256fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14257 if hunk.diff_base_byte_range.is_empty() {
14258 DiffHunkStatus::Added
14259 } else if hunk.row_range.is_empty() {
14260 DiffHunkStatus::Removed
14261 } else {
14262 DiffHunkStatus::Modified
14263 }
14264}
14265
14266/// If select range has more than one line, we
14267/// just point the cursor to range.start.
14268fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14269 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14270 range
14271 } else {
14272 range.start..range.start
14273 }
14274}