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 let task_inventory = project.read(cx).task_inventory().clone();
1883 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1884 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1885 }));
1886 }
1887 }
1888
1889 let inlay_hint_settings = inlay_hint_settings(
1890 selections.newest_anchor().head(),
1891 &buffer.read(cx).snapshot(cx),
1892 cx,
1893 );
1894 let focus_handle = cx.focus_handle();
1895 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1896 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1897 .detach();
1898 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1899 .detach();
1900 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1901
1902 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1903 Some(false)
1904 } else {
1905 None
1906 };
1907
1908 let mut code_action_providers = Vec::new();
1909 if let Some(project) = project.clone() {
1910 code_action_providers.push(Arc::new(project) as Arc<_>);
1911 }
1912
1913 let mut this = Self {
1914 focus_handle,
1915 show_cursor_when_unfocused: false,
1916 last_focused_descendant: None,
1917 buffer: buffer.clone(),
1918 display_map: display_map.clone(),
1919 selections,
1920 scroll_manager: ScrollManager::new(cx),
1921 columnar_selection_tail: None,
1922 add_selections_state: None,
1923 select_next_state: None,
1924 select_prev_state: None,
1925 selection_history: Default::default(),
1926 autoclose_regions: Default::default(),
1927 snippet_stack: Default::default(),
1928 select_larger_syntax_node_stack: Vec::new(),
1929 ime_transaction: Default::default(),
1930 active_diagnostics: None,
1931 soft_wrap_mode_override,
1932 completion_provider: project.clone().map(|project| Box::new(project) as _),
1933 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1934 project,
1935 blink_manager: blink_manager.clone(),
1936 show_local_selections: true,
1937 mode,
1938 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1939 show_gutter: mode == EditorMode::Full,
1940 show_line_numbers: None,
1941 use_relative_line_numbers: None,
1942 show_git_diff_gutter: None,
1943 show_code_actions: None,
1944 show_runnables: None,
1945 show_wrap_guides: None,
1946 show_indent_guides,
1947 placeholder_text: None,
1948 highlight_order: 0,
1949 highlighted_rows: HashMap::default(),
1950 background_highlights: Default::default(),
1951 gutter_highlights: TreeMap::default(),
1952 scrollbar_marker_state: ScrollbarMarkerState::default(),
1953 active_indent_guides_state: ActiveIndentGuidesState::default(),
1954 nav_history: None,
1955 context_menu: RwLock::new(None),
1956 mouse_context_menu: None,
1957 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1958 completion_tasks: Default::default(),
1959 signature_help_state: SignatureHelpState::default(),
1960 auto_signature_help: None,
1961 find_all_references_task_sources: Vec::new(),
1962 next_completion_id: 0,
1963 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1964 next_inlay_id: 0,
1965 code_action_providers,
1966 available_code_actions: Default::default(),
1967 code_actions_task: Default::default(),
1968 document_highlights_task: Default::default(),
1969 linked_editing_range_task: Default::default(),
1970 pending_rename: Default::default(),
1971 searchable: true,
1972 cursor_shape: EditorSettings::get_global(cx)
1973 .cursor_shape
1974 .unwrap_or_default(),
1975 current_line_highlight: None,
1976 autoindent_mode: Some(AutoindentMode::EachLine),
1977 collapse_matches: false,
1978 workspace: None,
1979 input_enabled: true,
1980 use_modal_editing: mode == EditorMode::Full,
1981 read_only: false,
1982 use_autoclose: true,
1983 use_auto_surround: true,
1984 auto_replace_emoji_shortcode: false,
1985 leader_peer_id: None,
1986 remote_id: None,
1987 hover_state: Default::default(),
1988 hovered_link_state: Default::default(),
1989 inline_completion_provider: None,
1990 active_inline_completion: None,
1991 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1992 expanded_hunks: ExpandedHunks::default(),
1993 gutter_hovered: false,
1994 pixel_position_of_newest_cursor: None,
1995 last_bounds: None,
1996 expect_bounds_change: None,
1997 gutter_dimensions: GutterDimensions::default(),
1998 style: None,
1999 show_cursor_names: false,
2000 hovered_cursors: Default::default(),
2001 next_editor_action_id: EditorActionId::default(),
2002 editor_actions: Rc::default(),
2003 show_inline_completions_override: None,
2004 enable_inline_completions: true,
2005 custom_context_menu: None,
2006 show_git_blame_gutter: false,
2007 show_git_blame_inline: false,
2008 show_selection_menu: None,
2009 show_git_blame_inline_delay_task: None,
2010 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2011 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2012 .session
2013 .restore_unsaved_buffers,
2014 blame: None,
2015 blame_subscription: None,
2016 file_header_size,
2017 tasks: Default::default(),
2018 _subscriptions: vec![
2019 cx.observe(&buffer, Self::on_buffer_changed),
2020 cx.subscribe(&buffer, Self::on_buffer_event),
2021 cx.observe(&display_map, Self::on_display_map_changed),
2022 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2023 cx.observe_global::<SettingsStore>(Self::settings_changed),
2024 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2025 cx.observe_window_activation(|editor, cx| {
2026 let active = cx.is_window_active();
2027 editor.blink_manager.update(cx, |blink_manager, cx| {
2028 if active {
2029 blink_manager.enable(cx);
2030 } else {
2031 blink_manager.disable(cx);
2032 }
2033 });
2034 }),
2035 ],
2036 tasks_update_task: None,
2037 linked_edit_ranges: Default::default(),
2038 previous_search_ranges: None,
2039 breadcrumb_header: None,
2040 focused_block: None,
2041 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2042 addons: HashMap::default(),
2043 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2044 };
2045 this.tasks_update_task = Some(this.refresh_runnables(cx));
2046 this._subscriptions.extend(project_subscriptions);
2047
2048 this.end_selection(cx);
2049 this.scroll_manager.show_scrollbar(cx);
2050
2051 if mode == EditorMode::Full {
2052 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2053 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2054
2055 if this.git_blame_inline_enabled {
2056 this.git_blame_inline_enabled = true;
2057 this.start_git_blame_inline(false, cx);
2058 }
2059 }
2060
2061 this.report_editor_event("open", None, cx);
2062 this
2063 }
2064
2065 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2066 self.mouse_context_menu
2067 .as_ref()
2068 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2069 }
2070
2071 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2072 let mut key_context = KeyContext::new_with_defaults();
2073 key_context.add("Editor");
2074 let mode = match self.mode {
2075 EditorMode::SingleLine { .. } => "single_line",
2076 EditorMode::AutoHeight { .. } => "auto_height",
2077 EditorMode::Full => "full",
2078 };
2079
2080 if EditorSettings::jupyter_enabled(cx) {
2081 key_context.add("jupyter");
2082 }
2083
2084 key_context.set("mode", mode);
2085 if self.pending_rename.is_some() {
2086 key_context.add("renaming");
2087 }
2088 if self.context_menu_visible() {
2089 match self.context_menu.read().as_ref() {
2090 Some(ContextMenu::Completions(_)) => {
2091 key_context.add("menu");
2092 key_context.add("showing_completions")
2093 }
2094 Some(ContextMenu::CodeActions(_)) => {
2095 key_context.add("menu");
2096 key_context.add("showing_code_actions")
2097 }
2098 None => {}
2099 }
2100 }
2101
2102 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2103 if !self.focus_handle(cx).contains_focused(cx)
2104 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2105 {
2106 for addon in self.addons.values() {
2107 addon.extend_key_context(&mut key_context, cx)
2108 }
2109 }
2110
2111 if let Some(extension) = self
2112 .buffer
2113 .read(cx)
2114 .as_singleton()
2115 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2116 {
2117 key_context.set("extension", extension.to_string());
2118 }
2119
2120 if self.has_active_inline_completion(cx) {
2121 key_context.add("copilot_suggestion");
2122 key_context.add("inline_completion");
2123 }
2124
2125 key_context
2126 }
2127
2128 pub fn new_file(
2129 workspace: &mut Workspace,
2130 _: &workspace::NewFile,
2131 cx: &mut ViewContext<Workspace>,
2132 ) {
2133 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2134 "Failed to create buffer",
2135 cx,
2136 |e, _| match e.error_code() {
2137 ErrorCode::RemoteUpgradeRequired => Some(format!(
2138 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2139 e.error_tag("required").unwrap_or("the latest version")
2140 )),
2141 _ => None,
2142 },
2143 );
2144 }
2145
2146 pub fn new_in_workspace(
2147 workspace: &mut Workspace,
2148 cx: &mut ViewContext<Workspace>,
2149 ) -> Task<Result<View<Editor>>> {
2150 let project = workspace.project().clone();
2151 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2152
2153 cx.spawn(|workspace, mut cx| async move {
2154 let buffer = create.await?;
2155 workspace.update(&mut cx, |workspace, cx| {
2156 let editor =
2157 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2158 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2159 editor
2160 })
2161 })
2162 }
2163
2164 fn new_file_vertical(
2165 workspace: &mut Workspace,
2166 _: &workspace::NewFileSplitVertical,
2167 cx: &mut ViewContext<Workspace>,
2168 ) {
2169 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2170 }
2171
2172 fn new_file_horizontal(
2173 workspace: &mut Workspace,
2174 _: &workspace::NewFileSplitHorizontal,
2175 cx: &mut ViewContext<Workspace>,
2176 ) {
2177 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2178 }
2179
2180 fn new_file_in_direction(
2181 workspace: &mut Workspace,
2182 direction: SplitDirection,
2183 cx: &mut ViewContext<Workspace>,
2184 ) {
2185 let project = workspace.project().clone();
2186 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2187
2188 cx.spawn(|workspace, mut cx| async move {
2189 let buffer = create.await?;
2190 workspace.update(&mut cx, move |workspace, cx| {
2191 workspace.split_item(
2192 direction,
2193 Box::new(
2194 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2195 ),
2196 cx,
2197 )
2198 })?;
2199 anyhow::Ok(())
2200 })
2201 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2202 ErrorCode::RemoteUpgradeRequired => Some(format!(
2203 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2204 e.error_tag("required").unwrap_or("the latest version")
2205 )),
2206 _ => None,
2207 });
2208 }
2209
2210 pub fn leader_peer_id(&self) -> Option<PeerId> {
2211 self.leader_peer_id
2212 }
2213
2214 pub fn buffer(&self) -> &Model<MultiBuffer> {
2215 &self.buffer
2216 }
2217
2218 pub fn workspace(&self) -> Option<View<Workspace>> {
2219 self.workspace.as_ref()?.0.upgrade()
2220 }
2221
2222 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2223 self.buffer().read(cx).title(cx)
2224 }
2225
2226 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2227 let git_blame_gutter_max_author_length = self
2228 .render_git_blame_gutter(cx)
2229 .then(|| {
2230 if let Some(blame) = self.blame.as_ref() {
2231 let max_author_length =
2232 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2233 Some(max_author_length)
2234 } else {
2235 None
2236 }
2237 })
2238 .flatten();
2239
2240 EditorSnapshot {
2241 mode: self.mode,
2242 show_gutter: self.show_gutter,
2243 show_line_numbers: self.show_line_numbers,
2244 show_git_diff_gutter: self.show_git_diff_gutter,
2245 show_code_actions: self.show_code_actions,
2246 show_runnables: self.show_runnables,
2247 git_blame_gutter_max_author_length,
2248 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2249 scroll_anchor: self.scroll_manager.anchor(),
2250 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2251 placeholder_text: self.placeholder_text.clone(),
2252 is_focused: self.focus_handle.is_focused(cx),
2253 current_line_highlight: self
2254 .current_line_highlight
2255 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2256 gutter_hovered: self.gutter_hovered,
2257 }
2258 }
2259
2260 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2261 self.buffer.read(cx).language_at(point, cx)
2262 }
2263
2264 pub fn file_at<T: ToOffset>(
2265 &self,
2266 point: T,
2267 cx: &AppContext,
2268 ) -> Option<Arc<dyn language::File>> {
2269 self.buffer.read(cx).read(cx).file_at(point).cloned()
2270 }
2271
2272 pub fn active_excerpt(
2273 &self,
2274 cx: &AppContext,
2275 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2276 self.buffer
2277 .read(cx)
2278 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2279 }
2280
2281 pub fn mode(&self) -> EditorMode {
2282 self.mode
2283 }
2284
2285 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2286 self.collaboration_hub.as_deref()
2287 }
2288
2289 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2290 self.collaboration_hub = Some(hub);
2291 }
2292
2293 pub fn set_custom_context_menu(
2294 &mut self,
2295 f: impl 'static
2296 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2297 ) {
2298 self.custom_context_menu = Some(Box::new(f))
2299 }
2300
2301 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2302 self.completion_provider = Some(provider);
2303 }
2304
2305 pub fn set_inline_completion_provider<T>(
2306 &mut self,
2307 provider: Option<Model<T>>,
2308 cx: &mut ViewContext<Self>,
2309 ) where
2310 T: InlineCompletionProvider,
2311 {
2312 self.inline_completion_provider =
2313 provider.map(|provider| RegisteredInlineCompletionProvider {
2314 _subscription: cx.observe(&provider, |this, _, cx| {
2315 if this.focus_handle.is_focused(cx) {
2316 this.update_visible_inline_completion(cx);
2317 }
2318 }),
2319 provider: Arc::new(provider),
2320 });
2321 self.refresh_inline_completion(false, false, cx);
2322 }
2323
2324 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2325 self.placeholder_text.as_deref()
2326 }
2327
2328 pub fn set_placeholder_text(
2329 &mut self,
2330 placeholder_text: impl Into<Arc<str>>,
2331 cx: &mut ViewContext<Self>,
2332 ) {
2333 let placeholder_text = Some(placeholder_text.into());
2334 if self.placeholder_text != placeholder_text {
2335 self.placeholder_text = placeholder_text;
2336 cx.notify();
2337 }
2338 }
2339
2340 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2341 self.cursor_shape = cursor_shape;
2342
2343 // Disrupt blink for immediate user feedback that the cursor shape has changed
2344 self.blink_manager.update(cx, BlinkManager::show_cursor);
2345
2346 cx.notify();
2347 }
2348
2349 pub fn set_current_line_highlight(
2350 &mut self,
2351 current_line_highlight: Option<CurrentLineHighlight>,
2352 ) {
2353 self.current_line_highlight = current_line_highlight;
2354 }
2355
2356 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2357 self.collapse_matches = collapse_matches;
2358 }
2359
2360 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2361 if self.collapse_matches {
2362 return range.start..range.start;
2363 }
2364 range.clone()
2365 }
2366
2367 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2368 if self.display_map.read(cx).clip_at_line_ends != clip {
2369 self.display_map
2370 .update(cx, |map, _| map.clip_at_line_ends = clip);
2371 }
2372 }
2373
2374 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2375 self.input_enabled = input_enabled;
2376 }
2377
2378 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2379 self.enable_inline_completions = enabled;
2380 }
2381
2382 pub fn set_autoindent(&mut self, autoindent: bool) {
2383 if autoindent {
2384 self.autoindent_mode = Some(AutoindentMode::EachLine);
2385 } else {
2386 self.autoindent_mode = None;
2387 }
2388 }
2389
2390 pub fn read_only(&self, cx: &AppContext) -> bool {
2391 self.read_only || self.buffer.read(cx).read_only()
2392 }
2393
2394 pub fn set_read_only(&mut self, read_only: bool) {
2395 self.read_only = read_only;
2396 }
2397
2398 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2399 self.use_autoclose = autoclose;
2400 }
2401
2402 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2403 self.use_auto_surround = auto_surround;
2404 }
2405
2406 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2407 self.auto_replace_emoji_shortcode = auto_replace;
2408 }
2409
2410 pub fn toggle_inline_completions(
2411 &mut self,
2412 _: &ToggleInlineCompletions,
2413 cx: &mut ViewContext<Self>,
2414 ) {
2415 if self.show_inline_completions_override.is_some() {
2416 self.set_show_inline_completions(None, cx);
2417 } else {
2418 let cursor = self.selections.newest_anchor().head();
2419 if let Some((buffer, cursor_buffer_position)) =
2420 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2421 {
2422 let show_inline_completions =
2423 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2424 self.set_show_inline_completions(Some(show_inline_completions), cx);
2425 }
2426 }
2427 }
2428
2429 pub fn set_show_inline_completions(
2430 &mut self,
2431 show_inline_completions: Option<bool>,
2432 cx: &mut ViewContext<Self>,
2433 ) {
2434 self.show_inline_completions_override = show_inline_completions;
2435 self.refresh_inline_completion(false, true, cx);
2436 }
2437
2438 fn should_show_inline_completions(
2439 &self,
2440 buffer: &Model<Buffer>,
2441 buffer_position: language::Anchor,
2442 cx: &AppContext,
2443 ) -> bool {
2444 if let Some(provider) = self.inline_completion_provider() {
2445 if let Some(show_inline_completions) = self.show_inline_completions_override {
2446 show_inline_completions
2447 } else {
2448 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2449 }
2450 } else {
2451 false
2452 }
2453 }
2454
2455 pub fn set_use_modal_editing(&mut self, to: bool) {
2456 self.use_modal_editing = to;
2457 }
2458
2459 pub fn use_modal_editing(&self) -> bool {
2460 self.use_modal_editing
2461 }
2462
2463 fn selections_did_change(
2464 &mut self,
2465 local: bool,
2466 old_cursor_position: &Anchor,
2467 show_completions: bool,
2468 cx: &mut ViewContext<Self>,
2469 ) {
2470 cx.invalidate_character_coordinates();
2471
2472 // Copy selections to primary selection buffer
2473 #[cfg(target_os = "linux")]
2474 if local {
2475 let selections = self.selections.all::<usize>(cx);
2476 let buffer_handle = self.buffer.read(cx).read(cx);
2477
2478 let mut text = String::new();
2479 for (index, selection) in selections.iter().enumerate() {
2480 let text_for_selection = buffer_handle
2481 .text_for_range(selection.start..selection.end)
2482 .collect::<String>();
2483
2484 text.push_str(&text_for_selection);
2485 if index != selections.len() - 1 {
2486 text.push('\n');
2487 }
2488 }
2489
2490 if !text.is_empty() {
2491 cx.write_to_primary(ClipboardItem::new_string(text));
2492 }
2493 }
2494
2495 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2496 self.buffer.update(cx, |buffer, cx| {
2497 buffer.set_active_selections(
2498 &self.selections.disjoint_anchors(),
2499 self.selections.line_mode,
2500 self.cursor_shape,
2501 cx,
2502 )
2503 });
2504 }
2505 let display_map = self
2506 .display_map
2507 .update(cx, |display_map, cx| display_map.snapshot(cx));
2508 let buffer = &display_map.buffer_snapshot;
2509 self.add_selections_state = None;
2510 self.select_next_state = None;
2511 self.select_prev_state = None;
2512 self.select_larger_syntax_node_stack.clear();
2513 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2514 self.snippet_stack
2515 .invalidate(&self.selections.disjoint_anchors(), buffer);
2516 self.take_rename(false, cx);
2517
2518 let new_cursor_position = self.selections.newest_anchor().head();
2519
2520 self.push_to_nav_history(
2521 *old_cursor_position,
2522 Some(new_cursor_position.to_point(buffer)),
2523 cx,
2524 );
2525
2526 if local {
2527 let new_cursor_position = self.selections.newest_anchor().head();
2528 let mut context_menu = self.context_menu.write();
2529 let completion_menu = match context_menu.as_ref() {
2530 Some(ContextMenu::Completions(menu)) => Some(menu),
2531
2532 _ => {
2533 *context_menu = None;
2534 None
2535 }
2536 };
2537
2538 if let Some(completion_menu) = completion_menu {
2539 let cursor_position = new_cursor_position.to_offset(buffer);
2540 let (word_range, kind) =
2541 buffer.surrounding_word(completion_menu.initial_position, true);
2542 if kind == Some(CharKind::Word)
2543 && word_range.to_inclusive().contains(&cursor_position)
2544 {
2545 let mut completion_menu = completion_menu.clone();
2546 drop(context_menu);
2547
2548 let query = Self::completion_query(buffer, cursor_position);
2549 cx.spawn(move |this, mut cx| async move {
2550 completion_menu
2551 .filter(query.as_deref(), cx.background_executor().clone())
2552 .await;
2553
2554 this.update(&mut cx, |this, cx| {
2555 let mut context_menu = this.context_menu.write();
2556 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2557 return;
2558 };
2559
2560 if menu.id > completion_menu.id {
2561 return;
2562 }
2563
2564 *context_menu = Some(ContextMenu::Completions(completion_menu));
2565 drop(context_menu);
2566 cx.notify();
2567 })
2568 })
2569 .detach();
2570
2571 if show_completions {
2572 self.show_completions(&ShowCompletions { trigger: None }, cx);
2573 }
2574 } else {
2575 drop(context_menu);
2576 self.hide_context_menu(cx);
2577 }
2578 } else {
2579 drop(context_menu);
2580 }
2581
2582 hide_hover(self, cx);
2583
2584 if old_cursor_position.to_display_point(&display_map).row()
2585 != new_cursor_position.to_display_point(&display_map).row()
2586 {
2587 self.available_code_actions.take();
2588 }
2589 self.refresh_code_actions(cx);
2590 self.refresh_document_highlights(cx);
2591 refresh_matching_bracket_highlights(self, cx);
2592 self.discard_inline_completion(false, cx);
2593 linked_editing_ranges::refresh_linked_ranges(self, cx);
2594 if self.git_blame_inline_enabled {
2595 self.start_inline_blame_timer(cx);
2596 }
2597 }
2598
2599 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2600 cx.emit(EditorEvent::SelectionsChanged { local });
2601
2602 if self.selections.disjoint_anchors().len() == 1 {
2603 cx.emit(SearchEvent::ActiveMatchChanged)
2604 }
2605 cx.notify();
2606 }
2607
2608 pub fn change_selections<R>(
2609 &mut self,
2610 autoscroll: Option<Autoscroll>,
2611 cx: &mut ViewContext<Self>,
2612 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2613 ) -> R {
2614 self.change_selections_inner(autoscroll, true, cx, change)
2615 }
2616
2617 pub fn change_selections_inner<R>(
2618 &mut self,
2619 autoscroll: Option<Autoscroll>,
2620 request_completions: bool,
2621 cx: &mut ViewContext<Self>,
2622 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2623 ) -> R {
2624 let old_cursor_position = self.selections.newest_anchor().head();
2625 self.push_to_selection_history();
2626
2627 let (changed, result) = self.selections.change_with(cx, change);
2628
2629 if changed {
2630 if let Some(autoscroll) = autoscroll {
2631 self.request_autoscroll(autoscroll, cx);
2632 }
2633 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2634
2635 if self.should_open_signature_help_automatically(
2636 &old_cursor_position,
2637 self.signature_help_state.backspace_pressed(),
2638 cx,
2639 ) {
2640 self.show_signature_help(&ShowSignatureHelp, cx);
2641 }
2642 self.signature_help_state.set_backspace_pressed(false);
2643 }
2644
2645 result
2646 }
2647
2648 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2649 where
2650 I: IntoIterator<Item = (Range<S>, T)>,
2651 S: ToOffset,
2652 T: Into<Arc<str>>,
2653 {
2654 if self.read_only(cx) {
2655 return;
2656 }
2657
2658 self.buffer
2659 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2660 }
2661
2662 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2663 where
2664 I: IntoIterator<Item = (Range<S>, T)>,
2665 S: ToOffset,
2666 T: Into<Arc<str>>,
2667 {
2668 if self.read_only(cx) {
2669 return;
2670 }
2671
2672 self.buffer.update(cx, |buffer, cx| {
2673 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2674 });
2675 }
2676
2677 pub fn edit_with_block_indent<I, S, T>(
2678 &mut self,
2679 edits: I,
2680 original_indent_columns: Vec<u32>,
2681 cx: &mut ViewContext<Self>,
2682 ) where
2683 I: IntoIterator<Item = (Range<S>, T)>,
2684 S: ToOffset,
2685 T: Into<Arc<str>>,
2686 {
2687 if self.read_only(cx) {
2688 return;
2689 }
2690
2691 self.buffer.update(cx, |buffer, cx| {
2692 buffer.edit(
2693 edits,
2694 Some(AutoindentMode::Block {
2695 original_indent_columns,
2696 }),
2697 cx,
2698 )
2699 });
2700 }
2701
2702 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2703 self.hide_context_menu(cx);
2704
2705 match phase {
2706 SelectPhase::Begin {
2707 position,
2708 add,
2709 click_count,
2710 } => self.begin_selection(position, add, click_count, cx),
2711 SelectPhase::BeginColumnar {
2712 position,
2713 goal_column,
2714 reset,
2715 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2716 SelectPhase::Extend {
2717 position,
2718 click_count,
2719 } => self.extend_selection(position, click_count, cx),
2720 SelectPhase::Update {
2721 position,
2722 goal_column,
2723 scroll_delta,
2724 } => self.update_selection(position, goal_column, scroll_delta, cx),
2725 SelectPhase::End => self.end_selection(cx),
2726 }
2727 }
2728
2729 fn extend_selection(
2730 &mut self,
2731 position: DisplayPoint,
2732 click_count: usize,
2733 cx: &mut ViewContext<Self>,
2734 ) {
2735 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2736 let tail = self.selections.newest::<usize>(cx).tail();
2737 self.begin_selection(position, false, click_count, cx);
2738
2739 let position = position.to_offset(&display_map, Bias::Left);
2740 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2741
2742 let mut pending_selection = self
2743 .selections
2744 .pending_anchor()
2745 .expect("extend_selection not called with pending selection");
2746 if position >= tail {
2747 pending_selection.start = tail_anchor;
2748 } else {
2749 pending_selection.end = tail_anchor;
2750 pending_selection.reversed = true;
2751 }
2752
2753 let mut pending_mode = self.selections.pending_mode().unwrap();
2754 match &mut pending_mode {
2755 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2756 _ => {}
2757 }
2758
2759 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2760 s.set_pending(pending_selection, pending_mode)
2761 });
2762 }
2763
2764 fn begin_selection(
2765 &mut self,
2766 position: DisplayPoint,
2767 add: bool,
2768 click_count: usize,
2769 cx: &mut ViewContext<Self>,
2770 ) {
2771 if !self.focus_handle.is_focused(cx) {
2772 self.last_focused_descendant = None;
2773 cx.focus(&self.focus_handle);
2774 }
2775
2776 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2777 let buffer = &display_map.buffer_snapshot;
2778 let newest_selection = self.selections.newest_anchor().clone();
2779 let position = display_map.clip_point(position, Bias::Left);
2780
2781 let start;
2782 let end;
2783 let mode;
2784 let auto_scroll;
2785 match click_count {
2786 1 => {
2787 start = buffer.anchor_before(position.to_point(&display_map));
2788 end = start;
2789 mode = SelectMode::Character;
2790 auto_scroll = true;
2791 }
2792 2 => {
2793 let range = movement::surrounding_word(&display_map, position);
2794 start = buffer.anchor_before(range.start.to_point(&display_map));
2795 end = buffer.anchor_before(range.end.to_point(&display_map));
2796 mode = SelectMode::Word(start..end);
2797 auto_scroll = true;
2798 }
2799 3 => {
2800 let position = display_map
2801 .clip_point(position, Bias::Left)
2802 .to_point(&display_map);
2803 let line_start = display_map.prev_line_boundary(position).0;
2804 let next_line_start = buffer.clip_point(
2805 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2806 Bias::Left,
2807 );
2808 start = buffer.anchor_before(line_start);
2809 end = buffer.anchor_before(next_line_start);
2810 mode = SelectMode::Line(start..end);
2811 auto_scroll = true;
2812 }
2813 _ => {
2814 start = buffer.anchor_before(0);
2815 end = buffer.anchor_before(buffer.len());
2816 mode = SelectMode::All;
2817 auto_scroll = false;
2818 }
2819 }
2820
2821 let point_to_delete: Option<usize> = {
2822 let selected_points: Vec<Selection<Point>> =
2823 self.selections.disjoint_in_range(start..end, cx);
2824
2825 if !add || click_count > 1 {
2826 None
2827 } else if !selected_points.is_empty() {
2828 Some(selected_points[0].id)
2829 } else {
2830 let clicked_point_already_selected =
2831 self.selections.disjoint.iter().find(|selection| {
2832 selection.start.to_point(buffer) == start.to_point(buffer)
2833 || selection.end.to_point(buffer) == end.to_point(buffer)
2834 });
2835
2836 clicked_point_already_selected.map(|selection| selection.id)
2837 }
2838 };
2839
2840 let selections_count = self.selections.count();
2841
2842 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2843 if let Some(point_to_delete) = point_to_delete {
2844 s.delete(point_to_delete);
2845
2846 if selections_count == 1 {
2847 s.set_pending_anchor_range(start..end, mode);
2848 }
2849 } else {
2850 if !add {
2851 s.clear_disjoint();
2852 } else if click_count > 1 {
2853 s.delete(newest_selection.id)
2854 }
2855
2856 s.set_pending_anchor_range(start..end, mode);
2857 }
2858 });
2859 }
2860
2861 fn begin_columnar_selection(
2862 &mut self,
2863 position: DisplayPoint,
2864 goal_column: u32,
2865 reset: bool,
2866 cx: &mut ViewContext<Self>,
2867 ) {
2868 if !self.focus_handle.is_focused(cx) {
2869 self.last_focused_descendant = None;
2870 cx.focus(&self.focus_handle);
2871 }
2872
2873 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2874
2875 if reset {
2876 let pointer_position = display_map
2877 .buffer_snapshot
2878 .anchor_before(position.to_point(&display_map));
2879
2880 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2881 s.clear_disjoint();
2882 s.set_pending_anchor_range(
2883 pointer_position..pointer_position,
2884 SelectMode::Character,
2885 );
2886 });
2887 }
2888
2889 let tail = self.selections.newest::<Point>(cx).tail();
2890 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2891
2892 if !reset {
2893 self.select_columns(
2894 tail.to_display_point(&display_map),
2895 position,
2896 goal_column,
2897 &display_map,
2898 cx,
2899 );
2900 }
2901 }
2902
2903 fn update_selection(
2904 &mut self,
2905 position: DisplayPoint,
2906 goal_column: u32,
2907 scroll_delta: gpui::Point<f32>,
2908 cx: &mut ViewContext<Self>,
2909 ) {
2910 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2911
2912 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2913 let tail = tail.to_display_point(&display_map);
2914 self.select_columns(tail, position, goal_column, &display_map, cx);
2915 } else if let Some(mut pending) = self.selections.pending_anchor() {
2916 let buffer = self.buffer.read(cx).snapshot(cx);
2917 let head;
2918 let tail;
2919 let mode = self.selections.pending_mode().unwrap();
2920 match &mode {
2921 SelectMode::Character => {
2922 head = position.to_point(&display_map);
2923 tail = pending.tail().to_point(&buffer);
2924 }
2925 SelectMode::Word(original_range) => {
2926 let original_display_range = original_range.start.to_display_point(&display_map)
2927 ..original_range.end.to_display_point(&display_map);
2928 let original_buffer_range = original_display_range.start.to_point(&display_map)
2929 ..original_display_range.end.to_point(&display_map);
2930 if movement::is_inside_word(&display_map, position)
2931 || original_display_range.contains(&position)
2932 {
2933 let word_range = movement::surrounding_word(&display_map, position);
2934 if word_range.start < original_display_range.start {
2935 head = word_range.start.to_point(&display_map);
2936 } else {
2937 head = word_range.end.to_point(&display_map);
2938 }
2939 } else {
2940 head = position.to_point(&display_map);
2941 }
2942
2943 if head <= original_buffer_range.start {
2944 tail = original_buffer_range.end;
2945 } else {
2946 tail = original_buffer_range.start;
2947 }
2948 }
2949 SelectMode::Line(original_range) => {
2950 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2951
2952 let position = display_map
2953 .clip_point(position, Bias::Left)
2954 .to_point(&display_map);
2955 let line_start = display_map.prev_line_boundary(position).0;
2956 let next_line_start = buffer.clip_point(
2957 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2958 Bias::Left,
2959 );
2960
2961 if line_start < original_range.start {
2962 head = line_start
2963 } else {
2964 head = next_line_start
2965 }
2966
2967 if head <= original_range.start {
2968 tail = original_range.end;
2969 } else {
2970 tail = original_range.start;
2971 }
2972 }
2973 SelectMode::All => {
2974 return;
2975 }
2976 };
2977
2978 if head < tail {
2979 pending.start = buffer.anchor_before(head);
2980 pending.end = buffer.anchor_before(tail);
2981 pending.reversed = true;
2982 } else {
2983 pending.start = buffer.anchor_before(tail);
2984 pending.end = buffer.anchor_before(head);
2985 pending.reversed = false;
2986 }
2987
2988 self.change_selections(None, cx, |s| {
2989 s.set_pending(pending, mode);
2990 });
2991 } else {
2992 log::error!("update_selection dispatched with no pending selection");
2993 return;
2994 }
2995
2996 self.apply_scroll_delta(scroll_delta, cx);
2997 cx.notify();
2998 }
2999
3000 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
3001 self.columnar_selection_tail.take();
3002 if self.selections.pending_anchor().is_some() {
3003 let selections = self.selections.all::<usize>(cx);
3004 self.change_selections(None, cx, |s| {
3005 s.select(selections);
3006 s.clear_pending();
3007 });
3008 }
3009 }
3010
3011 fn select_columns(
3012 &mut self,
3013 tail: DisplayPoint,
3014 head: DisplayPoint,
3015 goal_column: u32,
3016 display_map: &DisplaySnapshot,
3017 cx: &mut ViewContext<Self>,
3018 ) {
3019 let start_row = cmp::min(tail.row(), head.row());
3020 let end_row = cmp::max(tail.row(), head.row());
3021 let start_column = cmp::min(tail.column(), goal_column);
3022 let end_column = cmp::max(tail.column(), goal_column);
3023 let reversed = start_column < tail.column();
3024
3025 let selection_ranges = (start_row.0..=end_row.0)
3026 .map(DisplayRow)
3027 .filter_map(|row| {
3028 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3029 let start = display_map
3030 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3031 .to_point(display_map);
3032 let end = display_map
3033 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3034 .to_point(display_map);
3035 if reversed {
3036 Some(end..start)
3037 } else {
3038 Some(start..end)
3039 }
3040 } else {
3041 None
3042 }
3043 })
3044 .collect::<Vec<_>>();
3045
3046 self.change_selections(None, cx, |s| {
3047 s.select_ranges(selection_ranges);
3048 });
3049 cx.notify();
3050 }
3051
3052 pub fn has_pending_nonempty_selection(&self) -> bool {
3053 let pending_nonempty_selection = match self.selections.pending_anchor() {
3054 Some(Selection { start, end, .. }) => start != end,
3055 None => false,
3056 };
3057
3058 pending_nonempty_selection
3059 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3060 }
3061
3062 pub fn has_pending_selection(&self) -> bool {
3063 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3064 }
3065
3066 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3067 if self.clear_expanded_diff_hunks(cx) {
3068 cx.notify();
3069 return;
3070 }
3071 if self.dismiss_menus_and_popups(true, cx) {
3072 return;
3073 }
3074
3075 if self.mode == EditorMode::Full
3076 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3077 {
3078 return;
3079 }
3080
3081 cx.propagate();
3082 }
3083
3084 pub fn dismiss_menus_and_popups(
3085 &mut self,
3086 should_report_inline_completion_event: bool,
3087 cx: &mut ViewContext<Self>,
3088 ) -> bool {
3089 if self.take_rename(false, cx).is_some() {
3090 return true;
3091 }
3092
3093 if hide_hover(self, cx) {
3094 return true;
3095 }
3096
3097 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3098 return true;
3099 }
3100
3101 if self.hide_context_menu(cx).is_some() {
3102 return true;
3103 }
3104
3105 if self.mouse_context_menu.take().is_some() {
3106 return true;
3107 }
3108
3109 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3110 return true;
3111 }
3112
3113 if self.snippet_stack.pop().is_some() {
3114 return true;
3115 }
3116
3117 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3118 self.dismiss_diagnostics(cx);
3119 return true;
3120 }
3121
3122 false
3123 }
3124
3125 fn linked_editing_ranges_for(
3126 &self,
3127 selection: Range<text::Anchor>,
3128 cx: &AppContext,
3129 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3130 if self.linked_edit_ranges.is_empty() {
3131 return None;
3132 }
3133 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3134 selection.end.buffer_id.and_then(|end_buffer_id| {
3135 if selection.start.buffer_id != Some(end_buffer_id) {
3136 return None;
3137 }
3138 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3139 let snapshot = buffer.read(cx).snapshot();
3140 self.linked_edit_ranges
3141 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3142 .map(|ranges| (ranges, snapshot, buffer))
3143 })?;
3144 use text::ToOffset as TO;
3145 // find offset from the start of current range to current cursor position
3146 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3147
3148 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3149 let start_difference = start_offset - start_byte_offset;
3150 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3151 let end_difference = end_offset - start_byte_offset;
3152 // Current range has associated linked ranges.
3153 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3154 for range in linked_ranges.iter() {
3155 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3156 let end_offset = start_offset + end_difference;
3157 let start_offset = start_offset + start_difference;
3158 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3159 continue;
3160 }
3161 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3162 if s.start.buffer_id != selection.start.buffer_id
3163 || s.end.buffer_id != selection.end.buffer_id
3164 {
3165 return false;
3166 }
3167 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3168 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3169 }) {
3170 continue;
3171 }
3172 let start = buffer_snapshot.anchor_after(start_offset);
3173 let end = buffer_snapshot.anchor_after(end_offset);
3174 linked_edits
3175 .entry(buffer.clone())
3176 .or_default()
3177 .push(start..end);
3178 }
3179 Some(linked_edits)
3180 }
3181
3182 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3183 let text: Arc<str> = text.into();
3184
3185 if self.read_only(cx) {
3186 return;
3187 }
3188
3189 let selections = self.selections.all_adjusted(cx);
3190 let mut bracket_inserted = false;
3191 let mut edits = Vec::new();
3192 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3193 let mut new_selections = Vec::with_capacity(selections.len());
3194 let mut new_autoclose_regions = Vec::new();
3195 let snapshot = self.buffer.read(cx).read(cx);
3196
3197 for (selection, autoclose_region) in
3198 self.selections_with_autoclose_regions(selections, &snapshot)
3199 {
3200 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3201 // Determine if the inserted text matches the opening or closing
3202 // bracket of any of this language's bracket pairs.
3203 let mut bracket_pair = None;
3204 let mut is_bracket_pair_start = false;
3205 let mut is_bracket_pair_end = false;
3206 if !text.is_empty() {
3207 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3208 // and they are removing the character that triggered IME popup.
3209 for (pair, enabled) in scope.brackets() {
3210 if !pair.close && !pair.surround {
3211 continue;
3212 }
3213
3214 if enabled && pair.start.ends_with(text.as_ref()) {
3215 bracket_pair = Some(pair.clone());
3216 is_bracket_pair_start = true;
3217 break;
3218 }
3219 if pair.end.as_str() == text.as_ref() {
3220 bracket_pair = Some(pair.clone());
3221 is_bracket_pair_end = true;
3222 break;
3223 }
3224 }
3225 }
3226
3227 if let Some(bracket_pair) = bracket_pair {
3228 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3229 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3230 let auto_surround =
3231 self.use_auto_surround && snapshot_settings.use_auto_surround;
3232 if selection.is_empty() {
3233 if is_bracket_pair_start {
3234 let prefix_len = bracket_pair.start.len() - text.len();
3235
3236 // If the inserted text is a suffix of an opening bracket and the
3237 // selection is preceded by the rest of the opening bracket, then
3238 // insert the closing bracket.
3239 let following_text_allows_autoclose = snapshot
3240 .chars_at(selection.start)
3241 .next()
3242 .map_or(true, |c| scope.should_autoclose_before(c));
3243 let preceding_text_matches_prefix = prefix_len == 0
3244 || (selection.start.column >= (prefix_len as u32)
3245 && snapshot.contains_str_at(
3246 Point::new(
3247 selection.start.row,
3248 selection.start.column - (prefix_len as u32),
3249 ),
3250 &bracket_pair.start[..prefix_len],
3251 ));
3252
3253 if autoclose
3254 && bracket_pair.close
3255 && following_text_allows_autoclose
3256 && preceding_text_matches_prefix
3257 {
3258 let anchor = snapshot.anchor_before(selection.end);
3259 new_selections.push((selection.map(|_| anchor), text.len()));
3260 new_autoclose_regions.push((
3261 anchor,
3262 text.len(),
3263 selection.id,
3264 bracket_pair.clone(),
3265 ));
3266 edits.push((
3267 selection.range(),
3268 format!("{}{}", text, bracket_pair.end).into(),
3269 ));
3270 bracket_inserted = true;
3271 continue;
3272 }
3273 }
3274
3275 if let Some(region) = autoclose_region {
3276 // If the selection is followed by an auto-inserted closing bracket,
3277 // then don't insert that closing bracket again; just move the selection
3278 // past the closing bracket.
3279 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3280 && text.as_ref() == region.pair.end.as_str();
3281 if should_skip {
3282 let anchor = snapshot.anchor_after(selection.end);
3283 new_selections
3284 .push((selection.map(|_| anchor), region.pair.end.len()));
3285 continue;
3286 }
3287 }
3288
3289 let always_treat_brackets_as_autoclosed = snapshot
3290 .settings_at(selection.start, cx)
3291 .always_treat_brackets_as_autoclosed;
3292 if always_treat_brackets_as_autoclosed
3293 && is_bracket_pair_end
3294 && snapshot.contains_str_at(selection.end, text.as_ref())
3295 {
3296 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3297 // and the inserted text is a closing bracket and the selection is followed
3298 // by the closing bracket then move the selection past the closing bracket.
3299 let anchor = snapshot.anchor_after(selection.end);
3300 new_selections.push((selection.map(|_| anchor), text.len()));
3301 continue;
3302 }
3303 }
3304 // If an opening bracket is 1 character long and is typed while
3305 // text is selected, then surround that text with the bracket pair.
3306 else if auto_surround
3307 && bracket_pair.surround
3308 && is_bracket_pair_start
3309 && bracket_pair.start.chars().count() == 1
3310 {
3311 edits.push((selection.start..selection.start, text.clone()));
3312 edits.push((
3313 selection.end..selection.end,
3314 bracket_pair.end.as_str().into(),
3315 ));
3316 bracket_inserted = true;
3317 new_selections.push((
3318 Selection {
3319 id: selection.id,
3320 start: snapshot.anchor_after(selection.start),
3321 end: snapshot.anchor_before(selection.end),
3322 reversed: selection.reversed,
3323 goal: selection.goal,
3324 },
3325 0,
3326 ));
3327 continue;
3328 }
3329 }
3330 }
3331
3332 if self.auto_replace_emoji_shortcode
3333 && selection.is_empty()
3334 && text.as_ref().ends_with(':')
3335 {
3336 if let Some(possible_emoji_short_code) =
3337 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3338 {
3339 if !possible_emoji_short_code.is_empty() {
3340 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3341 let emoji_shortcode_start = Point::new(
3342 selection.start.row,
3343 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3344 );
3345
3346 // Remove shortcode from buffer
3347 edits.push((
3348 emoji_shortcode_start..selection.start,
3349 "".to_string().into(),
3350 ));
3351 new_selections.push((
3352 Selection {
3353 id: selection.id,
3354 start: snapshot.anchor_after(emoji_shortcode_start),
3355 end: snapshot.anchor_before(selection.start),
3356 reversed: selection.reversed,
3357 goal: selection.goal,
3358 },
3359 0,
3360 ));
3361
3362 // Insert emoji
3363 let selection_start_anchor = snapshot.anchor_after(selection.start);
3364 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3365 edits.push((selection.start..selection.end, emoji.to_string().into()));
3366
3367 continue;
3368 }
3369 }
3370 }
3371 }
3372
3373 // If not handling any auto-close operation, then just replace the selected
3374 // text with the given input and move the selection to the end of the
3375 // newly inserted text.
3376 let anchor = snapshot.anchor_after(selection.end);
3377 if !self.linked_edit_ranges.is_empty() {
3378 let start_anchor = snapshot.anchor_before(selection.start);
3379
3380 let is_word_char = text.chars().next().map_or(true, |char| {
3381 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3382 classifier.is_word(char)
3383 });
3384
3385 if is_word_char {
3386 if let Some(ranges) = self
3387 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3388 {
3389 for (buffer, edits) in ranges {
3390 linked_edits
3391 .entry(buffer.clone())
3392 .or_default()
3393 .extend(edits.into_iter().map(|range| (range, text.clone())));
3394 }
3395 }
3396 }
3397 }
3398
3399 new_selections.push((selection.map(|_| anchor), 0));
3400 edits.push((selection.start..selection.end, text.clone()));
3401 }
3402
3403 drop(snapshot);
3404
3405 self.transact(cx, |this, cx| {
3406 this.buffer.update(cx, |buffer, cx| {
3407 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3408 });
3409 for (buffer, edits) in linked_edits {
3410 buffer.update(cx, |buffer, cx| {
3411 let snapshot = buffer.snapshot();
3412 let edits = edits
3413 .into_iter()
3414 .map(|(range, text)| {
3415 use text::ToPoint as TP;
3416 let end_point = TP::to_point(&range.end, &snapshot);
3417 let start_point = TP::to_point(&range.start, &snapshot);
3418 (start_point..end_point, text)
3419 })
3420 .sorted_by_key(|(range, _)| range.start)
3421 .collect::<Vec<_>>();
3422 buffer.edit(edits, None, cx);
3423 })
3424 }
3425 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3426 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3427 let snapshot = this.buffer.read(cx).read(cx);
3428 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3429 .zip(new_selection_deltas)
3430 .map(|(selection, delta)| Selection {
3431 id: selection.id,
3432 start: selection.start + delta,
3433 end: selection.end + delta,
3434 reversed: selection.reversed,
3435 goal: SelectionGoal::None,
3436 })
3437 .collect::<Vec<_>>();
3438
3439 let mut i = 0;
3440 for (position, delta, selection_id, pair) in new_autoclose_regions {
3441 let position = position.to_offset(&snapshot) + delta;
3442 let start = snapshot.anchor_before(position);
3443 let end = snapshot.anchor_after(position);
3444 while let Some(existing_state) = this.autoclose_regions.get(i) {
3445 match existing_state.range.start.cmp(&start, &snapshot) {
3446 Ordering::Less => i += 1,
3447 Ordering::Greater => break,
3448 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3449 Ordering::Less => i += 1,
3450 Ordering::Equal => break,
3451 Ordering::Greater => break,
3452 },
3453 }
3454 }
3455 this.autoclose_regions.insert(
3456 i,
3457 AutocloseRegion {
3458 selection_id,
3459 range: start..end,
3460 pair,
3461 },
3462 );
3463 }
3464
3465 drop(snapshot);
3466 let had_active_inline_completion = this.has_active_inline_completion(cx);
3467 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3468 s.select(new_selections)
3469 });
3470
3471 if !bracket_inserted {
3472 if let Some(on_type_format_task) =
3473 this.trigger_on_type_formatting(text.to_string(), cx)
3474 {
3475 on_type_format_task.detach_and_log_err(cx);
3476 }
3477 }
3478
3479 let editor_settings = EditorSettings::get_global(cx);
3480 if bracket_inserted
3481 && (editor_settings.auto_signature_help
3482 || editor_settings.show_signature_help_after_edits)
3483 {
3484 this.show_signature_help(&ShowSignatureHelp, cx);
3485 }
3486
3487 let trigger_in_words = !had_active_inline_completion;
3488 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3489 linked_editing_ranges::refresh_linked_ranges(this, cx);
3490 this.refresh_inline_completion(true, false, cx);
3491 });
3492 }
3493
3494 fn find_possible_emoji_shortcode_at_position(
3495 snapshot: &MultiBufferSnapshot,
3496 position: Point,
3497 ) -> Option<String> {
3498 let mut chars = Vec::new();
3499 let mut found_colon = false;
3500 for char in snapshot.reversed_chars_at(position).take(100) {
3501 // Found a possible emoji shortcode in the middle of the buffer
3502 if found_colon {
3503 if char.is_whitespace() {
3504 chars.reverse();
3505 return Some(chars.iter().collect());
3506 }
3507 // If the previous character is not a whitespace, we are in the middle of a word
3508 // and we only want to complete the shortcode if the word is made up of other emojis
3509 let mut containing_word = String::new();
3510 for ch in snapshot
3511 .reversed_chars_at(position)
3512 .skip(chars.len() + 1)
3513 .take(100)
3514 {
3515 if ch.is_whitespace() {
3516 break;
3517 }
3518 containing_word.push(ch);
3519 }
3520 let containing_word = containing_word.chars().rev().collect::<String>();
3521 if util::word_consists_of_emojis(containing_word.as_str()) {
3522 chars.reverse();
3523 return Some(chars.iter().collect());
3524 }
3525 }
3526
3527 if char.is_whitespace() || !char.is_ascii() {
3528 return None;
3529 }
3530 if char == ':' {
3531 found_colon = true;
3532 } else {
3533 chars.push(char);
3534 }
3535 }
3536 // Found a possible emoji shortcode at the beginning of the buffer
3537 chars.reverse();
3538 Some(chars.iter().collect())
3539 }
3540
3541 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3542 self.transact(cx, |this, cx| {
3543 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3544 let selections = this.selections.all::<usize>(cx);
3545 let multi_buffer = this.buffer.read(cx);
3546 let buffer = multi_buffer.snapshot(cx);
3547 selections
3548 .iter()
3549 .map(|selection| {
3550 let start_point = selection.start.to_point(&buffer);
3551 let mut indent =
3552 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3553 indent.len = cmp::min(indent.len, start_point.column);
3554 let start = selection.start;
3555 let end = selection.end;
3556 let selection_is_empty = start == end;
3557 let language_scope = buffer.language_scope_at(start);
3558 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3559 &language_scope
3560 {
3561 let leading_whitespace_len = buffer
3562 .reversed_chars_at(start)
3563 .take_while(|c| c.is_whitespace() && *c != '\n')
3564 .map(|c| c.len_utf8())
3565 .sum::<usize>();
3566
3567 let trailing_whitespace_len = buffer
3568 .chars_at(end)
3569 .take_while(|c| c.is_whitespace() && *c != '\n')
3570 .map(|c| c.len_utf8())
3571 .sum::<usize>();
3572
3573 let insert_extra_newline =
3574 language.brackets().any(|(pair, enabled)| {
3575 let pair_start = pair.start.trim_end();
3576 let pair_end = pair.end.trim_start();
3577
3578 enabled
3579 && pair.newline
3580 && buffer.contains_str_at(
3581 end + trailing_whitespace_len,
3582 pair_end,
3583 )
3584 && buffer.contains_str_at(
3585 (start - leading_whitespace_len)
3586 .saturating_sub(pair_start.len()),
3587 pair_start,
3588 )
3589 });
3590
3591 // Comment extension on newline is allowed only for cursor selections
3592 let comment_delimiter = maybe!({
3593 if !selection_is_empty {
3594 return None;
3595 }
3596
3597 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3598 return None;
3599 }
3600
3601 let delimiters = language.line_comment_prefixes();
3602 let max_len_of_delimiter =
3603 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3604 let (snapshot, range) =
3605 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3606
3607 let mut index_of_first_non_whitespace = 0;
3608 let comment_candidate = snapshot
3609 .chars_for_range(range)
3610 .skip_while(|c| {
3611 let should_skip = c.is_whitespace();
3612 if should_skip {
3613 index_of_first_non_whitespace += 1;
3614 }
3615 should_skip
3616 })
3617 .take(max_len_of_delimiter)
3618 .collect::<String>();
3619 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3620 comment_candidate.starts_with(comment_prefix.as_ref())
3621 })?;
3622 let cursor_is_placed_after_comment_marker =
3623 index_of_first_non_whitespace + comment_prefix.len()
3624 <= start_point.column as usize;
3625 if cursor_is_placed_after_comment_marker {
3626 Some(comment_prefix.clone())
3627 } else {
3628 None
3629 }
3630 });
3631 (comment_delimiter, insert_extra_newline)
3632 } else {
3633 (None, false)
3634 };
3635
3636 let capacity_for_delimiter = comment_delimiter
3637 .as_deref()
3638 .map(str::len)
3639 .unwrap_or_default();
3640 let mut new_text =
3641 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3642 new_text.push('\n');
3643 new_text.extend(indent.chars());
3644 if let Some(delimiter) = &comment_delimiter {
3645 new_text.push_str(delimiter);
3646 }
3647 if insert_extra_newline {
3648 new_text = new_text.repeat(2);
3649 }
3650
3651 let anchor = buffer.anchor_after(end);
3652 let new_selection = selection.map(|_| anchor);
3653 (
3654 (start..end, new_text),
3655 (insert_extra_newline, new_selection),
3656 )
3657 })
3658 .unzip()
3659 };
3660
3661 this.edit_with_autoindent(edits, cx);
3662 let buffer = this.buffer.read(cx).snapshot(cx);
3663 let new_selections = selection_fixup_info
3664 .into_iter()
3665 .map(|(extra_newline_inserted, new_selection)| {
3666 let mut cursor = new_selection.end.to_point(&buffer);
3667 if extra_newline_inserted {
3668 cursor.row -= 1;
3669 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3670 }
3671 new_selection.map(|_| cursor)
3672 })
3673 .collect();
3674
3675 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3676 this.refresh_inline_completion(true, false, cx);
3677 });
3678 }
3679
3680 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3681 let buffer = self.buffer.read(cx);
3682 let snapshot = buffer.snapshot(cx);
3683
3684 let mut edits = Vec::new();
3685 let mut rows = Vec::new();
3686
3687 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3688 let cursor = selection.head();
3689 let row = cursor.row;
3690
3691 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3692
3693 let newline = "\n".to_string();
3694 edits.push((start_of_line..start_of_line, newline));
3695
3696 rows.push(row + rows_inserted as u32);
3697 }
3698
3699 self.transact(cx, |editor, cx| {
3700 editor.edit(edits, cx);
3701
3702 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3703 let mut index = 0;
3704 s.move_cursors_with(|map, _, _| {
3705 let row = rows[index];
3706 index += 1;
3707
3708 let point = Point::new(row, 0);
3709 let boundary = map.next_line_boundary(point).1;
3710 let clipped = map.clip_point(boundary, Bias::Left);
3711
3712 (clipped, SelectionGoal::None)
3713 });
3714 });
3715
3716 let mut indent_edits = Vec::new();
3717 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3718 for row in rows {
3719 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3720 for (row, indent) in indents {
3721 if indent.len == 0 {
3722 continue;
3723 }
3724
3725 let text = match indent.kind {
3726 IndentKind::Space => " ".repeat(indent.len as usize),
3727 IndentKind::Tab => "\t".repeat(indent.len as usize),
3728 };
3729 let point = Point::new(row.0, 0);
3730 indent_edits.push((point..point, text));
3731 }
3732 }
3733 editor.edit(indent_edits, cx);
3734 });
3735 }
3736
3737 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3738 let buffer = self.buffer.read(cx);
3739 let snapshot = buffer.snapshot(cx);
3740
3741 let mut edits = Vec::new();
3742 let mut rows = Vec::new();
3743 let mut rows_inserted = 0;
3744
3745 for selection in self.selections.all_adjusted(cx) {
3746 let cursor = selection.head();
3747 let row = cursor.row;
3748
3749 let point = Point::new(row + 1, 0);
3750 let start_of_line = snapshot.clip_point(point, Bias::Left);
3751
3752 let newline = "\n".to_string();
3753 edits.push((start_of_line..start_of_line, newline));
3754
3755 rows_inserted += 1;
3756 rows.push(row + rows_inserted);
3757 }
3758
3759 self.transact(cx, |editor, cx| {
3760 editor.edit(edits, cx);
3761
3762 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3763 let mut index = 0;
3764 s.move_cursors_with(|map, _, _| {
3765 let row = rows[index];
3766 index += 1;
3767
3768 let point = Point::new(row, 0);
3769 let boundary = map.next_line_boundary(point).1;
3770 let clipped = map.clip_point(boundary, Bias::Left);
3771
3772 (clipped, SelectionGoal::None)
3773 });
3774 });
3775
3776 let mut indent_edits = Vec::new();
3777 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3778 for row in rows {
3779 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3780 for (row, indent) in indents {
3781 if indent.len == 0 {
3782 continue;
3783 }
3784
3785 let text = match indent.kind {
3786 IndentKind::Space => " ".repeat(indent.len as usize),
3787 IndentKind::Tab => "\t".repeat(indent.len as usize),
3788 };
3789 let point = Point::new(row.0, 0);
3790 indent_edits.push((point..point, text));
3791 }
3792 }
3793 editor.edit(indent_edits, cx);
3794 });
3795 }
3796
3797 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3798 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3799 original_indent_columns: Vec::new(),
3800 });
3801 self.insert_with_autoindent_mode(text, autoindent, cx);
3802 }
3803
3804 fn insert_with_autoindent_mode(
3805 &mut self,
3806 text: &str,
3807 autoindent_mode: Option<AutoindentMode>,
3808 cx: &mut ViewContext<Self>,
3809 ) {
3810 if self.read_only(cx) {
3811 return;
3812 }
3813
3814 let text: Arc<str> = text.into();
3815 self.transact(cx, |this, cx| {
3816 let old_selections = this.selections.all_adjusted(cx);
3817 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3818 let anchors = {
3819 let snapshot = buffer.read(cx);
3820 old_selections
3821 .iter()
3822 .map(|s| {
3823 let anchor = snapshot.anchor_after(s.head());
3824 s.map(|_| anchor)
3825 })
3826 .collect::<Vec<_>>()
3827 };
3828 buffer.edit(
3829 old_selections
3830 .iter()
3831 .map(|s| (s.start..s.end, text.clone())),
3832 autoindent_mode,
3833 cx,
3834 );
3835 anchors
3836 });
3837
3838 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3839 s.select_anchors(selection_anchors);
3840 })
3841 });
3842 }
3843
3844 fn trigger_completion_on_input(
3845 &mut self,
3846 text: &str,
3847 trigger_in_words: bool,
3848 cx: &mut ViewContext<Self>,
3849 ) {
3850 if self.is_completion_trigger(text, trigger_in_words, cx) {
3851 self.show_completions(
3852 &ShowCompletions {
3853 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3854 },
3855 cx,
3856 );
3857 } else {
3858 self.hide_context_menu(cx);
3859 }
3860 }
3861
3862 fn is_completion_trigger(
3863 &self,
3864 text: &str,
3865 trigger_in_words: bool,
3866 cx: &mut ViewContext<Self>,
3867 ) -> bool {
3868 let position = self.selections.newest_anchor().head();
3869 let multibuffer = self.buffer.read(cx);
3870 let Some(buffer) = position
3871 .buffer_id
3872 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3873 else {
3874 return false;
3875 };
3876
3877 if let Some(completion_provider) = &self.completion_provider {
3878 completion_provider.is_completion_trigger(
3879 &buffer,
3880 position.text_anchor,
3881 text,
3882 trigger_in_words,
3883 cx,
3884 )
3885 } else {
3886 false
3887 }
3888 }
3889
3890 /// If any empty selections is touching the start of its innermost containing autoclose
3891 /// region, expand it to select the brackets.
3892 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3893 let selections = self.selections.all::<usize>(cx);
3894 let buffer = self.buffer.read(cx).read(cx);
3895 let new_selections = self
3896 .selections_with_autoclose_regions(selections, &buffer)
3897 .map(|(mut selection, region)| {
3898 if !selection.is_empty() {
3899 return selection;
3900 }
3901
3902 if let Some(region) = region {
3903 let mut range = region.range.to_offset(&buffer);
3904 if selection.start == range.start && range.start >= region.pair.start.len() {
3905 range.start -= region.pair.start.len();
3906 if buffer.contains_str_at(range.start, ®ion.pair.start)
3907 && buffer.contains_str_at(range.end, ®ion.pair.end)
3908 {
3909 range.end += region.pair.end.len();
3910 selection.start = range.start;
3911 selection.end = range.end;
3912
3913 return selection;
3914 }
3915 }
3916 }
3917
3918 let always_treat_brackets_as_autoclosed = buffer
3919 .settings_at(selection.start, cx)
3920 .always_treat_brackets_as_autoclosed;
3921
3922 if !always_treat_brackets_as_autoclosed {
3923 return selection;
3924 }
3925
3926 if let Some(scope) = buffer.language_scope_at(selection.start) {
3927 for (pair, enabled) in scope.brackets() {
3928 if !enabled || !pair.close {
3929 continue;
3930 }
3931
3932 if buffer.contains_str_at(selection.start, &pair.end) {
3933 let pair_start_len = pair.start.len();
3934 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3935 {
3936 selection.start -= pair_start_len;
3937 selection.end += pair.end.len();
3938
3939 return selection;
3940 }
3941 }
3942 }
3943 }
3944
3945 selection
3946 })
3947 .collect();
3948
3949 drop(buffer);
3950 self.change_selections(None, cx, |selections| selections.select(new_selections));
3951 }
3952
3953 /// Iterate the given selections, and for each one, find the smallest surrounding
3954 /// autoclose region. This uses the ordering of the selections and the autoclose
3955 /// regions to avoid repeated comparisons.
3956 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3957 &'a self,
3958 selections: impl IntoIterator<Item = Selection<D>>,
3959 buffer: &'a MultiBufferSnapshot,
3960 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3961 let mut i = 0;
3962 let mut regions = self.autoclose_regions.as_slice();
3963 selections.into_iter().map(move |selection| {
3964 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3965
3966 let mut enclosing = None;
3967 while let Some(pair_state) = regions.get(i) {
3968 if pair_state.range.end.to_offset(buffer) < range.start {
3969 regions = ®ions[i + 1..];
3970 i = 0;
3971 } else if pair_state.range.start.to_offset(buffer) > range.end {
3972 break;
3973 } else {
3974 if pair_state.selection_id == selection.id {
3975 enclosing = Some(pair_state);
3976 }
3977 i += 1;
3978 }
3979 }
3980
3981 (selection.clone(), enclosing)
3982 })
3983 }
3984
3985 /// Remove any autoclose regions that no longer contain their selection.
3986 fn invalidate_autoclose_regions(
3987 &mut self,
3988 mut selections: &[Selection<Anchor>],
3989 buffer: &MultiBufferSnapshot,
3990 ) {
3991 self.autoclose_regions.retain(|state| {
3992 let mut i = 0;
3993 while let Some(selection) = selections.get(i) {
3994 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3995 selections = &selections[1..];
3996 continue;
3997 }
3998 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3999 break;
4000 }
4001 if selection.id == state.selection_id {
4002 return true;
4003 } else {
4004 i += 1;
4005 }
4006 }
4007 false
4008 });
4009 }
4010
4011 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4012 let offset = position.to_offset(buffer);
4013 let (word_range, kind) = buffer.surrounding_word(offset, true);
4014 if offset > word_range.start && kind == Some(CharKind::Word) {
4015 Some(
4016 buffer
4017 .text_for_range(word_range.start..offset)
4018 .collect::<String>(),
4019 )
4020 } else {
4021 None
4022 }
4023 }
4024
4025 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4026 self.refresh_inlay_hints(
4027 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4028 cx,
4029 );
4030 }
4031
4032 pub fn inlay_hints_enabled(&self) -> bool {
4033 self.inlay_hint_cache.enabled
4034 }
4035
4036 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4037 if self.project.is_none() || self.mode != EditorMode::Full {
4038 return;
4039 }
4040
4041 let reason_description = reason.description();
4042 let ignore_debounce = matches!(
4043 reason,
4044 InlayHintRefreshReason::SettingsChange(_)
4045 | InlayHintRefreshReason::Toggle(_)
4046 | InlayHintRefreshReason::ExcerptsRemoved(_)
4047 );
4048 let (invalidate_cache, required_languages) = match reason {
4049 InlayHintRefreshReason::Toggle(enabled) => {
4050 self.inlay_hint_cache.enabled = enabled;
4051 if enabled {
4052 (InvalidationStrategy::RefreshRequested, None)
4053 } else {
4054 self.inlay_hint_cache.clear();
4055 self.splice_inlays(
4056 self.visible_inlay_hints(cx)
4057 .iter()
4058 .map(|inlay| inlay.id)
4059 .collect(),
4060 Vec::new(),
4061 cx,
4062 );
4063 return;
4064 }
4065 }
4066 InlayHintRefreshReason::SettingsChange(new_settings) => {
4067 match self.inlay_hint_cache.update_settings(
4068 &self.buffer,
4069 new_settings,
4070 self.visible_inlay_hints(cx),
4071 cx,
4072 ) {
4073 ControlFlow::Break(Some(InlaySplice {
4074 to_remove,
4075 to_insert,
4076 })) => {
4077 self.splice_inlays(to_remove, to_insert, cx);
4078 return;
4079 }
4080 ControlFlow::Break(None) => return,
4081 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4082 }
4083 }
4084 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4085 if let Some(InlaySplice {
4086 to_remove,
4087 to_insert,
4088 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4089 {
4090 self.splice_inlays(to_remove, to_insert, cx);
4091 }
4092 return;
4093 }
4094 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4095 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4096 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4097 }
4098 InlayHintRefreshReason::RefreshRequested => {
4099 (InvalidationStrategy::RefreshRequested, None)
4100 }
4101 };
4102
4103 if let Some(InlaySplice {
4104 to_remove,
4105 to_insert,
4106 }) = self.inlay_hint_cache.spawn_hint_refresh(
4107 reason_description,
4108 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4109 invalidate_cache,
4110 ignore_debounce,
4111 cx,
4112 ) {
4113 self.splice_inlays(to_remove, to_insert, cx);
4114 }
4115 }
4116
4117 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4118 self.display_map
4119 .read(cx)
4120 .current_inlays()
4121 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4122 .cloned()
4123 .collect()
4124 }
4125
4126 pub fn excerpts_for_inlay_hints_query(
4127 &self,
4128 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4129 cx: &mut ViewContext<Editor>,
4130 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4131 let Some(project) = self.project.as_ref() else {
4132 return HashMap::default();
4133 };
4134 let project = project.read(cx);
4135 let multi_buffer = self.buffer().read(cx);
4136 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4137 let multi_buffer_visible_start = self
4138 .scroll_manager
4139 .anchor()
4140 .anchor
4141 .to_point(&multi_buffer_snapshot);
4142 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4143 multi_buffer_visible_start
4144 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4145 Bias::Left,
4146 );
4147 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4148 multi_buffer
4149 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4150 .into_iter()
4151 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4152 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4153 let buffer = buffer_handle.read(cx);
4154 let buffer_file = project::File::from_dyn(buffer.file())?;
4155 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4156 let worktree_entry = buffer_worktree
4157 .read(cx)
4158 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4159 if worktree_entry.is_ignored {
4160 return None;
4161 }
4162
4163 let language = buffer.language()?;
4164 if let Some(restrict_to_languages) = restrict_to_languages {
4165 if !restrict_to_languages.contains(language) {
4166 return None;
4167 }
4168 }
4169 Some((
4170 excerpt_id,
4171 (
4172 buffer_handle,
4173 buffer.version().clone(),
4174 excerpt_visible_range,
4175 ),
4176 ))
4177 })
4178 .collect()
4179 }
4180
4181 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4182 TextLayoutDetails {
4183 text_system: cx.text_system().clone(),
4184 editor_style: self.style.clone().unwrap(),
4185 rem_size: cx.rem_size(),
4186 scroll_anchor: self.scroll_manager.anchor(),
4187 visible_rows: self.visible_line_count(),
4188 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4189 }
4190 }
4191
4192 fn splice_inlays(
4193 &self,
4194 to_remove: Vec<InlayId>,
4195 to_insert: Vec<Inlay>,
4196 cx: &mut ViewContext<Self>,
4197 ) {
4198 self.display_map.update(cx, |display_map, cx| {
4199 display_map.splice_inlays(to_remove, to_insert, cx);
4200 });
4201 cx.notify();
4202 }
4203
4204 fn trigger_on_type_formatting(
4205 &self,
4206 input: String,
4207 cx: &mut ViewContext<Self>,
4208 ) -> Option<Task<Result<()>>> {
4209 if input.len() != 1 {
4210 return None;
4211 }
4212
4213 let project = self.project.as_ref()?;
4214 let position = self.selections.newest_anchor().head();
4215 let (buffer, buffer_position) = self
4216 .buffer
4217 .read(cx)
4218 .text_anchor_for_position(position, cx)?;
4219
4220 let settings = language_settings::language_settings(
4221 buffer.read(cx).language_at(buffer_position).as_ref(),
4222 buffer.read(cx).file(),
4223 cx,
4224 );
4225 if !settings.use_on_type_format {
4226 return None;
4227 }
4228
4229 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4230 // hence we do LSP request & edit on host side only — add formats to host's history.
4231 let push_to_lsp_host_history = true;
4232 // If this is not the host, append its history with new edits.
4233 let push_to_client_history = project.read(cx).is_via_collab();
4234
4235 let on_type_formatting = project.update(cx, |project, cx| {
4236 project.on_type_format(
4237 buffer.clone(),
4238 buffer_position,
4239 input,
4240 push_to_lsp_host_history,
4241 cx,
4242 )
4243 });
4244 Some(cx.spawn(|editor, mut cx| async move {
4245 if let Some(transaction) = on_type_formatting.await? {
4246 if push_to_client_history {
4247 buffer
4248 .update(&mut cx, |buffer, _| {
4249 buffer.push_transaction(transaction, Instant::now());
4250 })
4251 .ok();
4252 }
4253 editor.update(&mut cx, |editor, cx| {
4254 editor.refresh_document_highlights(cx);
4255 })?;
4256 }
4257 Ok(())
4258 }))
4259 }
4260
4261 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4262 if self.pending_rename.is_some() {
4263 return;
4264 }
4265
4266 let Some(provider) = self.completion_provider.as_ref() else {
4267 return;
4268 };
4269
4270 let position = self.selections.newest_anchor().head();
4271 let (buffer, buffer_position) =
4272 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4273 output
4274 } else {
4275 return;
4276 };
4277
4278 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4279 let is_followup_invoke = {
4280 let context_menu_state = self.context_menu.read();
4281 matches!(
4282 context_menu_state.deref(),
4283 Some(ContextMenu::Completions(_))
4284 )
4285 };
4286 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4287 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4288 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4289 CompletionTriggerKind::TRIGGER_CHARACTER
4290 }
4291
4292 _ => CompletionTriggerKind::INVOKED,
4293 };
4294 let completion_context = CompletionContext {
4295 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4296 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4297 Some(String::from(trigger))
4298 } else {
4299 None
4300 }
4301 }),
4302 trigger_kind,
4303 };
4304 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4305 let sort_completions = provider.sort_completions();
4306
4307 let id = post_inc(&mut self.next_completion_id);
4308 let task = cx.spawn(|this, mut cx| {
4309 async move {
4310 this.update(&mut cx, |this, _| {
4311 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4312 })?;
4313 let completions = completions.await.log_err();
4314 let menu = if let Some(completions) = completions {
4315 let mut menu = CompletionsMenu {
4316 id,
4317 sort_completions,
4318 initial_position: position,
4319 match_candidates: completions
4320 .iter()
4321 .enumerate()
4322 .map(|(id, completion)| {
4323 StringMatchCandidate::new(
4324 id,
4325 completion.label.text[completion.label.filter_range.clone()]
4326 .into(),
4327 )
4328 })
4329 .collect(),
4330 buffer: buffer.clone(),
4331 completions: Arc::new(RwLock::new(completions.into())),
4332 matches: Vec::new().into(),
4333 selected_item: 0,
4334 scroll_handle: UniformListScrollHandle::new(),
4335 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4336 DebouncedDelay::new(),
4337 )),
4338 };
4339 menu.filter(query.as_deref(), cx.background_executor().clone())
4340 .await;
4341
4342 if menu.matches.is_empty() {
4343 None
4344 } else {
4345 this.update(&mut cx, |editor, cx| {
4346 let completions = menu.completions.clone();
4347 let matches = menu.matches.clone();
4348
4349 let delay_ms = EditorSettings::get_global(cx)
4350 .completion_documentation_secondary_query_debounce;
4351 let delay = Duration::from_millis(delay_ms);
4352 editor
4353 .completion_documentation_pre_resolve_debounce
4354 .fire_new(delay, cx, |editor, cx| {
4355 CompletionsMenu::pre_resolve_completion_documentation(
4356 buffer,
4357 completions,
4358 matches,
4359 editor,
4360 cx,
4361 )
4362 });
4363 })
4364 .ok();
4365 Some(menu)
4366 }
4367 } else {
4368 None
4369 };
4370
4371 this.update(&mut cx, |this, cx| {
4372 let mut context_menu = this.context_menu.write();
4373 match context_menu.as_ref() {
4374 None => {}
4375
4376 Some(ContextMenu::Completions(prev_menu)) => {
4377 if prev_menu.id > id {
4378 return;
4379 }
4380 }
4381
4382 _ => return,
4383 }
4384
4385 if this.focus_handle.is_focused(cx) && menu.is_some() {
4386 let menu = menu.unwrap();
4387 *context_menu = Some(ContextMenu::Completions(menu));
4388 drop(context_menu);
4389 this.discard_inline_completion(false, cx);
4390 cx.notify();
4391 } else if this.completion_tasks.len() <= 1 {
4392 // If there are no more completion tasks and the last menu was
4393 // empty, we should hide it. If it was already hidden, we should
4394 // also show the copilot completion when available.
4395 drop(context_menu);
4396 if this.hide_context_menu(cx).is_none() {
4397 this.update_visible_inline_completion(cx);
4398 }
4399 }
4400 })?;
4401
4402 Ok::<_, anyhow::Error>(())
4403 }
4404 .log_err()
4405 });
4406
4407 self.completion_tasks.push((id, task));
4408 }
4409
4410 pub fn confirm_completion(
4411 &mut self,
4412 action: &ConfirmCompletion,
4413 cx: &mut ViewContext<Self>,
4414 ) -> Option<Task<Result<()>>> {
4415 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4416 }
4417
4418 pub fn compose_completion(
4419 &mut self,
4420 action: &ComposeCompletion,
4421 cx: &mut ViewContext<Self>,
4422 ) -> Option<Task<Result<()>>> {
4423 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4424 }
4425
4426 fn do_completion(
4427 &mut self,
4428 item_ix: Option<usize>,
4429 intent: CompletionIntent,
4430 cx: &mut ViewContext<Self>,
4431 ) -> Option<Task<anyhow::Result<()>>> {
4432 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4433 menu
4434 } else {
4435 return None;
4436 };
4437
4438 let mut resolve_task_store = completions_menu
4439 .selected_completion_documentation_resolve_debounce
4440 .lock();
4441 let selected_completion_resolve = resolve_task_store.start_now();
4442 let menu_pre_resolve = self
4443 .completion_documentation_pre_resolve_debounce
4444 .start_now();
4445 drop(resolve_task_store);
4446
4447 Some(cx.spawn(|editor, mut cx| async move {
4448 match (selected_completion_resolve, menu_pre_resolve) {
4449 (None, None) => {}
4450 (Some(resolve), None) | (None, Some(resolve)) => resolve.await,
4451 (Some(resolve_1), Some(resolve_2)) => {
4452 futures::join!(resolve_1, resolve_2);
4453 }
4454 }
4455 if let Some(apply_edits_task) = editor.update(&mut cx, |editor, cx| {
4456 editor.apply_resolved_completion(completions_menu, item_ix, intent, cx)
4457 })? {
4458 apply_edits_task.await?;
4459 }
4460 Ok(())
4461 }))
4462 }
4463
4464 fn apply_resolved_completion(
4465 &mut self,
4466 completions_menu: CompletionsMenu,
4467 item_ix: Option<usize>,
4468 intent: CompletionIntent,
4469 cx: &mut ViewContext<'_, Editor>,
4470 ) -> Option<Task<anyhow::Result<Option<language::Transaction>>>> {
4471 use language::ToOffset as _;
4472
4473 let mat = completions_menu
4474 .matches
4475 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4476 let buffer_handle = completions_menu.buffer;
4477 let completions = completions_menu.completions.read();
4478 let completion = completions.get(mat.candidate_id)?;
4479 cx.stop_propagation();
4480
4481 let snippet;
4482 let text;
4483
4484 if completion.is_snippet() {
4485 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4486 text = snippet.as_ref().unwrap().text.clone();
4487 } else {
4488 snippet = None;
4489 text = completion.new_text.clone();
4490 };
4491 let selections = self.selections.all::<usize>(cx);
4492 let buffer = buffer_handle.read(cx);
4493 let old_range = completion.old_range.to_offset(buffer);
4494 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4495
4496 let newest_selection = self.selections.newest_anchor();
4497 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4498 return None;
4499 }
4500
4501 let lookbehind = newest_selection
4502 .start
4503 .text_anchor
4504 .to_offset(buffer)
4505 .saturating_sub(old_range.start);
4506 let lookahead = old_range
4507 .end
4508 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4509 let mut common_prefix_len = old_text
4510 .bytes()
4511 .zip(text.bytes())
4512 .take_while(|(a, b)| a == b)
4513 .count();
4514
4515 let snapshot = self.buffer.read(cx).snapshot(cx);
4516 let mut range_to_replace: Option<Range<isize>> = None;
4517 let mut ranges = Vec::new();
4518 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4519 for selection in &selections {
4520 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4521 let start = selection.start.saturating_sub(lookbehind);
4522 let end = selection.end + lookahead;
4523 if selection.id == newest_selection.id {
4524 range_to_replace = Some(
4525 ((start + common_prefix_len) as isize - selection.start as isize)
4526 ..(end as isize - selection.start as isize),
4527 );
4528 }
4529 ranges.push(start + common_prefix_len..end);
4530 } else {
4531 common_prefix_len = 0;
4532 ranges.clear();
4533 ranges.extend(selections.iter().map(|s| {
4534 if s.id == newest_selection.id {
4535 range_to_replace = Some(
4536 old_range.start.to_offset_utf16(&snapshot).0 as isize
4537 - selection.start as isize
4538 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4539 - selection.start as isize,
4540 );
4541 old_range.clone()
4542 } else {
4543 s.start..s.end
4544 }
4545 }));
4546 break;
4547 }
4548 if !self.linked_edit_ranges.is_empty() {
4549 let start_anchor = snapshot.anchor_before(selection.head());
4550 let end_anchor = snapshot.anchor_after(selection.tail());
4551 if let Some(ranges) = self
4552 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4553 {
4554 for (buffer, edits) in ranges {
4555 linked_edits.entry(buffer.clone()).or_default().extend(
4556 edits
4557 .into_iter()
4558 .map(|range| (range, text[common_prefix_len..].to_owned())),
4559 );
4560 }
4561 }
4562 }
4563 }
4564 let text = &text[common_prefix_len..];
4565
4566 cx.emit(EditorEvent::InputHandled {
4567 utf16_range_to_replace: range_to_replace,
4568 text: text.into(),
4569 });
4570
4571 self.transact(cx, |this, cx| {
4572 if let Some(mut snippet) = snippet {
4573 snippet.text = text.to_string();
4574 for tabstop in snippet.tabstops.iter_mut().flatten() {
4575 tabstop.start -= common_prefix_len as isize;
4576 tabstop.end -= common_prefix_len as isize;
4577 }
4578
4579 this.insert_snippet(&ranges, snippet, cx).log_err();
4580 } else {
4581 this.buffer.update(cx, |buffer, cx| {
4582 buffer.edit(
4583 ranges.iter().map(|range| (range.clone(), text)),
4584 this.autoindent_mode.clone(),
4585 cx,
4586 );
4587 });
4588 }
4589 for (buffer, edits) in linked_edits {
4590 buffer.update(cx, |buffer, cx| {
4591 let snapshot = buffer.snapshot();
4592 let edits = edits
4593 .into_iter()
4594 .map(|(range, text)| {
4595 use text::ToPoint as TP;
4596 let end_point = TP::to_point(&range.end, &snapshot);
4597 let start_point = TP::to_point(&range.start, &snapshot);
4598 (start_point..end_point, text)
4599 })
4600 .sorted_by_key(|(range, _)| range.start)
4601 .collect::<Vec<_>>();
4602 buffer.edit(edits, None, cx);
4603 })
4604 }
4605
4606 this.refresh_inline_completion(true, false, cx);
4607 });
4608
4609 let show_new_completions_on_confirm = completion
4610 .confirm
4611 .as_ref()
4612 .map_or(false, |confirm| confirm(intent, cx));
4613 if show_new_completions_on_confirm {
4614 self.show_completions(&ShowCompletions { trigger: None }, cx);
4615 }
4616
4617 let provider = self.completion_provider.as_ref()?;
4618 let apply_edits = provider.apply_additional_edits_for_completion(
4619 buffer_handle,
4620 completion.clone(),
4621 true,
4622 cx,
4623 );
4624
4625 let editor_settings = EditorSettings::get_global(cx);
4626 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4627 // After the code completion is finished, users often want to know what signatures are needed.
4628 // so we should automatically call signature_help
4629 self.show_signature_help(&ShowSignatureHelp, cx);
4630 }
4631 Some(apply_edits)
4632 }
4633
4634 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4635 let mut context_menu = self.context_menu.write();
4636 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4637 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4638 // Toggle if we're selecting the same one
4639 *context_menu = None;
4640 cx.notify();
4641 return;
4642 } else {
4643 // Otherwise, clear it and start a new one
4644 *context_menu = None;
4645 cx.notify();
4646 }
4647 }
4648 drop(context_menu);
4649 let snapshot = self.snapshot(cx);
4650 let deployed_from_indicator = action.deployed_from_indicator;
4651 let mut task = self.code_actions_task.take();
4652 let action = action.clone();
4653 cx.spawn(|editor, mut cx| async move {
4654 while let Some(prev_task) = task {
4655 prev_task.await.log_err();
4656 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4657 }
4658
4659 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4660 if editor.focus_handle.is_focused(cx) {
4661 let multibuffer_point = action
4662 .deployed_from_indicator
4663 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4664 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4665 let (buffer, buffer_row) = snapshot
4666 .buffer_snapshot
4667 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4668 .and_then(|(buffer_snapshot, range)| {
4669 editor
4670 .buffer
4671 .read(cx)
4672 .buffer(buffer_snapshot.remote_id())
4673 .map(|buffer| (buffer, range.start.row))
4674 })?;
4675 let (_, code_actions) = editor
4676 .available_code_actions
4677 .clone()
4678 .and_then(|(location, code_actions)| {
4679 let snapshot = location.buffer.read(cx).snapshot();
4680 let point_range = location.range.to_point(&snapshot);
4681 let point_range = point_range.start.row..=point_range.end.row;
4682 if point_range.contains(&buffer_row) {
4683 Some((location, code_actions))
4684 } else {
4685 None
4686 }
4687 })
4688 .unzip();
4689 let buffer_id = buffer.read(cx).remote_id();
4690 let tasks = editor
4691 .tasks
4692 .get(&(buffer_id, buffer_row))
4693 .map(|t| Arc::new(t.to_owned()));
4694 if tasks.is_none() && code_actions.is_none() {
4695 return None;
4696 }
4697
4698 editor.completion_tasks.clear();
4699 editor.discard_inline_completion(false, cx);
4700 let task_context =
4701 tasks
4702 .as_ref()
4703 .zip(editor.project.clone())
4704 .map(|(tasks, project)| {
4705 let position = Point::new(buffer_row, tasks.column);
4706 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4707 let location = Location {
4708 buffer: buffer.clone(),
4709 range: range_start..range_start,
4710 };
4711 // Fill in the environmental variables from the tree-sitter captures
4712 let mut captured_task_variables = TaskVariables::default();
4713 for (capture_name, value) in tasks.extra_variables.clone() {
4714 captured_task_variables.insert(
4715 task::VariableName::Custom(capture_name.into()),
4716 value.clone(),
4717 );
4718 }
4719 project.update(cx, |project, cx| {
4720 project.task_context_for_location(
4721 captured_task_variables,
4722 location,
4723 cx,
4724 )
4725 })
4726 });
4727
4728 Some(cx.spawn(|editor, mut cx| async move {
4729 let task_context = match task_context {
4730 Some(task_context) => task_context.await,
4731 None => None,
4732 };
4733 let resolved_tasks =
4734 tasks.zip(task_context).map(|(tasks, task_context)| {
4735 Arc::new(ResolvedTasks {
4736 templates: tasks
4737 .templates
4738 .iter()
4739 .filter_map(|(kind, template)| {
4740 template
4741 .resolve_task(&kind.to_id_base(), &task_context)
4742 .map(|task| (kind.clone(), task))
4743 })
4744 .collect(),
4745 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4746 multibuffer_point.row,
4747 tasks.column,
4748 )),
4749 })
4750 });
4751 let spawn_straight_away = resolved_tasks
4752 .as_ref()
4753 .map_or(false, |tasks| tasks.templates.len() == 1)
4754 && code_actions
4755 .as_ref()
4756 .map_or(true, |actions| actions.is_empty());
4757 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4758 *editor.context_menu.write() =
4759 Some(ContextMenu::CodeActions(CodeActionsMenu {
4760 buffer,
4761 actions: CodeActionContents {
4762 tasks: resolved_tasks,
4763 actions: code_actions,
4764 },
4765 selected_item: Default::default(),
4766 scroll_handle: UniformListScrollHandle::default(),
4767 deployed_from_indicator,
4768 }));
4769 if spawn_straight_away {
4770 if let Some(task) = editor.confirm_code_action(
4771 &ConfirmCodeAction { item_ix: Some(0) },
4772 cx,
4773 ) {
4774 cx.notify();
4775 return task;
4776 }
4777 }
4778 cx.notify();
4779 Task::ready(Ok(()))
4780 }) {
4781 task.await
4782 } else {
4783 Ok(())
4784 }
4785 }))
4786 } else {
4787 Some(Task::ready(Ok(())))
4788 }
4789 })?;
4790 if let Some(task) = spawned_test_task {
4791 task.await?;
4792 }
4793
4794 Ok::<_, anyhow::Error>(())
4795 })
4796 .detach_and_log_err(cx);
4797 }
4798
4799 pub fn confirm_code_action(
4800 &mut self,
4801 action: &ConfirmCodeAction,
4802 cx: &mut ViewContext<Self>,
4803 ) -> Option<Task<Result<()>>> {
4804 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4805 menu
4806 } else {
4807 return None;
4808 };
4809 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4810 let action = actions_menu.actions.get(action_ix)?;
4811 let title = action.label();
4812 let buffer = actions_menu.buffer;
4813 let workspace = self.workspace()?;
4814
4815 match action {
4816 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4817 workspace.update(cx, |workspace, cx| {
4818 workspace::tasks::schedule_resolved_task(
4819 workspace,
4820 task_source_kind,
4821 resolved_task,
4822 false,
4823 cx,
4824 );
4825
4826 Some(Task::ready(Ok(())))
4827 })
4828 }
4829 CodeActionsItem::CodeAction {
4830 excerpt_id,
4831 action,
4832 provider,
4833 } => {
4834 let apply_code_action =
4835 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4836 let workspace = workspace.downgrade();
4837 Some(cx.spawn(|editor, cx| async move {
4838 let project_transaction = apply_code_action.await?;
4839 Self::open_project_transaction(
4840 &editor,
4841 workspace,
4842 project_transaction,
4843 title,
4844 cx,
4845 )
4846 .await
4847 }))
4848 }
4849 }
4850 }
4851
4852 pub async fn open_project_transaction(
4853 this: &WeakView<Editor>,
4854 workspace: WeakView<Workspace>,
4855 transaction: ProjectTransaction,
4856 title: String,
4857 mut cx: AsyncWindowContext,
4858 ) -> Result<()> {
4859 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4860 cx.update(|cx| {
4861 entries.sort_unstable_by_key(|(buffer, _)| {
4862 buffer.read(cx).file().map(|f| f.path().clone())
4863 });
4864 })?;
4865
4866 // If the project transaction's edits are all contained within this editor, then
4867 // avoid opening a new editor to display them.
4868
4869 if let Some((buffer, transaction)) = entries.first() {
4870 if entries.len() == 1 {
4871 let excerpt = this.update(&mut cx, |editor, cx| {
4872 editor
4873 .buffer()
4874 .read(cx)
4875 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4876 })?;
4877 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4878 if excerpted_buffer == *buffer {
4879 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4880 let excerpt_range = excerpt_range.to_offset(buffer);
4881 buffer
4882 .edited_ranges_for_transaction::<usize>(transaction)
4883 .all(|range| {
4884 excerpt_range.start <= range.start
4885 && excerpt_range.end >= range.end
4886 })
4887 })?;
4888
4889 if all_edits_within_excerpt {
4890 return Ok(());
4891 }
4892 }
4893 }
4894 }
4895 } else {
4896 return Ok(());
4897 }
4898
4899 let mut ranges_to_highlight = Vec::new();
4900 let excerpt_buffer = cx.new_model(|cx| {
4901 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4902 for (buffer_handle, transaction) in &entries {
4903 let buffer = buffer_handle.read(cx);
4904 ranges_to_highlight.extend(
4905 multibuffer.push_excerpts_with_context_lines(
4906 buffer_handle.clone(),
4907 buffer
4908 .edited_ranges_for_transaction::<usize>(transaction)
4909 .collect(),
4910 DEFAULT_MULTIBUFFER_CONTEXT,
4911 cx,
4912 ),
4913 );
4914 }
4915 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4916 multibuffer
4917 })?;
4918
4919 workspace.update(&mut cx, |workspace, cx| {
4920 let project = workspace.project().clone();
4921 let editor =
4922 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4923 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4924 editor.update(cx, |editor, cx| {
4925 editor.highlight_background::<Self>(
4926 &ranges_to_highlight,
4927 |theme| theme.editor_highlighted_line_background,
4928 cx,
4929 );
4930 });
4931 })?;
4932
4933 Ok(())
4934 }
4935
4936 pub fn push_code_action_provider(
4937 &mut self,
4938 provider: Arc<dyn CodeActionProvider>,
4939 cx: &mut ViewContext<Self>,
4940 ) {
4941 self.code_action_providers.push(provider);
4942 self.refresh_code_actions(cx);
4943 }
4944
4945 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4946 let buffer = self.buffer.read(cx);
4947 let newest_selection = self.selections.newest_anchor().clone();
4948 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4949 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4950 if start_buffer != end_buffer {
4951 return None;
4952 }
4953
4954 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4955 cx.background_executor()
4956 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4957 .await;
4958
4959 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4960 let providers = this.code_action_providers.clone();
4961 let tasks = this
4962 .code_action_providers
4963 .iter()
4964 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4965 .collect::<Vec<_>>();
4966 (providers, tasks)
4967 })?;
4968
4969 let mut actions = Vec::new();
4970 for (provider, provider_actions) in
4971 providers.into_iter().zip(future::join_all(tasks).await)
4972 {
4973 if let Some(provider_actions) = provider_actions.log_err() {
4974 actions.extend(provider_actions.into_iter().map(|action| {
4975 AvailableCodeAction {
4976 excerpt_id: newest_selection.start.excerpt_id,
4977 action,
4978 provider: provider.clone(),
4979 }
4980 }));
4981 }
4982 }
4983
4984 this.update(&mut cx, |this, cx| {
4985 this.available_code_actions = if actions.is_empty() {
4986 None
4987 } else {
4988 Some((
4989 Location {
4990 buffer: start_buffer,
4991 range: start..end,
4992 },
4993 actions.into(),
4994 ))
4995 };
4996 cx.notify();
4997 })
4998 }));
4999 None
5000 }
5001
5002 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
5003 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
5004 self.show_git_blame_inline = false;
5005
5006 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
5007 cx.background_executor().timer(delay).await;
5008
5009 this.update(&mut cx, |this, cx| {
5010 this.show_git_blame_inline = true;
5011 cx.notify();
5012 })
5013 .log_err();
5014 }));
5015 }
5016 }
5017
5018 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
5019 if self.pending_rename.is_some() {
5020 return None;
5021 }
5022
5023 let project = self.project.clone()?;
5024 let buffer = self.buffer.read(cx);
5025 let newest_selection = self.selections.newest_anchor().clone();
5026 let cursor_position = newest_selection.head();
5027 let (cursor_buffer, cursor_buffer_position) =
5028 buffer.text_anchor_for_position(cursor_position, cx)?;
5029 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
5030 if cursor_buffer != tail_buffer {
5031 return None;
5032 }
5033
5034 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5035 cx.background_executor()
5036 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5037 .await;
5038
5039 let highlights = if let Some(highlights) = project
5040 .update(&mut cx, |project, cx| {
5041 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5042 })
5043 .log_err()
5044 {
5045 highlights.await.log_err()
5046 } else {
5047 None
5048 };
5049
5050 if let Some(highlights) = highlights {
5051 this.update(&mut cx, |this, cx| {
5052 if this.pending_rename.is_some() {
5053 return;
5054 }
5055
5056 let buffer_id = cursor_position.buffer_id;
5057 let buffer = this.buffer.read(cx);
5058 if !buffer
5059 .text_anchor_for_position(cursor_position, cx)
5060 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5061 {
5062 return;
5063 }
5064
5065 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5066 let mut write_ranges = Vec::new();
5067 let mut read_ranges = Vec::new();
5068 for highlight in highlights {
5069 for (excerpt_id, excerpt_range) in
5070 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5071 {
5072 let start = highlight
5073 .range
5074 .start
5075 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5076 let end = highlight
5077 .range
5078 .end
5079 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5080 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5081 continue;
5082 }
5083
5084 let range = Anchor {
5085 buffer_id,
5086 excerpt_id,
5087 text_anchor: start,
5088 }..Anchor {
5089 buffer_id,
5090 excerpt_id,
5091 text_anchor: end,
5092 };
5093 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5094 write_ranges.push(range);
5095 } else {
5096 read_ranges.push(range);
5097 }
5098 }
5099 }
5100
5101 this.highlight_background::<DocumentHighlightRead>(
5102 &read_ranges,
5103 |theme| theme.editor_document_highlight_read_background,
5104 cx,
5105 );
5106 this.highlight_background::<DocumentHighlightWrite>(
5107 &write_ranges,
5108 |theme| theme.editor_document_highlight_write_background,
5109 cx,
5110 );
5111 cx.notify();
5112 })
5113 .log_err();
5114 }
5115 }));
5116 None
5117 }
5118
5119 pub fn refresh_inline_completion(
5120 &mut self,
5121 debounce: bool,
5122 user_requested: bool,
5123 cx: &mut ViewContext<Self>,
5124 ) -> Option<()> {
5125 let provider = self.inline_completion_provider()?;
5126 let cursor = self.selections.newest_anchor().head();
5127 let (buffer, cursor_buffer_position) =
5128 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5129
5130 if !user_requested
5131 && (!self.enable_inline_completions
5132 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5133 {
5134 self.discard_inline_completion(false, cx);
5135 return None;
5136 }
5137
5138 self.update_visible_inline_completion(cx);
5139 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5140 Some(())
5141 }
5142
5143 fn cycle_inline_completion(
5144 &mut self,
5145 direction: Direction,
5146 cx: &mut ViewContext<Self>,
5147 ) -> Option<()> {
5148 let provider = self.inline_completion_provider()?;
5149 let cursor = self.selections.newest_anchor().head();
5150 let (buffer, cursor_buffer_position) =
5151 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5152 if !self.enable_inline_completions
5153 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5154 {
5155 return None;
5156 }
5157
5158 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5159 self.update_visible_inline_completion(cx);
5160
5161 Some(())
5162 }
5163
5164 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5165 if !self.has_active_inline_completion(cx) {
5166 self.refresh_inline_completion(false, true, cx);
5167 return;
5168 }
5169
5170 self.update_visible_inline_completion(cx);
5171 }
5172
5173 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5174 self.show_cursor_names(cx);
5175 }
5176
5177 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5178 self.show_cursor_names = true;
5179 cx.notify();
5180 cx.spawn(|this, mut cx| async move {
5181 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5182 this.update(&mut cx, |this, cx| {
5183 this.show_cursor_names = false;
5184 cx.notify()
5185 })
5186 .ok()
5187 })
5188 .detach();
5189 }
5190
5191 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5192 if self.has_active_inline_completion(cx) {
5193 self.cycle_inline_completion(Direction::Next, cx);
5194 } else {
5195 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5196 if is_copilot_disabled {
5197 cx.propagate();
5198 }
5199 }
5200 }
5201
5202 pub fn previous_inline_completion(
5203 &mut self,
5204 _: &PreviousInlineCompletion,
5205 cx: &mut ViewContext<Self>,
5206 ) {
5207 if self.has_active_inline_completion(cx) {
5208 self.cycle_inline_completion(Direction::Prev, cx);
5209 } else {
5210 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5211 if is_copilot_disabled {
5212 cx.propagate();
5213 }
5214 }
5215 }
5216
5217 pub fn accept_inline_completion(
5218 &mut self,
5219 _: &AcceptInlineCompletion,
5220 cx: &mut ViewContext<Self>,
5221 ) {
5222 let Some(completion) = self.take_active_inline_completion(cx) else {
5223 return;
5224 };
5225 if let Some(provider) = self.inline_completion_provider() {
5226 provider.accept(cx);
5227 }
5228
5229 cx.emit(EditorEvent::InputHandled {
5230 utf16_range_to_replace: None,
5231 text: completion.text.to_string().into(),
5232 });
5233
5234 if let Some(range) = completion.delete_range {
5235 self.change_selections(None, cx, |s| s.select_ranges([range]))
5236 }
5237 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5238 self.refresh_inline_completion(true, true, cx);
5239 cx.notify();
5240 }
5241
5242 pub fn accept_partial_inline_completion(
5243 &mut self,
5244 _: &AcceptPartialInlineCompletion,
5245 cx: &mut ViewContext<Self>,
5246 ) {
5247 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5248 if let Some(completion) = self.take_active_inline_completion(cx) {
5249 let mut partial_completion = completion
5250 .text
5251 .chars()
5252 .by_ref()
5253 .take_while(|c| c.is_alphabetic())
5254 .collect::<String>();
5255 if partial_completion.is_empty() {
5256 partial_completion = completion
5257 .text
5258 .chars()
5259 .by_ref()
5260 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5261 .collect::<String>();
5262 }
5263
5264 cx.emit(EditorEvent::InputHandled {
5265 utf16_range_to_replace: None,
5266 text: partial_completion.clone().into(),
5267 });
5268
5269 if let Some(range) = completion.delete_range {
5270 self.change_selections(None, cx, |s| s.select_ranges([range]))
5271 }
5272 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5273
5274 self.refresh_inline_completion(true, true, cx);
5275 cx.notify();
5276 }
5277 }
5278 }
5279
5280 fn discard_inline_completion(
5281 &mut self,
5282 should_report_inline_completion_event: bool,
5283 cx: &mut ViewContext<Self>,
5284 ) -> bool {
5285 if let Some(provider) = self.inline_completion_provider() {
5286 provider.discard(should_report_inline_completion_event, cx);
5287 }
5288
5289 self.take_active_inline_completion(cx).is_some()
5290 }
5291
5292 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5293 if let Some(completion) = self.active_inline_completion.as_ref() {
5294 let buffer = self.buffer.read(cx).read(cx);
5295 completion.position.is_valid(&buffer)
5296 } else {
5297 false
5298 }
5299 }
5300
5301 fn take_active_inline_completion(
5302 &mut self,
5303 cx: &mut ViewContext<Self>,
5304 ) -> Option<CompletionState> {
5305 let completion = self.active_inline_completion.take()?;
5306 let render_inlay_ids = completion.render_inlay_ids.clone();
5307 self.display_map.update(cx, |map, cx| {
5308 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5309 });
5310 let buffer = self.buffer.read(cx).read(cx);
5311
5312 if completion.position.is_valid(&buffer) {
5313 Some(completion)
5314 } else {
5315 None
5316 }
5317 }
5318
5319 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5320 let selection = self.selections.newest_anchor();
5321 let cursor = selection.head();
5322
5323 let excerpt_id = cursor.excerpt_id;
5324
5325 if self.context_menu.read().is_none()
5326 && self.completion_tasks.is_empty()
5327 && selection.start == selection.end
5328 {
5329 if let Some(provider) = self.inline_completion_provider() {
5330 if let Some((buffer, cursor_buffer_position)) =
5331 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5332 {
5333 if let Some(proposal) =
5334 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5335 {
5336 let mut to_remove = Vec::new();
5337 if let Some(completion) = self.active_inline_completion.take() {
5338 to_remove.extend(completion.render_inlay_ids.iter());
5339 }
5340
5341 let to_add = proposal
5342 .inlays
5343 .iter()
5344 .filter_map(|inlay| {
5345 let snapshot = self.buffer.read(cx).snapshot(cx);
5346 let id = post_inc(&mut self.next_inlay_id);
5347 match inlay {
5348 InlayProposal::Hint(position, hint) => {
5349 let position =
5350 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5351 Some(Inlay::hint(id, position, hint))
5352 }
5353 InlayProposal::Suggestion(position, text) => {
5354 let position =
5355 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5356 Some(Inlay::suggestion(id, position, text.clone()))
5357 }
5358 }
5359 })
5360 .collect_vec();
5361
5362 self.active_inline_completion = Some(CompletionState {
5363 position: cursor,
5364 text: proposal.text,
5365 delete_range: proposal.delete_range.and_then(|range| {
5366 let snapshot = self.buffer.read(cx).snapshot(cx);
5367 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5368 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5369 Some(start?..end?)
5370 }),
5371 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5372 });
5373
5374 self.display_map
5375 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5376
5377 cx.notify();
5378 return;
5379 }
5380 }
5381 }
5382 }
5383
5384 self.discard_inline_completion(false, cx);
5385 }
5386
5387 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5388 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5389 }
5390
5391 fn render_code_actions_indicator(
5392 &self,
5393 _style: &EditorStyle,
5394 row: DisplayRow,
5395 is_active: bool,
5396 cx: &mut ViewContext<Self>,
5397 ) -> Option<IconButton> {
5398 if self.available_code_actions.is_some() {
5399 Some(
5400 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5401 .shape(ui::IconButtonShape::Square)
5402 .icon_size(IconSize::XSmall)
5403 .icon_color(Color::Muted)
5404 .selected(is_active)
5405 .tooltip({
5406 let focus_handle = self.focus_handle.clone();
5407 move |cx| {
5408 Tooltip::for_action_in(
5409 "Toggle Code Actions",
5410 &ToggleCodeActions {
5411 deployed_from_indicator: None,
5412 },
5413 &focus_handle,
5414 cx,
5415 )
5416 }
5417 })
5418 .on_click(cx.listener(move |editor, _e, cx| {
5419 editor.focus(cx);
5420 editor.toggle_code_actions(
5421 &ToggleCodeActions {
5422 deployed_from_indicator: Some(row),
5423 },
5424 cx,
5425 );
5426 })),
5427 )
5428 } else {
5429 None
5430 }
5431 }
5432
5433 fn clear_tasks(&mut self) {
5434 self.tasks.clear()
5435 }
5436
5437 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5438 if self.tasks.insert(key, value).is_some() {
5439 // This case should hopefully be rare, but just in case...
5440 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5441 }
5442 }
5443
5444 fn render_run_indicator(
5445 &self,
5446 _style: &EditorStyle,
5447 is_active: bool,
5448 row: DisplayRow,
5449 cx: &mut ViewContext<Self>,
5450 ) -> IconButton {
5451 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5452 .shape(ui::IconButtonShape::Square)
5453 .icon_size(IconSize::XSmall)
5454 .icon_color(Color::Muted)
5455 .selected(is_active)
5456 .on_click(cx.listener(move |editor, _e, cx| {
5457 editor.focus(cx);
5458 editor.toggle_code_actions(
5459 &ToggleCodeActions {
5460 deployed_from_indicator: Some(row),
5461 },
5462 cx,
5463 );
5464 }))
5465 }
5466
5467 pub fn context_menu_visible(&self) -> bool {
5468 self.context_menu
5469 .read()
5470 .as_ref()
5471 .map_or(false, |menu| menu.visible())
5472 }
5473
5474 fn render_context_menu(
5475 &self,
5476 cursor_position: DisplayPoint,
5477 style: &EditorStyle,
5478 max_height: Pixels,
5479 cx: &mut ViewContext<Editor>,
5480 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5481 self.context_menu.read().as_ref().map(|menu| {
5482 menu.render(
5483 cursor_position,
5484 style,
5485 max_height,
5486 self.workspace.as_ref().map(|(w, _)| w.clone()),
5487 cx,
5488 )
5489 })
5490 }
5491
5492 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5493 cx.notify();
5494 self.completion_tasks.clear();
5495 let context_menu = self.context_menu.write().take();
5496 if context_menu.is_some() {
5497 self.update_visible_inline_completion(cx);
5498 }
5499 context_menu
5500 }
5501
5502 pub fn insert_snippet(
5503 &mut self,
5504 insertion_ranges: &[Range<usize>],
5505 snippet: Snippet,
5506 cx: &mut ViewContext<Self>,
5507 ) -> Result<()> {
5508 struct Tabstop<T> {
5509 is_end_tabstop: bool,
5510 ranges: Vec<Range<T>>,
5511 }
5512
5513 let tabstops = self.buffer.update(cx, |buffer, cx| {
5514 let snippet_text: Arc<str> = snippet.text.clone().into();
5515 buffer.edit(
5516 insertion_ranges
5517 .iter()
5518 .cloned()
5519 .map(|range| (range, snippet_text.clone())),
5520 Some(AutoindentMode::EachLine),
5521 cx,
5522 );
5523
5524 let snapshot = &*buffer.read(cx);
5525 let snippet = &snippet;
5526 snippet
5527 .tabstops
5528 .iter()
5529 .map(|tabstop| {
5530 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5531 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5532 });
5533 let mut tabstop_ranges = tabstop
5534 .iter()
5535 .flat_map(|tabstop_range| {
5536 let mut delta = 0_isize;
5537 insertion_ranges.iter().map(move |insertion_range| {
5538 let insertion_start = insertion_range.start as isize + delta;
5539 delta +=
5540 snippet.text.len() as isize - insertion_range.len() as isize;
5541
5542 let start = ((insertion_start + tabstop_range.start) as usize)
5543 .min(snapshot.len());
5544 let end = ((insertion_start + tabstop_range.end) as usize)
5545 .min(snapshot.len());
5546 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5547 })
5548 })
5549 .collect::<Vec<_>>();
5550 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5551
5552 Tabstop {
5553 is_end_tabstop,
5554 ranges: tabstop_ranges,
5555 }
5556 })
5557 .collect::<Vec<_>>()
5558 });
5559 if let Some(tabstop) = tabstops.first() {
5560 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5561 s.select_ranges(tabstop.ranges.iter().cloned());
5562 });
5563
5564 // If we're already at the last tabstop and it's at the end of the snippet,
5565 // we're done, we don't need to keep the state around.
5566 if !tabstop.is_end_tabstop {
5567 let ranges = tabstops
5568 .into_iter()
5569 .map(|tabstop| tabstop.ranges)
5570 .collect::<Vec<_>>();
5571 self.snippet_stack.push(SnippetState {
5572 active_index: 0,
5573 ranges,
5574 });
5575 }
5576
5577 // Check whether the just-entered snippet ends with an auto-closable bracket.
5578 if self.autoclose_regions.is_empty() {
5579 let snapshot = self.buffer.read(cx).snapshot(cx);
5580 for selection in &mut self.selections.all::<Point>(cx) {
5581 let selection_head = selection.head();
5582 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5583 continue;
5584 };
5585
5586 let mut bracket_pair = None;
5587 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5588 let prev_chars = snapshot
5589 .reversed_chars_at(selection_head)
5590 .collect::<String>();
5591 for (pair, enabled) in scope.brackets() {
5592 if enabled
5593 && pair.close
5594 && prev_chars.starts_with(pair.start.as_str())
5595 && next_chars.starts_with(pair.end.as_str())
5596 {
5597 bracket_pair = Some(pair.clone());
5598 break;
5599 }
5600 }
5601 if let Some(pair) = bracket_pair {
5602 let start = snapshot.anchor_after(selection_head);
5603 let end = snapshot.anchor_after(selection_head);
5604 self.autoclose_regions.push(AutocloseRegion {
5605 selection_id: selection.id,
5606 range: start..end,
5607 pair,
5608 });
5609 }
5610 }
5611 }
5612 }
5613 Ok(())
5614 }
5615
5616 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5617 self.move_to_snippet_tabstop(Bias::Right, cx)
5618 }
5619
5620 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5621 self.move_to_snippet_tabstop(Bias::Left, cx)
5622 }
5623
5624 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5625 if let Some(mut snippet) = self.snippet_stack.pop() {
5626 match bias {
5627 Bias::Left => {
5628 if snippet.active_index > 0 {
5629 snippet.active_index -= 1;
5630 } else {
5631 self.snippet_stack.push(snippet);
5632 return false;
5633 }
5634 }
5635 Bias::Right => {
5636 if snippet.active_index + 1 < snippet.ranges.len() {
5637 snippet.active_index += 1;
5638 } else {
5639 self.snippet_stack.push(snippet);
5640 return false;
5641 }
5642 }
5643 }
5644 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5645 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5646 s.select_anchor_ranges(current_ranges.iter().cloned())
5647 });
5648 // If snippet state is not at the last tabstop, push it back on the stack
5649 if snippet.active_index + 1 < snippet.ranges.len() {
5650 self.snippet_stack.push(snippet);
5651 }
5652 return true;
5653 }
5654 }
5655
5656 false
5657 }
5658
5659 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5660 self.transact(cx, |this, cx| {
5661 this.select_all(&SelectAll, cx);
5662 this.insert("", cx);
5663 });
5664 }
5665
5666 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5667 self.transact(cx, |this, cx| {
5668 this.select_autoclose_pair(cx);
5669 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5670 if !this.linked_edit_ranges.is_empty() {
5671 let selections = this.selections.all::<MultiBufferPoint>(cx);
5672 let snapshot = this.buffer.read(cx).snapshot(cx);
5673
5674 for selection in selections.iter() {
5675 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5676 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5677 if selection_start.buffer_id != selection_end.buffer_id {
5678 continue;
5679 }
5680 if let Some(ranges) =
5681 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5682 {
5683 for (buffer, entries) in ranges {
5684 linked_ranges.entry(buffer).or_default().extend(entries);
5685 }
5686 }
5687 }
5688 }
5689
5690 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5691 if !this.selections.line_mode {
5692 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5693 for selection in &mut selections {
5694 if selection.is_empty() {
5695 let old_head = selection.head();
5696 let mut new_head =
5697 movement::left(&display_map, old_head.to_display_point(&display_map))
5698 .to_point(&display_map);
5699 if let Some((buffer, line_buffer_range)) = display_map
5700 .buffer_snapshot
5701 .buffer_line_for_row(MultiBufferRow(old_head.row))
5702 {
5703 let indent_size =
5704 buffer.indent_size_for_line(line_buffer_range.start.row);
5705 let indent_len = match indent_size.kind {
5706 IndentKind::Space => {
5707 buffer.settings_at(line_buffer_range.start, cx).tab_size
5708 }
5709 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5710 };
5711 if old_head.column <= indent_size.len && old_head.column > 0 {
5712 let indent_len = indent_len.get();
5713 new_head = cmp::min(
5714 new_head,
5715 MultiBufferPoint::new(
5716 old_head.row,
5717 ((old_head.column - 1) / indent_len) * indent_len,
5718 ),
5719 );
5720 }
5721 }
5722
5723 selection.set_head(new_head, SelectionGoal::None);
5724 }
5725 }
5726 }
5727
5728 this.signature_help_state.set_backspace_pressed(true);
5729 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5730 this.insert("", cx);
5731 let empty_str: Arc<str> = Arc::from("");
5732 for (buffer, edits) in linked_ranges {
5733 let snapshot = buffer.read(cx).snapshot();
5734 use text::ToPoint as TP;
5735
5736 let edits = edits
5737 .into_iter()
5738 .map(|range| {
5739 let end_point = TP::to_point(&range.end, &snapshot);
5740 let mut start_point = TP::to_point(&range.start, &snapshot);
5741
5742 if end_point == start_point {
5743 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5744 .saturating_sub(1);
5745 start_point = TP::to_point(&offset, &snapshot);
5746 };
5747
5748 (start_point..end_point, empty_str.clone())
5749 })
5750 .sorted_by_key(|(range, _)| range.start)
5751 .collect::<Vec<_>>();
5752 buffer.update(cx, |this, cx| {
5753 this.edit(edits, None, cx);
5754 })
5755 }
5756 this.refresh_inline_completion(true, false, cx);
5757 linked_editing_ranges::refresh_linked_ranges(this, cx);
5758 });
5759 }
5760
5761 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5762 self.transact(cx, |this, cx| {
5763 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5764 let line_mode = s.line_mode;
5765 s.move_with(|map, selection| {
5766 if selection.is_empty() && !line_mode {
5767 let cursor = movement::right(map, selection.head());
5768 selection.end = cursor;
5769 selection.reversed = true;
5770 selection.goal = SelectionGoal::None;
5771 }
5772 })
5773 });
5774 this.insert("", cx);
5775 this.refresh_inline_completion(true, false, cx);
5776 });
5777 }
5778
5779 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5780 if self.move_to_prev_snippet_tabstop(cx) {
5781 return;
5782 }
5783
5784 self.outdent(&Outdent, cx);
5785 }
5786
5787 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5788 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5789 return;
5790 }
5791
5792 let mut selections = self.selections.all_adjusted(cx);
5793 let buffer = self.buffer.read(cx);
5794 let snapshot = buffer.snapshot(cx);
5795 let rows_iter = selections.iter().map(|s| s.head().row);
5796 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5797
5798 let mut edits = Vec::new();
5799 let mut prev_edited_row = 0;
5800 let mut row_delta = 0;
5801 for selection in &mut selections {
5802 if selection.start.row != prev_edited_row {
5803 row_delta = 0;
5804 }
5805 prev_edited_row = selection.end.row;
5806
5807 // If the selection is non-empty, then increase the indentation of the selected lines.
5808 if !selection.is_empty() {
5809 row_delta =
5810 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5811 continue;
5812 }
5813
5814 // If the selection is empty and the cursor is in the leading whitespace before the
5815 // suggested indentation, then auto-indent the line.
5816 let cursor = selection.head();
5817 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5818 if let Some(suggested_indent) =
5819 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5820 {
5821 if cursor.column < suggested_indent.len
5822 && cursor.column <= current_indent.len
5823 && current_indent.len <= suggested_indent.len
5824 {
5825 selection.start = Point::new(cursor.row, suggested_indent.len);
5826 selection.end = selection.start;
5827 if row_delta == 0 {
5828 edits.extend(Buffer::edit_for_indent_size_adjustment(
5829 cursor.row,
5830 current_indent,
5831 suggested_indent,
5832 ));
5833 row_delta = suggested_indent.len - current_indent.len;
5834 }
5835 continue;
5836 }
5837 }
5838
5839 // Otherwise, insert a hard or soft tab.
5840 let settings = buffer.settings_at(cursor, cx);
5841 let tab_size = if settings.hard_tabs {
5842 IndentSize::tab()
5843 } else {
5844 let tab_size = settings.tab_size.get();
5845 let char_column = snapshot
5846 .text_for_range(Point::new(cursor.row, 0)..cursor)
5847 .flat_map(str::chars)
5848 .count()
5849 + row_delta as usize;
5850 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5851 IndentSize::spaces(chars_to_next_tab_stop)
5852 };
5853 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5854 selection.end = selection.start;
5855 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5856 row_delta += tab_size.len;
5857 }
5858
5859 self.transact(cx, |this, cx| {
5860 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5861 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5862 this.refresh_inline_completion(true, false, cx);
5863 });
5864 }
5865
5866 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5867 if self.read_only(cx) {
5868 return;
5869 }
5870 let mut selections = self.selections.all::<Point>(cx);
5871 let mut prev_edited_row = 0;
5872 let mut row_delta = 0;
5873 let mut edits = Vec::new();
5874 let buffer = self.buffer.read(cx);
5875 let snapshot = buffer.snapshot(cx);
5876 for selection in &mut selections {
5877 if selection.start.row != prev_edited_row {
5878 row_delta = 0;
5879 }
5880 prev_edited_row = selection.end.row;
5881
5882 row_delta =
5883 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5884 }
5885
5886 self.transact(cx, |this, cx| {
5887 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5888 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5889 });
5890 }
5891
5892 fn indent_selection(
5893 buffer: &MultiBuffer,
5894 snapshot: &MultiBufferSnapshot,
5895 selection: &mut Selection<Point>,
5896 edits: &mut Vec<(Range<Point>, String)>,
5897 delta_for_start_row: u32,
5898 cx: &AppContext,
5899 ) -> u32 {
5900 let settings = buffer.settings_at(selection.start, cx);
5901 let tab_size = settings.tab_size.get();
5902 let indent_kind = if settings.hard_tabs {
5903 IndentKind::Tab
5904 } else {
5905 IndentKind::Space
5906 };
5907 let mut start_row = selection.start.row;
5908 let mut end_row = selection.end.row + 1;
5909
5910 // If a selection ends at the beginning of a line, don't indent
5911 // that last line.
5912 if selection.end.column == 0 && selection.end.row > selection.start.row {
5913 end_row -= 1;
5914 }
5915
5916 // Avoid re-indenting a row that has already been indented by a
5917 // previous selection, but still update this selection's column
5918 // to reflect that indentation.
5919 if delta_for_start_row > 0 {
5920 start_row += 1;
5921 selection.start.column += delta_for_start_row;
5922 if selection.end.row == selection.start.row {
5923 selection.end.column += delta_for_start_row;
5924 }
5925 }
5926
5927 let mut delta_for_end_row = 0;
5928 let has_multiple_rows = start_row + 1 != end_row;
5929 for row in start_row..end_row {
5930 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5931 let indent_delta = match (current_indent.kind, indent_kind) {
5932 (IndentKind::Space, IndentKind::Space) => {
5933 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5934 IndentSize::spaces(columns_to_next_tab_stop)
5935 }
5936 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5937 (_, IndentKind::Tab) => IndentSize::tab(),
5938 };
5939
5940 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5941 0
5942 } else {
5943 selection.start.column
5944 };
5945 let row_start = Point::new(row, start);
5946 edits.push((
5947 row_start..row_start,
5948 indent_delta.chars().collect::<String>(),
5949 ));
5950
5951 // Update this selection's endpoints to reflect the indentation.
5952 if row == selection.start.row {
5953 selection.start.column += indent_delta.len;
5954 }
5955 if row == selection.end.row {
5956 selection.end.column += indent_delta.len;
5957 delta_for_end_row = indent_delta.len;
5958 }
5959 }
5960
5961 if selection.start.row == selection.end.row {
5962 delta_for_start_row + delta_for_end_row
5963 } else {
5964 delta_for_end_row
5965 }
5966 }
5967
5968 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5969 if self.read_only(cx) {
5970 return;
5971 }
5972 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5973 let selections = self.selections.all::<Point>(cx);
5974 let mut deletion_ranges = Vec::new();
5975 let mut last_outdent = None;
5976 {
5977 let buffer = self.buffer.read(cx);
5978 let snapshot = buffer.snapshot(cx);
5979 for selection in &selections {
5980 let settings = buffer.settings_at(selection.start, cx);
5981 let tab_size = settings.tab_size.get();
5982 let mut rows = selection.spanned_rows(false, &display_map);
5983
5984 // Avoid re-outdenting a row that has already been outdented by a
5985 // previous selection.
5986 if let Some(last_row) = last_outdent {
5987 if last_row == rows.start {
5988 rows.start = rows.start.next_row();
5989 }
5990 }
5991 let has_multiple_rows = rows.len() > 1;
5992 for row in rows.iter_rows() {
5993 let indent_size = snapshot.indent_size_for_line(row);
5994 if indent_size.len > 0 {
5995 let deletion_len = match indent_size.kind {
5996 IndentKind::Space => {
5997 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5998 if columns_to_prev_tab_stop == 0 {
5999 tab_size
6000 } else {
6001 columns_to_prev_tab_stop
6002 }
6003 }
6004 IndentKind::Tab => 1,
6005 };
6006 let start = if has_multiple_rows
6007 || deletion_len > selection.start.column
6008 || indent_size.len < selection.start.column
6009 {
6010 0
6011 } else {
6012 selection.start.column - deletion_len
6013 };
6014 deletion_ranges.push(
6015 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
6016 );
6017 last_outdent = Some(row);
6018 }
6019 }
6020 }
6021 }
6022
6023 self.transact(cx, |this, cx| {
6024 this.buffer.update(cx, |buffer, cx| {
6025 let empty_str: Arc<str> = Arc::default();
6026 buffer.edit(
6027 deletion_ranges
6028 .into_iter()
6029 .map(|range| (range, empty_str.clone())),
6030 None,
6031 cx,
6032 );
6033 });
6034 let selections = this.selections.all::<usize>(cx);
6035 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6036 });
6037 }
6038
6039 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6040 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6041 let selections = self.selections.all::<Point>(cx);
6042
6043 let mut new_cursors = Vec::new();
6044 let mut edit_ranges = Vec::new();
6045 let mut selections = selections.iter().peekable();
6046 while let Some(selection) = selections.next() {
6047 let mut rows = selection.spanned_rows(false, &display_map);
6048 let goal_display_column = selection.head().to_display_point(&display_map).column();
6049
6050 // Accumulate contiguous regions of rows that we want to delete.
6051 while let Some(next_selection) = selections.peek() {
6052 let next_rows = next_selection.spanned_rows(false, &display_map);
6053 if next_rows.start <= rows.end {
6054 rows.end = next_rows.end;
6055 selections.next().unwrap();
6056 } else {
6057 break;
6058 }
6059 }
6060
6061 let buffer = &display_map.buffer_snapshot;
6062 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6063 let edit_end;
6064 let cursor_buffer_row;
6065 if buffer.max_point().row >= rows.end.0 {
6066 // If there's a line after the range, delete the \n from the end of the row range
6067 // and position the cursor on the next line.
6068 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6069 cursor_buffer_row = rows.end;
6070 } else {
6071 // If there isn't a line after the range, delete the \n from the line before the
6072 // start of the row range and position the cursor there.
6073 edit_start = edit_start.saturating_sub(1);
6074 edit_end = buffer.len();
6075 cursor_buffer_row = rows.start.previous_row();
6076 }
6077
6078 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6079 *cursor.column_mut() =
6080 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6081
6082 new_cursors.push((
6083 selection.id,
6084 buffer.anchor_after(cursor.to_point(&display_map)),
6085 ));
6086 edit_ranges.push(edit_start..edit_end);
6087 }
6088
6089 self.transact(cx, |this, cx| {
6090 let buffer = this.buffer.update(cx, |buffer, cx| {
6091 let empty_str: Arc<str> = Arc::default();
6092 buffer.edit(
6093 edit_ranges
6094 .into_iter()
6095 .map(|range| (range, empty_str.clone())),
6096 None,
6097 cx,
6098 );
6099 buffer.snapshot(cx)
6100 });
6101 let new_selections = new_cursors
6102 .into_iter()
6103 .map(|(id, cursor)| {
6104 let cursor = cursor.to_point(&buffer);
6105 Selection {
6106 id,
6107 start: cursor,
6108 end: cursor,
6109 reversed: false,
6110 goal: SelectionGoal::None,
6111 }
6112 })
6113 .collect();
6114
6115 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6116 s.select(new_selections);
6117 });
6118 });
6119 }
6120
6121 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6122 if self.read_only(cx) {
6123 return;
6124 }
6125 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6126 for selection in self.selections.all::<Point>(cx) {
6127 let start = MultiBufferRow(selection.start.row);
6128 let end = if selection.start.row == selection.end.row {
6129 MultiBufferRow(selection.start.row + 1)
6130 } else {
6131 MultiBufferRow(selection.end.row)
6132 };
6133
6134 if let Some(last_row_range) = row_ranges.last_mut() {
6135 if start <= last_row_range.end {
6136 last_row_range.end = end;
6137 continue;
6138 }
6139 }
6140 row_ranges.push(start..end);
6141 }
6142
6143 let snapshot = self.buffer.read(cx).snapshot(cx);
6144 let mut cursor_positions = Vec::new();
6145 for row_range in &row_ranges {
6146 let anchor = snapshot.anchor_before(Point::new(
6147 row_range.end.previous_row().0,
6148 snapshot.line_len(row_range.end.previous_row()),
6149 ));
6150 cursor_positions.push(anchor..anchor);
6151 }
6152
6153 self.transact(cx, |this, cx| {
6154 for row_range in row_ranges.into_iter().rev() {
6155 for row in row_range.iter_rows().rev() {
6156 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6157 let next_line_row = row.next_row();
6158 let indent = snapshot.indent_size_for_line(next_line_row);
6159 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6160
6161 let replace = if snapshot.line_len(next_line_row) > indent.len {
6162 " "
6163 } else {
6164 ""
6165 };
6166
6167 this.buffer.update(cx, |buffer, cx| {
6168 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6169 });
6170 }
6171 }
6172
6173 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6174 s.select_anchor_ranges(cursor_positions)
6175 });
6176 });
6177 }
6178
6179 pub fn sort_lines_case_sensitive(
6180 &mut self,
6181 _: &SortLinesCaseSensitive,
6182 cx: &mut ViewContext<Self>,
6183 ) {
6184 self.manipulate_lines(cx, |lines| lines.sort())
6185 }
6186
6187 pub fn sort_lines_case_insensitive(
6188 &mut self,
6189 _: &SortLinesCaseInsensitive,
6190 cx: &mut ViewContext<Self>,
6191 ) {
6192 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6193 }
6194
6195 pub fn unique_lines_case_insensitive(
6196 &mut self,
6197 _: &UniqueLinesCaseInsensitive,
6198 cx: &mut ViewContext<Self>,
6199 ) {
6200 self.manipulate_lines(cx, |lines| {
6201 let mut seen = HashSet::default();
6202 lines.retain(|line| seen.insert(line.to_lowercase()));
6203 })
6204 }
6205
6206 pub fn unique_lines_case_sensitive(
6207 &mut self,
6208 _: &UniqueLinesCaseSensitive,
6209 cx: &mut ViewContext<Self>,
6210 ) {
6211 self.manipulate_lines(cx, |lines| {
6212 let mut seen = HashSet::default();
6213 lines.retain(|line| seen.insert(*line));
6214 })
6215 }
6216
6217 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6218 let mut revert_changes = HashMap::default();
6219 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6220 for hunk in hunks_for_rows(
6221 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6222 &multi_buffer_snapshot,
6223 ) {
6224 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6225 }
6226 if !revert_changes.is_empty() {
6227 self.transact(cx, |editor, cx| {
6228 editor.revert(revert_changes, cx);
6229 });
6230 }
6231 }
6232
6233 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6234 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6235 if !revert_changes.is_empty() {
6236 self.transact(cx, |editor, cx| {
6237 editor.revert(revert_changes, cx);
6238 });
6239 }
6240 }
6241
6242 fn apply_selected_diff_hunks(&mut self, _: &ApplyDiffHunk, cx: &mut ViewContext<Self>) {
6243 let snapshot = self.buffer.read(cx).snapshot(cx);
6244 let hunks = hunks_for_selections(&snapshot, &self.selections.disjoint_anchors());
6245 let mut ranges_by_buffer = HashMap::default();
6246 self.transact(cx, |editor, cx| {
6247 for hunk in hunks {
6248 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
6249 ranges_by_buffer
6250 .entry(buffer.clone())
6251 .or_insert_with(Vec::new)
6252 .push(hunk.buffer_range.to_offset(buffer.read(cx)));
6253 }
6254 }
6255
6256 for (buffer, ranges) in ranges_by_buffer {
6257 buffer.update(cx, |buffer, cx| {
6258 buffer.merge_into_base(ranges, cx);
6259 });
6260 }
6261 });
6262 }
6263
6264 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6265 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6266 let project_path = buffer.read(cx).project_path(cx)?;
6267 let project = self.project.as_ref()?.read(cx);
6268 let entry = project.entry_for_path(&project_path, cx)?;
6269 let abs_path = project.absolute_path(&project_path, cx)?;
6270 let parent = if entry.is_symlink {
6271 abs_path.canonicalize().ok()?
6272 } else {
6273 abs_path
6274 }
6275 .parent()?
6276 .to_path_buf();
6277 Some(parent)
6278 }) {
6279 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6280 }
6281 }
6282
6283 fn gather_revert_changes(
6284 &mut self,
6285 selections: &[Selection<Anchor>],
6286 cx: &mut ViewContext<'_, Editor>,
6287 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6288 let mut revert_changes = HashMap::default();
6289 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6290 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6291 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6292 }
6293 revert_changes
6294 }
6295
6296 pub fn prepare_revert_change(
6297 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6298 multi_buffer: &Model<MultiBuffer>,
6299 hunk: &MultiBufferDiffHunk,
6300 cx: &AppContext,
6301 ) -> Option<()> {
6302 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6303 let buffer = buffer.read(cx);
6304 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6305 let buffer_snapshot = buffer.snapshot();
6306 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6307 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6308 probe
6309 .0
6310 .start
6311 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6312 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6313 }) {
6314 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6315 Some(())
6316 } else {
6317 None
6318 }
6319 }
6320
6321 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6322 self.manipulate_lines(cx, |lines| lines.reverse())
6323 }
6324
6325 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6326 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6327 }
6328
6329 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6330 where
6331 Fn: FnMut(&mut Vec<&str>),
6332 {
6333 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6334 let buffer = self.buffer.read(cx).snapshot(cx);
6335
6336 let mut edits = Vec::new();
6337
6338 let selections = self.selections.all::<Point>(cx);
6339 let mut selections = selections.iter().peekable();
6340 let mut contiguous_row_selections = Vec::new();
6341 let mut new_selections = Vec::new();
6342 let mut added_lines = 0;
6343 let mut removed_lines = 0;
6344
6345 while let Some(selection) = selections.next() {
6346 let (start_row, end_row) = consume_contiguous_rows(
6347 &mut contiguous_row_selections,
6348 selection,
6349 &display_map,
6350 &mut selections,
6351 );
6352
6353 let start_point = Point::new(start_row.0, 0);
6354 let end_point = Point::new(
6355 end_row.previous_row().0,
6356 buffer.line_len(end_row.previous_row()),
6357 );
6358 let text = buffer
6359 .text_for_range(start_point..end_point)
6360 .collect::<String>();
6361
6362 let mut lines = text.split('\n').collect_vec();
6363
6364 let lines_before = lines.len();
6365 callback(&mut lines);
6366 let lines_after = lines.len();
6367
6368 edits.push((start_point..end_point, lines.join("\n")));
6369
6370 // Selections must change based on added and removed line count
6371 let start_row =
6372 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6373 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6374 new_selections.push(Selection {
6375 id: selection.id,
6376 start: start_row,
6377 end: end_row,
6378 goal: SelectionGoal::None,
6379 reversed: selection.reversed,
6380 });
6381
6382 if lines_after > lines_before {
6383 added_lines += lines_after - lines_before;
6384 } else if lines_before > lines_after {
6385 removed_lines += lines_before - lines_after;
6386 }
6387 }
6388
6389 self.transact(cx, |this, cx| {
6390 let buffer = this.buffer.update(cx, |buffer, cx| {
6391 buffer.edit(edits, None, cx);
6392 buffer.snapshot(cx)
6393 });
6394
6395 // Recalculate offsets on newly edited buffer
6396 let new_selections = new_selections
6397 .iter()
6398 .map(|s| {
6399 let start_point = Point::new(s.start.0, 0);
6400 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6401 Selection {
6402 id: s.id,
6403 start: buffer.point_to_offset(start_point),
6404 end: buffer.point_to_offset(end_point),
6405 goal: s.goal,
6406 reversed: s.reversed,
6407 }
6408 })
6409 .collect();
6410
6411 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6412 s.select(new_selections);
6413 });
6414
6415 this.request_autoscroll(Autoscroll::fit(), cx);
6416 });
6417 }
6418
6419 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6420 self.manipulate_text(cx, |text| text.to_uppercase())
6421 }
6422
6423 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6424 self.manipulate_text(cx, |text| text.to_lowercase())
6425 }
6426
6427 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6428 self.manipulate_text(cx, |text| {
6429 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6430 // https://github.com/rutrum/convert-case/issues/16
6431 text.split('\n')
6432 .map(|line| line.to_case(Case::Title))
6433 .join("\n")
6434 })
6435 }
6436
6437 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6438 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6439 }
6440
6441 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6442 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6443 }
6444
6445 pub fn convert_to_upper_camel_case(
6446 &mut self,
6447 _: &ConvertToUpperCamelCase,
6448 cx: &mut ViewContext<Self>,
6449 ) {
6450 self.manipulate_text(cx, |text| {
6451 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6452 // https://github.com/rutrum/convert-case/issues/16
6453 text.split('\n')
6454 .map(|line| line.to_case(Case::UpperCamel))
6455 .join("\n")
6456 })
6457 }
6458
6459 pub fn convert_to_lower_camel_case(
6460 &mut self,
6461 _: &ConvertToLowerCamelCase,
6462 cx: &mut ViewContext<Self>,
6463 ) {
6464 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6465 }
6466
6467 pub fn convert_to_opposite_case(
6468 &mut self,
6469 _: &ConvertToOppositeCase,
6470 cx: &mut ViewContext<Self>,
6471 ) {
6472 self.manipulate_text(cx, |text| {
6473 text.chars()
6474 .fold(String::with_capacity(text.len()), |mut t, c| {
6475 if c.is_uppercase() {
6476 t.extend(c.to_lowercase());
6477 } else {
6478 t.extend(c.to_uppercase());
6479 }
6480 t
6481 })
6482 })
6483 }
6484
6485 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6486 where
6487 Fn: FnMut(&str) -> String,
6488 {
6489 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6490 let buffer = self.buffer.read(cx).snapshot(cx);
6491
6492 let mut new_selections = Vec::new();
6493 let mut edits = Vec::new();
6494 let mut selection_adjustment = 0i32;
6495
6496 for selection in self.selections.all::<usize>(cx) {
6497 let selection_is_empty = selection.is_empty();
6498
6499 let (start, end) = if selection_is_empty {
6500 let word_range = movement::surrounding_word(
6501 &display_map,
6502 selection.start.to_display_point(&display_map),
6503 );
6504 let start = word_range.start.to_offset(&display_map, Bias::Left);
6505 let end = word_range.end.to_offset(&display_map, Bias::Left);
6506 (start, end)
6507 } else {
6508 (selection.start, selection.end)
6509 };
6510
6511 let text = buffer.text_for_range(start..end).collect::<String>();
6512 let old_length = text.len() as i32;
6513 let text = callback(&text);
6514
6515 new_selections.push(Selection {
6516 start: (start as i32 - selection_adjustment) as usize,
6517 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6518 goal: SelectionGoal::None,
6519 ..selection
6520 });
6521
6522 selection_adjustment += old_length - text.len() as i32;
6523
6524 edits.push((start..end, text));
6525 }
6526
6527 self.transact(cx, |this, cx| {
6528 this.buffer.update(cx, |buffer, cx| {
6529 buffer.edit(edits, None, cx);
6530 });
6531
6532 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6533 s.select(new_selections);
6534 });
6535
6536 this.request_autoscroll(Autoscroll::fit(), cx);
6537 });
6538 }
6539
6540 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6541 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6542 let buffer = &display_map.buffer_snapshot;
6543 let selections = self.selections.all::<Point>(cx);
6544
6545 let mut edits = Vec::new();
6546 let mut selections_iter = selections.iter().peekable();
6547 while let Some(selection) = selections_iter.next() {
6548 // Avoid duplicating the same lines twice.
6549 let mut rows = selection.spanned_rows(false, &display_map);
6550
6551 while let Some(next_selection) = selections_iter.peek() {
6552 let next_rows = next_selection.spanned_rows(false, &display_map);
6553 if next_rows.start < rows.end {
6554 rows.end = next_rows.end;
6555 selections_iter.next().unwrap();
6556 } else {
6557 break;
6558 }
6559 }
6560
6561 // Copy the text from the selected row region and splice it either at the start
6562 // or end of the region.
6563 let start = Point::new(rows.start.0, 0);
6564 let end = Point::new(
6565 rows.end.previous_row().0,
6566 buffer.line_len(rows.end.previous_row()),
6567 );
6568 let text = buffer
6569 .text_for_range(start..end)
6570 .chain(Some("\n"))
6571 .collect::<String>();
6572 let insert_location = if upwards {
6573 Point::new(rows.end.0, 0)
6574 } else {
6575 start
6576 };
6577 edits.push((insert_location..insert_location, text));
6578 }
6579
6580 self.transact(cx, |this, cx| {
6581 this.buffer.update(cx, |buffer, cx| {
6582 buffer.edit(edits, None, cx);
6583 });
6584
6585 this.request_autoscroll(Autoscroll::fit(), cx);
6586 });
6587 }
6588
6589 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6590 self.duplicate_line(true, cx);
6591 }
6592
6593 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6594 self.duplicate_line(false, cx);
6595 }
6596
6597 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6598 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6599 let buffer = self.buffer.read(cx).snapshot(cx);
6600
6601 let mut edits = Vec::new();
6602 let mut unfold_ranges = Vec::new();
6603 let mut refold_ranges = Vec::new();
6604
6605 let selections = self.selections.all::<Point>(cx);
6606 let mut selections = selections.iter().peekable();
6607 let mut contiguous_row_selections = Vec::new();
6608 let mut new_selections = Vec::new();
6609
6610 while let Some(selection) = selections.next() {
6611 // Find all the selections that span a contiguous row range
6612 let (start_row, end_row) = consume_contiguous_rows(
6613 &mut contiguous_row_selections,
6614 selection,
6615 &display_map,
6616 &mut selections,
6617 );
6618
6619 // Move the text spanned by the row range to be before the line preceding the row range
6620 if start_row.0 > 0 {
6621 let range_to_move = Point::new(
6622 start_row.previous_row().0,
6623 buffer.line_len(start_row.previous_row()),
6624 )
6625 ..Point::new(
6626 end_row.previous_row().0,
6627 buffer.line_len(end_row.previous_row()),
6628 );
6629 let insertion_point = display_map
6630 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6631 .0;
6632
6633 // Don't move lines across excerpts
6634 if buffer
6635 .excerpt_boundaries_in_range((
6636 Bound::Excluded(insertion_point),
6637 Bound::Included(range_to_move.end),
6638 ))
6639 .next()
6640 .is_none()
6641 {
6642 let text = buffer
6643 .text_for_range(range_to_move.clone())
6644 .flat_map(|s| s.chars())
6645 .skip(1)
6646 .chain(['\n'])
6647 .collect::<String>();
6648
6649 edits.push((
6650 buffer.anchor_after(range_to_move.start)
6651 ..buffer.anchor_before(range_to_move.end),
6652 String::new(),
6653 ));
6654 let insertion_anchor = buffer.anchor_after(insertion_point);
6655 edits.push((insertion_anchor..insertion_anchor, text));
6656
6657 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6658
6659 // Move selections up
6660 new_selections.extend(contiguous_row_selections.drain(..).map(
6661 |mut selection| {
6662 selection.start.row -= row_delta;
6663 selection.end.row -= row_delta;
6664 selection
6665 },
6666 ));
6667
6668 // Move folds up
6669 unfold_ranges.push(range_to_move.clone());
6670 for fold in display_map.folds_in_range(
6671 buffer.anchor_before(range_to_move.start)
6672 ..buffer.anchor_after(range_to_move.end),
6673 ) {
6674 let mut start = fold.range.start.to_point(&buffer);
6675 let mut end = fold.range.end.to_point(&buffer);
6676 start.row -= row_delta;
6677 end.row -= row_delta;
6678 refold_ranges.push((start..end, fold.placeholder.clone()));
6679 }
6680 }
6681 }
6682
6683 // If we didn't move line(s), preserve the existing selections
6684 new_selections.append(&mut contiguous_row_selections);
6685 }
6686
6687 self.transact(cx, |this, cx| {
6688 this.unfold_ranges(unfold_ranges, true, true, cx);
6689 this.buffer.update(cx, |buffer, cx| {
6690 for (range, text) in edits {
6691 buffer.edit([(range, text)], None, cx);
6692 }
6693 });
6694 this.fold_ranges(refold_ranges, true, cx);
6695 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6696 s.select(new_selections);
6697 })
6698 });
6699 }
6700
6701 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6702 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6703 let buffer = self.buffer.read(cx).snapshot(cx);
6704
6705 let mut edits = Vec::new();
6706 let mut unfold_ranges = Vec::new();
6707 let mut refold_ranges = Vec::new();
6708
6709 let selections = self.selections.all::<Point>(cx);
6710 let mut selections = selections.iter().peekable();
6711 let mut contiguous_row_selections = Vec::new();
6712 let mut new_selections = Vec::new();
6713
6714 while let Some(selection) = selections.next() {
6715 // Find all the selections that span a contiguous row range
6716 let (start_row, end_row) = consume_contiguous_rows(
6717 &mut contiguous_row_selections,
6718 selection,
6719 &display_map,
6720 &mut selections,
6721 );
6722
6723 // Move the text spanned by the row range to be after the last line of the row range
6724 if end_row.0 <= buffer.max_point().row {
6725 let range_to_move =
6726 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6727 let insertion_point = display_map
6728 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6729 .0;
6730
6731 // Don't move lines across excerpt boundaries
6732 if buffer
6733 .excerpt_boundaries_in_range((
6734 Bound::Excluded(range_to_move.start),
6735 Bound::Included(insertion_point),
6736 ))
6737 .next()
6738 .is_none()
6739 {
6740 let mut text = String::from("\n");
6741 text.extend(buffer.text_for_range(range_to_move.clone()));
6742 text.pop(); // Drop trailing newline
6743 edits.push((
6744 buffer.anchor_after(range_to_move.start)
6745 ..buffer.anchor_before(range_to_move.end),
6746 String::new(),
6747 ));
6748 let insertion_anchor = buffer.anchor_after(insertion_point);
6749 edits.push((insertion_anchor..insertion_anchor, text));
6750
6751 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6752
6753 // Move selections down
6754 new_selections.extend(contiguous_row_selections.drain(..).map(
6755 |mut selection| {
6756 selection.start.row += row_delta;
6757 selection.end.row += row_delta;
6758 selection
6759 },
6760 ));
6761
6762 // Move folds down
6763 unfold_ranges.push(range_to_move.clone());
6764 for fold in display_map.folds_in_range(
6765 buffer.anchor_before(range_to_move.start)
6766 ..buffer.anchor_after(range_to_move.end),
6767 ) {
6768 let mut start = fold.range.start.to_point(&buffer);
6769 let mut end = fold.range.end.to_point(&buffer);
6770 start.row += row_delta;
6771 end.row += row_delta;
6772 refold_ranges.push((start..end, fold.placeholder.clone()));
6773 }
6774 }
6775 }
6776
6777 // If we didn't move line(s), preserve the existing selections
6778 new_selections.append(&mut contiguous_row_selections);
6779 }
6780
6781 self.transact(cx, |this, cx| {
6782 this.unfold_ranges(unfold_ranges, true, true, cx);
6783 this.buffer.update(cx, |buffer, cx| {
6784 for (range, text) in edits {
6785 buffer.edit([(range, text)], None, cx);
6786 }
6787 });
6788 this.fold_ranges(refold_ranges, true, cx);
6789 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6790 });
6791 }
6792
6793 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6794 let text_layout_details = &self.text_layout_details(cx);
6795 self.transact(cx, |this, cx| {
6796 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6797 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6798 let line_mode = s.line_mode;
6799 s.move_with(|display_map, selection| {
6800 if !selection.is_empty() || line_mode {
6801 return;
6802 }
6803
6804 let mut head = selection.head();
6805 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6806 if head.column() == display_map.line_len(head.row()) {
6807 transpose_offset = display_map
6808 .buffer_snapshot
6809 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6810 }
6811
6812 if transpose_offset == 0 {
6813 return;
6814 }
6815
6816 *head.column_mut() += 1;
6817 head = display_map.clip_point(head, Bias::Right);
6818 let goal = SelectionGoal::HorizontalPosition(
6819 display_map
6820 .x_for_display_point(head, text_layout_details)
6821 .into(),
6822 );
6823 selection.collapse_to(head, goal);
6824
6825 let transpose_start = display_map
6826 .buffer_snapshot
6827 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6828 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6829 let transpose_end = display_map
6830 .buffer_snapshot
6831 .clip_offset(transpose_offset + 1, Bias::Right);
6832 if let Some(ch) =
6833 display_map.buffer_snapshot.chars_at(transpose_start).next()
6834 {
6835 edits.push((transpose_start..transpose_offset, String::new()));
6836 edits.push((transpose_end..transpose_end, ch.to_string()));
6837 }
6838 }
6839 });
6840 edits
6841 });
6842 this.buffer
6843 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6844 let selections = this.selections.all::<usize>(cx);
6845 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6846 s.select(selections);
6847 });
6848 });
6849 }
6850
6851 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6852 self.rewrap_impl(true, cx)
6853 }
6854
6855 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6856 let buffer = self.buffer.read(cx).snapshot(cx);
6857 let selections = self.selections.all::<Point>(cx);
6858 let mut selections = selections.iter().peekable();
6859
6860 let mut edits = Vec::new();
6861 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6862
6863 while let Some(selection) = selections.next() {
6864 let mut start_row = selection.start.row;
6865 let mut end_row = selection.end.row;
6866
6867 // Skip selections that overlap with a range that has already been rewrapped.
6868 let selection_range = start_row..end_row;
6869 if rewrapped_row_ranges
6870 .iter()
6871 .any(|range| range.overlaps(&selection_range))
6872 {
6873 continue;
6874 }
6875
6876 let mut should_rewrap = !only_text;
6877
6878 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6879 match language_scope.language_name().0.as_ref() {
6880 "Markdown" | "Plain Text" => {
6881 should_rewrap = true;
6882 }
6883 _ => {}
6884 }
6885 }
6886
6887 // Since not all lines in the selection may be at the same indent
6888 // level, choose the indent size that is the most common between all
6889 // of the lines.
6890 //
6891 // If there is a tie, we use the deepest indent.
6892 let (indent_size, indent_end) = {
6893 let mut indent_size_occurrences = HashMap::default();
6894 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6895
6896 for row in start_row..=end_row {
6897 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6898 rows_by_indent_size.entry(indent).or_default().push(row);
6899 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6900 }
6901
6902 let indent_size = indent_size_occurrences
6903 .into_iter()
6904 .max_by_key(|(indent, count)| (*count, indent.len))
6905 .map(|(indent, _)| indent)
6906 .unwrap_or_default();
6907 let row = rows_by_indent_size[&indent_size][0];
6908 let indent_end = Point::new(row, indent_size.len);
6909
6910 (indent_size, indent_end)
6911 };
6912
6913 let mut line_prefix = indent_size.chars().collect::<String>();
6914
6915 if let Some(comment_prefix) =
6916 buffer
6917 .language_scope_at(selection.head())
6918 .and_then(|language| {
6919 language
6920 .line_comment_prefixes()
6921 .iter()
6922 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6923 .cloned()
6924 })
6925 {
6926 line_prefix.push_str(&comment_prefix);
6927 should_rewrap = true;
6928 }
6929
6930 if selection.is_empty() {
6931 'expand_upwards: while start_row > 0 {
6932 let prev_row = start_row - 1;
6933 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6934 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6935 {
6936 start_row = prev_row;
6937 } else {
6938 break 'expand_upwards;
6939 }
6940 }
6941
6942 'expand_downwards: while end_row < buffer.max_point().row {
6943 let next_row = end_row + 1;
6944 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6945 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6946 {
6947 end_row = next_row;
6948 } else {
6949 break 'expand_downwards;
6950 }
6951 }
6952 }
6953
6954 if !should_rewrap {
6955 continue;
6956 }
6957
6958 let start = Point::new(start_row, 0);
6959 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6960 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6961 let Some(lines_without_prefixes) = selection_text
6962 .lines()
6963 .map(|line| {
6964 line.strip_prefix(&line_prefix)
6965 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6966 .ok_or_else(|| {
6967 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6968 })
6969 })
6970 .collect::<Result<Vec<_>, _>>()
6971 .log_err()
6972 else {
6973 continue;
6974 };
6975
6976 let unwrapped_text = lines_without_prefixes.join(" ");
6977 let wrap_column = buffer
6978 .settings_at(Point::new(start_row, 0), cx)
6979 .preferred_line_length as usize;
6980 let mut wrapped_text = String::new();
6981 let mut current_line = line_prefix.clone();
6982 for word in unwrapped_text.split_whitespace() {
6983 if current_line.len() + word.len() >= wrap_column {
6984 wrapped_text.push_str(¤t_line);
6985 wrapped_text.push('\n');
6986 current_line.truncate(line_prefix.len());
6987 }
6988
6989 if current_line.len() > line_prefix.len() {
6990 current_line.push(' ');
6991 }
6992
6993 current_line.push_str(word);
6994 }
6995
6996 if !current_line.is_empty() {
6997 wrapped_text.push_str(¤t_line);
6998 }
6999
7000 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
7001 let mut offset = start.to_offset(&buffer);
7002 let mut moved_since_edit = true;
7003
7004 for change in diff.iter_all_changes() {
7005 let value = change.value();
7006 match change.tag() {
7007 ChangeTag::Equal => {
7008 offset += value.len();
7009 moved_since_edit = true;
7010 }
7011 ChangeTag::Delete => {
7012 let start = buffer.anchor_after(offset);
7013 let end = buffer.anchor_before(offset + value.len());
7014
7015 if moved_since_edit {
7016 edits.push((start..end, String::new()));
7017 } else {
7018 edits.last_mut().unwrap().0.end = end;
7019 }
7020
7021 offset += value.len();
7022 moved_since_edit = false;
7023 }
7024 ChangeTag::Insert => {
7025 if moved_since_edit {
7026 let anchor = buffer.anchor_after(offset);
7027 edits.push((anchor..anchor, value.to_string()));
7028 } else {
7029 edits.last_mut().unwrap().1.push_str(value);
7030 }
7031
7032 moved_since_edit = false;
7033 }
7034 }
7035 }
7036
7037 rewrapped_row_ranges.push(start_row..=end_row);
7038 }
7039
7040 self.buffer
7041 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7042 }
7043
7044 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7045 let mut text = String::new();
7046 let buffer = self.buffer.read(cx).snapshot(cx);
7047 let mut selections = self.selections.all::<Point>(cx);
7048 let mut clipboard_selections = Vec::with_capacity(selections.len());
7049 {
7050 let max_point = buffer.max_point();
7051 let mut is_first = true;
7052 for selection in &mut selections {
7053 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7054 if is_entire_line {
7055 selection.start = Point::new(selection.start.row, 0);
7056 if !selection.is_empty() && selection.end.column == 0 {
7057 selection.end = cmp::min(max_point, selection.end);
7058 } else {
7059 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7060 }
7061 selection.goal = SelectionGoal::None;
7062 }
7063 if is_first {
7064 is_first = false;
7065 } else {
7066 text += "\n";
7067 }
7068 let mut len = 0;
7069 for chunk in buffer.text_for_range(selection.start..selection.end) {
7070 text.push_str(chunk);
7071 len += chunk.len();
7072 }
7073 clipboard_selections.push(ClipboardSelection {
7074 len,
7075 is_entire_line,
7076 first_line_indent: buffer
7077 .indent_size_for_line(MultiBufferRow(selection.start.row))
7078 .len,
7079 });
7080 }
7081 }
7082
7083 self.transact(cx, |this, cx| {
7084 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7085 s.select(selections);
7086 });
7087 this.insert("", cx);
7088 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7089 text,
7090 clipboard_selections,
7091 ));
7092 });
7093 }
7094
7095 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7096 let selections = self.selections.all::<Point>(cx);
7097 let buffer = self.buffer.read(cx).read(cx);
7098 let mut text = String::new();
7099
7100 let mut clipboard_selections = Vec::with_capacity(selections.len());
7101 {
7102 let max_point = buffer.max_point();
7103 let mut is_first = true;
7104 for selection in selections.iter() {
7105 let mut start = selection.start;
7106 let mut end = selection.end;
7107 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7108 if is_entire_line {
7109 start = Point::new(start.row, 0);
7110 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7111 }
7112 if is_first {
7113 is_first = false;
7114 } else {
7115 text += "\n";
7116 }
7117 let mut len = 0;
7118 for chunk in buffer.text_for_range(start..end) {
7119 text.push_str(chunk);
7120 len += chunk.len();
7121 }
7122 clipboard_selections.push(ClipboardSelection {
7123 len,
7124 is_entire_line,
7125 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7126 });
7127 }
7128 }
7129
7130 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7131 text,
7132 clipboard_selections,
7133 ));
7134 }
7135
7136 pub fn do_paste(
7137 &mut self,
7138 text: &String,
7139 clipboard_selections: Option<Vec<ClipboardSelection>>,
7140 handle_entire_lines: bool,
7141 cx: &mut ViewContext<Self>,
7142 ) {
7143 if self.read_only(cx) {
7144 return;
7145 }
7146
7147 let clipboard_text = Cow::Borrowed(text);
7148
7149 self.transact(cx, |this, cx| {
7150 if let Some(mut clipboard_selections) = clipboard_selections {
7151 let old_selections = this.selections.all::<usize>(cx);
7152 let all_selections_were_entire_line =
7153 clipboard_selections.iter().all(|s| s.is_entire_line);
7154 let first_selection_indent_column =
7155 clipboard_selections.first().map(|s| s.first_line_indent);
7156 if clipboard_selections.len() != old_selections.len() {
7157 clipboard_selections.drain(..);
7158 }
7159
7160 this.buffer.update(cx, |buffer, cx| {
7161 let snapshot = buffer.read(cx);
7162 let mut start_offset = 0;
7163 let mut edits = Vec::new();
7164 let mut original_indent_columns = Vec::new();
7165 for (ix, selection) in old_selections.iter().enumerate() {
7166 let to_insert;
7167 let entire_line;
7168 let original_indent_column;
7169 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7170 let end_offset = start_offset + clipboard_selection.len;
7171 to_insert = &clipboard_text[start_offset..end_offset];
7172 entire_line = clipboard_selection.is_entire_line;
7173 start_offset = end_offset + 1;
7174 original_indent_column = Some(clipboard_selection.first_line_indent);
7175 } else {
7176 to_insert = clipboard_text.as_str();
7177 entire_line = all_selections_were_entire_line;
7178 original_indent_column = first_selection_indent_column
7179 }
7180
7181 // If the corresponding selection was empty when this slice of the
7182 // clipboard text was written, then the entire line containing the
7183 // selection was copied. If this selection is also currently empty,
7184 // then paste the line before the current line of the buffer.
7185 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7186 let column = selection.start.to_point(&snapshot).column as usize;
7187 let line_start = selection.start - column;
7188 line_start..line_start
7189 } else {
7190 selection.range()
7191 };
7192
7193 edits.push((range, to_insert));
7194 original_indent_columns.extend(original_indent_column);
7195 }
7196 drop(snapshot);
7197
7198 buffer.edit(
7199 edits,
7200 Some(AutoindentMode::Block {
7201 original_indent_columns,
7202 }),
7203 cx,
7204 );
7205 });
7206
7207 let selections = this.selections.all::<usize>(cx);
7208 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7209 } else {
7210 this.insert(&clipboard_text, cx);
7211 }
7212 });
7213 }
7214
7215 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7216 if let Some(item) = cx.read_from_clipboard() {
7217 let entries = item.entries();
7218
7219 match entries.first() {
7220 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7221 // of all the pasted entries.
7222 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7223 .do_paste(
7224 clipboard_string.text(),
7225 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7226 true,
7227 cx,
7228 ),
7229 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7230 }
7231 }
7232 }
7233
7234 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7235 if self.read_only(cx) {
7236 return;
7237 }
7238
7239 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7240 if let Some((selections, _)) =
7241 self.selection_history.transaction(transaction_id).cloned()
7242 {
7243 self.change_selections(None, cx, |s| {
7244 s.select_anchors(selections.to_vec());
7245 });
7246 }
7247 self.request_autoscroll(Autoscroll::fit(), cx);
7248 self.unmark_text(cx);
7249 self.refresh_inline_completion(true, false, cx);
7250 cx.emit(EditorEvent::Edited { transaction_id });
7251 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7252 }
7253 }
7254
7255 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7256 if self.read_only(cx) {
7257 return;
7258 }
7259
7260 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7261 if let Some((_, Some(selections))) =
7262 self.selection_history.transaction(transaction_id).cloned()
7263 {
7264 self.change_selections(None, cx, |s| {
7265 s.select_anchors(selections.to_vec());
7266 });
7267 }
7268 self.request_autoscroll(Autoscroll::fit(), cx);
7269 self.unmark_text(cx);
7270 self.refresh_inline_completion(true, false, cx);
7271 cx.emit(EditorEvent::Edited { transaction_id });
7272 }
7273 }
7274
7275 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7276 self.buffer
7277 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7278 }
7279
7280 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7281 self.buffer
7282 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7283 }
7284
7285 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7286 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7287 let line_mode = s.line_mode;
7288 s.move_with(|map, selection| {
7289 let cursor = if selection.is_empty() && !line_mode {
7290 movement::left(map, selection.start)
7291 } else {
7292 selection.start
7293 };
7294 selection.collapse_to(cursor, SelectionGoal::None);
7295 });
7296 })
7297 }
7298
7299 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7300 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7301 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7302 })
7303 }
7304
7305 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7306 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7307 let line_mode = s.line_mode;
7308 s.move_with(|map, selection| {
7309 let cursor = if selection.is_empty() && !line_mode {
7310 movement::right(map, selection.end)
7311 } else {
7312 selection.end
7313 };
7314 selection.collapse_to(cursor, SelectionGoal::None)
7315 });
7316 })
7317 }
7318
7319 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7320 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7321 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7322 })
7323 }
7324
7325 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7326 if self.take_rename(true, cx).is_some() {
7327 return;
7328 }
7329
7330 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7331 cx.propagate();
7332 return;
7333 }
7334
7335 let text_layout_details = &self.text_layout_details(cx);
7336 let selection_count = self.selections.count();
7337 let first_selection = self.selections.first_anchor();
7338
7339 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7340 let line_mode = s.line_mode;
7341 s.move_with(|map, selection| {
7342 if !selection.is_empty() && !line_mode {
7343 selection.goal = SelectionGoal::None;
7344 }
7345 let (cursor, goal) = movement::up(
7346 map,
7347 selection.start,
7348 selection.goal,
7349 false,
7350 text_layout_details,
7351 );
7352 selection.collapse_to(cursor, goal);
7353 });
7354 });
7355
7356 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7357 {
7358 cx.propagate();
7359 }
7360 }
7361
7362 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7363 if self.take_rename(true, cx).is_some() {
7364 return;
7365 }
7366
7367 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7368 cx.propagate();
7369 return;
7370 }
7371
7372 let text_layout_details = &self.text_layout_details(cx);
7373
7374 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7375 let line_mode = s.line_mode;
7376 s.move_with(|map, selection| {
7377 if !selection.is_empty() && !line_mode {
7378 selection.goal = SelectionGoal::None;
7379 }
7380 let (cursor, goal) = movement::up_by_rows(
7381 map,
7382 selection.start,
7383 action.lines,
7384 selection.goal,
7385 false,
7386 text_layout_details,
7387 );
7388 selection.collapse_to(cursor, goal);
7389 });
7390 })
7391 }
7392
7393 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7394 if self.take_rename(true, cx).is_some() {
7395 return;
7396 }
7397
7398 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7399 cx.propagate();
7400 return;
7401 }
7402
7403 let text_layout_details = &self.text_layout_details(cx);
7404
7405 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7406 let line_mode = s.line_mode;
7407 s.move_with(|map, selection| {
7408 if !selection.is_empty() && !line_mode {
7409 selection.goal = SelectionGoal::None;
7410 }
7411 let (cursor, goal) = movement::down_by_rows(
7412 map,
7413 selection.start,
7414 action.lines,
7415 selection.goal,
7416 false,
7417 text_layout_details,
7418 );
7419 selection.collapse_to(cursor, goal);
7420 });
7421 })
7422 }
7423
7424 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7425 let text_layout_details = &self.text_layout_details(cx);
7426 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7427 s.move_heads_with(|map, head, goal| {
7428 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7429 })
7430 })
7431 }
7432
7433 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, 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::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7438 })
7439 })
7440 }
7441
7442 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7443 let Some(row_count) = self.visible_row_count() else {
7444 return;
7445 };
7446
7447 let text_layout_details = &self.text_layout_details(cx);
7448
7449 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7450 s.move_heads_with(|map, head, goal| {
7451 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7452 })
7453 })
7454 }
7455
7456 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7457 if self.take_rename(true, cx).is_some() {
7458 return;
7459 }
7460
7461 if self
7462 .context_menu
7463 .write()
7464 .as_mut()
7465 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7466 .unwrap_or(false)
7467 {
7468 return;
7469 }
7470
7471 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7472 cx.propagate();
7473 return;
7474 }
7475
7476 let Some(row_count) = self.visible_row_count() else {
7477 return;
7478 };
7479
7480 let autoscroll = if action.center_cursor {
7481 Autoscroll::center()
7482 } else {
7483 Autoscroll::fit()
7484 };
7485
7486 let text_layout_details = &self.text_layout_details(cx);
7487
7488 self.change_selections(Some(autoscroll), cx, |s| {
7489 let line_mode = s.line_mode;
7490 s.move_with(|map, selection| {
7491 if !selection.is_empty() && !line_mode {
7492 selection.goal = SelectionGoal::None;
7493 }
7494 let (cursor, goal) = movement::up_by_rows(
7495 map,
7496 selection.end,
7497 row_count,
7498 selection.goal,
7499 false,
7500 text_layout_details,
7501 );
7502 selection.collapse_to(cursor, goal);
7503 });
7504 });
7505 }
7506
7507 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7508 let text_layout_details = &self.text_layout_details(cx);
7509 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7510 s.move_heads_with(|map, head, goal| {
7511 movement::up(map, head, goal, false, text_layout_details)
7512 })
7513 })
7514 }
7515
7516 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7517 self.take_rename(true, cx);
7518
7519 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7520 cx.propagate();
7521 return;
7522 }
7523
7524 let text_layout_details = &self.text_layout_details(cx);
7525 let selection_count = self.selections.count();
7526 let first_selection = self.selections.first_anchor();
7527
7528 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7529 let line_mode = s.line_mode;
7530 s.move_with(|map, selection| {
7531 if !selection.is_empty() && !line_mode {
7532 selection.goal = SelectionGoal::None;
7533 }
7534 let (cursor, goal) = movement::down(
7535 map,
7536 selection.end,
7537 selection.goal,
7538 false,
7539 text_layout_details,
7540 );
7541 selection.collapse_to(cursor, goal);
7542 });
7543 });
7544
7545 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7546 {
7547 cx.propagate();
7548 }
7549 }
7550
7551 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7552 let Some(row_count) = self.visible_row_count() else {
7553 return;
7554 };
7555
7556 let text_layout_details = &self.text_layout_details(cx);
7557
7558 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7559 s.move_heads_with(|map, head, goal| {
7560 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7561 })
7562 })
7563 }
7564
7565 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7566 if self.take_rename(true, cx).is_some() {
7567 return;
7568 }
7569
7570 if self
7571 .context_menu
7572 .write()
7573 .as_mut()
7574 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7575 .unwrap_or(false)
7576 {
7577 return;
7578 }
7579
7580 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7581 cx.propagate();
7582 return;
7583 }
7584
7585 let Some(row_count) = self.visible_row_count() else {
7586 return;
7587 };
7588
7589 let autoscroll = if action.center_cursor {
7590 Autoscroll::center()
7591 } else {
7592 Autoscroll::fit()
7593 };
7594
7595 let text_layout_details = &self.text_layout_details(cx);
7596 self.change_selections(Some(autoscroll), cx, |s| {
7597 let line_mode = s.line_mode;
7598 s.move_with(|map, selection| {
7599 if !selection.is_empty() && !line_mode {
7600 selection.goal = SelectionGoal::None;
7601 }
7602 let (cursor, goal) = movement::down_by_rows(
7603 map,
7604 selection.end,
7605 row_count,
7606 selection.goal,
7607 false,
7608 text_layout_details,
7609 );
7610 selection.collapse_to(cursor, goal);
7611 });
7612 });
7613 }
7614
7615 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7616 let text_layout_details = &self.text_layout_details(cx);
7617 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7618 s.move_heads_with(|map, head, goal| {
7619 movement::down(map, head, goal, false, text_layout_details)
7620 })
7621 });
7622 }
7623
7624 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7625 if let Some(context_menu) = self.context_menu.write().as_mut() {
7626 context_menu.select_first(self.project.as_ref(), cx);
7627 }
7628 }
7629
7630 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7631 if let Some(context_menu) = self.context_menu.write().as_mut() {
7632 context_menu.select_prev(self.project.as_ref(), cx);
7633 }
7634 }
7635
7636 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7637 if let Some(context_menu) = self.context_menu.write().as_mut() {
7638 context_menu.select_next(self.project.as_ref(), cx);
7639 }
7640 }
7641
7642 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7643 if let Some(context_menu) = self.context_menu.write().as_mut() {
7644 context_menu.select_last(self.project.as_ref(), cx);
7645 }
7646 }
7647
7648 pub fn move_to_previous_word_start(
7649 &mut self,
7650 _: &MoveToPreviousWordStart,
7651 cx: &mut ViewContext<Self>,
7652 ) {
7653 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7654 s.move_cursors_with(|map, head, _| {
7655 (
7656 movement::previous_word_start(map, head),
7657 SelectionGoal::None,
7658 )
7659 });
7660 })
7661 }
7662
7663 pub fn move_to_previous_subword_start(
7664 &mut self,
7665 _: &MoveToPreviousSubwordStart,
7666 cx: &mut ViewContext<Self>,
7667 ) {
7668 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7669 s.move_cursors_with(|map, head, _| {
7670 (
7671 movement::previous_subword_start(map, head),
7672 SelectionGoal::None,
7673 )
7674 });
7675 })
7676 }
7677
7678 pub fn select_to_previous_word_start(
7679 &mut self,
7680 _: &SelectToPreviousWordStart,
7681 cx: &mut ViewContext<Self>,
7682 ) {
7683 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7684 s.move_heads_with(|map, head, _| {
7685 (
7686 movement::previous_word_start(map, head),
7687 SelectionGoal::None,
7688 )
7689 });
7690 })
7691 }
7692
7693 pub fn select_to_previous_subword_start(
7694 &mut self,
7695 _: &SelectToPreviousSubwordStart,
7696 cx: &mut ViewContext<Self>,
7697 ) {
7698 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7699 s.move_heads_with(|map, head, _| {
7700 (
7701 movement::previous_subword_start(map, head),
7702 SelectionGoal::None,
7703 )
7704 });
7705 })
7706 }
7707
7708 pub fn delete_to_previous_word_start(
7709 &mut self,
7710 action: &DeleteToPreviousWordStart,
7711 cx: &mut ViewContext<Self>,
7712 ) {
7713 self.transact(cx, |this, cx| {
7714 this.select_autoclose_pair(cx);
7715 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7716 let line_mode = s.line_mode;
7717 s.move_with(|map, selection| {
7718 if selection.is_empty() && !line_mode {
7719 let cursor = if action.ignore_newlines {
7720 movement::previous_word_start(map, selection.head())
7721 } else {
7722 movement::previous_word_start_or_newline(map, selection.head())
7723 };
7724 selection.set_head(cursor, SelectionGoal::None);
7725 }
7726 });
7727 });
7728 this.insert("", cx);
7729 });
7730 }
7731
7732 pub fn delete_to_previous_subword_start(
7733 &mut self,
7734 _: &DeleteToPreviousSubwordStart,
7735 cx: &mut ViewContext<Self>,
7736 ) {
7737 self.transact(cx, |this, cx| {
7738 this.select_autoclose_pair(cx);
7739 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7740 let line_mode = s.line_mode;
7741 s.move_with(|map, selection| {
7742 if selection.is_empty() && !line_mode {
7743 let cursor = movement::previous_subword_start(map, selection.head());
7744 selection.set_head(cursor, SelectionGoal::None);
7745 }
7746 });
7747 });
7748 this.insert("", cx);
7749 });
7750 }
7751
7752 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7753 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7754 s.move_cursors_with(|map, head, _| {
7755 (movement::next_word_end(map, head), SelectionGoal::None)
7756 });
7757 })
7758 }
7759
7760 pub fn move_to_next_subword_end(
7761 &mut self,
7762 _: &MoveToNextSubwordEnd,
7763 cx: &mut ViewContext<Self>,
7764 ) {
7765 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7766 s.move_cursors_with(|map, head, _| {
7767 (movement::next_subword_end(map, head), SelectionGoal::None)
7768 });
7769 })
7770 }
7771
7772 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7773 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7774 s.move_heads_with(|map, head, _| {
7775 (movement::next_word_end(map, head), SelectionGoal::None)
7776 });
7777 })
7778 }
7779
7780 pub fn select_to_next_subword_end(
7781 &mut self,
7782 _: &SelectToNextSubwordEnd,
7783 cx: &mut ViewContext<Self>,
7784 ) {
7785 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7786 s.move_heads_with(|map, head, _| {
7787 (movement::next_subword_end(map, head), SelectionGoal::None)
7788 });
7789 })
7790 }
7791
7792 pub fn delete_to_next_word_end(
7793 &mut self,
7794 action: &DeleteToNextWordEnd,
7795 cx: &mut ViewContext<Self>,
7796 ) {
7797 self.transact(cx, |this, cx| {
7798 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7799 let line_mode = s.line_mode;
7800 s.move_with(|map, selection| {
7801 if selection.is_empty() && !line_mode {
7802 let cursor = if action.ignore_newlines {
7803 movement::next_word_end(map, selection.head())
7804 } else {
7805 movement::next_word_end_or_newline(map, selection.head())
7806 };
7807 selection.set_head(cursor, SelectionGoal::None);
7808 }
7809 });
7810 });
7811 this.insert("", cx);
7812 });
7813 }
7814
7815 pub fn delete_to_next_subword_end(
7816 &mut self,
7817 _: &DeleteToNextSubwordEnd,
7818 cx: &mut ViewContext<Self>,
7819 ) {
7820 self.transact(cx, |this, cx| {
7821 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7822 s.move_with(|map, selection| {
7823 if selection.is_empty() {
7824 let cursor = movement::next_subword_end(map, selection.head());
7825 selection.set_head(cursor, SelectionGoal::None);
7826 }
7827 });
7828 });
7829 this.insert("", cx);
7830 });
7831 }
7832
7833 pub fn move_to_beginning_of_line(
7834 &mut self,
7835 action: &MoveToBeginningOfLine,
7836 cx: &mut ViewContext<Self>,
7837 ) {
7838 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7839 s.move_cursors_with(|map, head, _| {
7840 (
7841 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7842 SelectionGoal::None,
7843 )
7844 });
7845 })
7846 }
7847
7848 pub fn select_to_beginning_of_line(
7849 &mut self,
7850 action: &SelectToBeginningOfLine,
7851 cx: &mut ViewContext<Self>,
7852 ) {
7853 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7854 s.move_heads_with(|map, head, _| {
7855 (
7856 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7857 SelectionGoal::None,
7858 )
7859 });
7860 });
7861 }
7862
7863 pub fn delete_to_beginning_of_line(
7864 &mut self,
7865 _: &DeleteToBeginningOfLine,
7866 cx: &mut ViewContext<Self>,
7867 ) {
7868 self.transact(cx, |this, cx| {
7869 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7870 s.move_with(|_, selection| {
7871 selection.reversed = true;
7872 });
7873 });
7874
7875 this.select_to_beginning_of_line(
7876 &SelectToBeginningOfLine {
7877 stop_at_soft_wraps: false,
7878 },
7879 cx,
7880 );
7881 this.backspace(&Backspace, cx);
7882 });
7883 }
7884
7885 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7886 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7887 s.move_cursors_with(|map, head, _| {
7888 (
7889 movement::line_end(map, head, action.stop_at_soft_wraps),
7890 SelectionGoal::None,
7891 )
7892 });
7893 })
7894 }
7895
7896 pub fn select_to_end_of_line(
7897 &mut self,
7898 action: &SelectToEndOfLine,
7899 cx: &mut ViewContext<Self>,
7900 ) {
7901 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7902 s.move_heads_with(|map, head, _| {
7903 (
7904 movement::line_end(map, head, action.stop_at_soft_wraps),
7905 SelectionGoal::None,
7906 )
7907 });
7908 })
7909 }
7910
7911 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7912 self.transact(cx, |this, cx| {
7913 this.select_to_end_of_line(
7914 &SelectToEndOfLine {
7915 stop_at_soft_wraps: false,
7916 },
7917 cx,
7918 );
7919 this.delete(&Delete, cx);
7920 });
7921 }
7922
7923 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7924 self.transact(cx, |this, cx| {
7925 this.select_to_end_of_line(
7926 &SelectToEndOfLine {
7927 stop_at_soft_wraps: false,
7928 },
7929 cx,
7930 );
7931 this.cut(&Cut, cx);
7932 });
7933 }
7934
7935 pub fn move_to_start_of_paragraph(
7936 &mut self,
7937 _: &MoveToStartOfParagraph,
7938 cx: &mut ViewContext<Self>,
7939 ) {
7940 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7941 cx.propagate();
7942 return;
7943 }
7944
7945 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7946 s.move_with(|map, selection| {
7947 selection.collapse_to(
7948 movement::start_of_paragraph(map, selection.head(), 1),
7949 SelectionGoal::None,
7950 )
7951 });
7952 })
7953 }
7954
7955 pub fn move_to_end_of_paragraph(
7956 &mut self,
7957 _: &MoveToEndOfParagraph,
7958 cx: &mut ViewContext<Self>,
7959 ) {
7960 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7961 cx.propagate();
7962 return;
7963 }
7964
7965 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7966 s.move_with(|map, selection| {
7967 selection.collapse_to(
7968 movement::end_of_paragraph(map, selection.head(), 1),
7969 SelectionGoal::None,
7970 )
7971 });
7972 })
7973 }
7974
7975 pub fn select_to_start_of_paragraph(
7976 &mut self,
7977 _: &SelectToStartOfParagraph,
7978 cx: &mut ViewContext<Self>,
7979 ) {
7980 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7981 cx.propagate();
7982 return;
7983 }
7984
7985 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7986 s.move_heads_with(|map, head, _| {
7987 (
7988 movement::start_of_paragraph(map, head, 1),
7989 SelectionGoal::None,
7990 )
7991 });
7992 })
7993 }
7994
7995 pub fn select_to_end_of_paragraph(
7996 &mut self,
7997 _: &SelectToEndOfParagraph,
7998 cx: &mut ViewContext<Self>,
7999 ) {
8000 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8001 cx.propagate();
8002 return;
8003 }
8004
8005 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8006 s.move_heads_with(|map, head, _| {
8007 (
8008 movement::end_of_paragraph(map, head, 1),
8009 SelectionGoal::None,
8010 )
8011 });
8012 })
8013 }
8014
8015 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
8016 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8017 cx.propagate();
8018 return;
8019 }
8020
8021 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8022 s.select_ranges(vec![0..0]);
8023 });
8024 }
8025
8026 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
8027 let mut selection = self.selections.last::<Point>(cx);
8028 selection.set_head(Point::zero(), SelectionGoal::None);
8029
8030 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8031 s.select(vec![selection]);
8032 });
8033 }
8034
8035 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
8036 if matches!(self.mode, EditorMode::SingleLine { .. }) {
8037 cx.propagate();
8038 return;
8039 }
8040
8041 let cursor = self.buffer.read(cx).read(cx).len();
8042 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8043 s.select_ranges(vec![cursor..cursor])
8044 });
8045 }
8046
8047 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8048 self.nav_history = nav_history;
8049 }
8050
8051 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8052 self.nav_history.as_ref()
8053 }
8054
8055 fn push_to_nav_history(
8056 &mut self,
8057 cursor_anchor: Anchor,
8058 new_position: Option<Point>,
8059 cx: &mut ViewContext<Self>,
8060 ) {
8061 if let Some(nav_history) = self.nav_history.as_mut() {
8062 let buffer = self.buffer.read(cx).read(cx);
8063 let cursor_position = cursor_anchor.to_point(&buffer);
8064 let scroll_state = self.scroll_manager.anchor();
8065 let scroll_top_row = scroll_state.top_row(&buffer);
8066 drop(buffer);
8067
8068 if let Some(new_position) = new_position {
8069 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8070 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8071 return;
8072 }
8073 }
8074
8075 nav_history.push(
8076 Some(NavigationData {
8077 cursor_anchor,
8078 cursor_position,
8079 scroll_anchor: scroll_state,
8080 scroll_top_row,
8081 }),
8082 cx,
8083 );
8084 }
8085 }
8086
8087 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8088 let buffer = self.buffer.read(cx).snapshot(cx);
8089 let mut selection = self.selections.first::<usize>(cx);
8090 selection.set_head(buffer.len(), SelectionGoal::None);
8091 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8092 s.select(vec![selection]);
8093 });
8094 }
8095
8096 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8097 let end = self.buffer.read(cx).read(cx).len();
8098 self.change_selections(None, cx, |s| {
8099 s.select_ranges(vec![0..end]);
8100 });
8101 }
8102
8103 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8104 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8105 let mut selections = self.selections.all::<Point>(cx);
8106 let max_point = display_map.buffer_snapshot.max_point();
8107 for selection in &mut selections {
8108 let rows = selection.spanned_rows(true, &display_map);
8109 selection.start = Point::new(rows.start.0, 0);
8110 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8111 selection.reversed = false;
8112 }
8113 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8114 s.select(selections);
8115 });
8116 }
8117
8118 pub fn split_selection_into_lines(
8119 &mut self,
8120 _: &SplitSelectionIntoLines,
8121 cx: &mut ViewContext<Self>,
8122 ) {
8123 let mut to_unfold = Vec::new();
8124 let mut new_selection_ranges = Vec::new();
8125 {
8126 let selections = self.selections.all::<Point>(cx);
8127 let buffer = self.buffer.read(cx).read(cx);
8128 for selection in selections {
8129 for row in selection.start.row..selection.end.row {
8130 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8131 new_selection_ranges.push(cursor..cursor);
8132 }
8133 new_selection_ranges.push(selection.end..selection.end);
8134 to_unfold.push(selection.start..selection.end);
8135 }
8136 }
8137 self.unfold_ranges(to_unfold, true, true, cx);
8138 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8139 s.select_ranges(new_selection_ranges);
8140 });
8141 }
8142
8143 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8144 self.add_selection(true, cx);
8145 }
8146
8147 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8148 self.add_selection(false, cx);
8149 }
8150
8151 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8152 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8153 let mut selections = self.selections.all::<Point>(cx);
8154 let text_layout_details = self.text_layout_details(cx);
8155 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8156 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8157 let range = oldest_selection.display_range(&display_map).sorted();
8158
8159 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8160 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8161 let positions = start_x.min(end_x)..start_x.max(end_x);
8162
8163 selections.clear();
8164 let mut stack = Vec::new();
8165 for row in range.start.row().0..=range.end.row().0 {
8166 if let Some(selection) = self.selections.build_columnar_selection(
8167 &display_map,
8168 DisplayRow(row),
8169 &positions,
8170 oldest_selection.reversed,
8171 &text_layout_details,
8172 ) {
8173 stack.push(selection.id);
8174 selections.push(selection);
8175 }
8176 }
8177
8178 if above {
8179 stack.reverse();
8180 }
8181
8182 AddSelectionsState { above, stack }
8183 });
8184
8185 let last_added_selection = *state.stack.last().unwrap();
8186 let mut new_selections = Vec::new();
8187 if above == state.above {
8188 let end_row = if above {
8189 DisplayRow(0)
8190 } else {
8191 display_map.max_point().row()
8192 };
8193
8194 'outer: for selection in selections {
8195 if selection.id == last_added_selection {
8196 let range = selection.display_range(&display_map).sorted();
8197 debug_assert_eq!(range.start.row(), range.end.row());
8198 let mut row = range.start.row();
8199 let positions =
8200 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8201 px(start)..px(end)
8202 } else {
8203 let start_x =
8204 display_map.x_for_display_point(range.start, &text_layout_details);
8205 let end_x =
8206 display_map.x_for_display_point(range.end, &text_layout_details);
8207 start_x.min(end_x)..start_x.max(end_x)
8208 };
8209
8210 while row != end_row {
8211 if above {
8212 row.0 -= 1;
8213 } else {
8214 row.0 += 1;
8215 }
8216
8217 if let Some(new_selection) = self.selections.build_columnar_selection(
8218 &display_map,
8219 row,
8220 &positions,
8221 selection.reversed,
8222 &text_layout_details,
8223 ) {
8224 state.stack.push(new_selection.id);
8225 if above {
8226 new_selections.push(new_selection);
8227 new_selections.push(selection);
8228 } else {
8229 new_selections.push(selection);
8230 new_selections.push(new_selection);
8231 }
8232
8233 continue 'outer;
8234 }
8235 }
8236 }
8237
8238 new_selections.push(selection);
8239 }
8240 } else {
8241 new_selections = selections;
8242 new_selections.retain(|s| s.id != last_added_selection);
8243 state.stack.pop();
8244 }
8245
8246 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8247 s.select(new_selections);
8248 });
8249 if state.stack.len() > 1 {
8250 self.add_selections_state = Some(state);
8251 }
8252 }
8253
8254 pub fn select_next_match_internal(
8255 &mut self,
8256 display_map: &DisplaySnapshot,
8257 replace_newest: bool,
8258 autoscroll: Option<Autoscroll>,
8259 cx: &mut ViewContext<Self>,
8260 ) -> Result<()> {
8261 fn select_next_match_ranges(
8262 this: &mut Editor,
8263 range: Range<usize>,
8264 replace_newest: bool,
8265 auto_scroll: Option<Autoscroll>,
8266 cx: &mut ViewContext<Editor>,
8267 ) {
8268 this.unfold_ranges([range.clone()], false, true, cx);
8269 this.change_selections(auto_scroll, cx, |s| {
8270 if replace_newest {
8271 s.delete(s.newest_anchor().id);
8272 }
8273 s.insert_range(range.clone());
8274 });
8275 }
8276
8277 let buffer = &display_map.buffer_snapshot;
8278 let mut selections = self.selections.all::<usize>(cx);
8279 if let Some(mut select_next_state) = self.select_next_state.take() {
8280 let query = &select_next_state.query;
8281 if !select_next_state.done {
8282 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8283 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8284 let mut next_selected_range = None;
8285
8286 let bytes_after_last_selection =
8287 buffer.bytes_in_range(last_selection.end..buffer.len());
8288 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8289 let query_matches = query
8290 .stream_find_iter(bytes_after_last_selection)
8291 .map(|result| (last_selection.end, result))
8292 .chain(
8293 query
8294 .stream_find_iter(bytes_before_first_selection)
8295 .map(|result| (0, result)),
8296 );
8297
8298 for (start_offset, query_match) in query_matches {
8299 let query_match = query_match.unwrap(); // can only fail due to I/O
8300 let offset_range =
8301 start_offset + query_match.start()..start_offset + query_match.end();
8302 let display_range = offset_range.start.to_display_point(display_map)
8303 ..offset_range.end.to_display_point(display_map);
8304
8305 if !select_next_state.wordwise
8306 || (!movement::is_inside_word(display_map, display_range.start)
8307 && !movement::is_inside_word(display_map, display_range.end))
8308 {
8309 // TODO: This is n^2, because we might check all the selections
8310 if !selections
8311 .iter()
8312 .any(|selection| selection.range().overlaps(&offset_range))
8313 {
8314 next_selected_range = Some(offset_range);
8315 break;
8316 }
8317 }
8318 }
8319
8320 if let Some(next_selected_range) = next_selected_range {
8321 select_next_match_ranges(
8322 self,
8323 next_selected_range,
8324 replace_newest,
8325 autoscroll,
8326 cx,
8327 );
8328 } else {
8329 select_next_state.done = true;
8330 }
8331 }
8332
8333 self.select_next_state = Some(select_next_state);
8334 } else {
8335 let mut only_carets = true;
8336 let mut same_text_selected = true;
8337 let mut selected_text = None;
8338
8339 let mut selections_iter = selections.iter().peekable();
8340 while let Some(selection) = selections_iter.next() {
8341 if selection.start != selection.end {
8342 only_carets = false;
8343 }
8344
8345 if same_text_selected {
8346 if selected_text.is_none() {
8347 selected_text =
8348 Some(buffer.text_for_range(selection.range()).collect::<String>());
8349 }
8350
8351 if let Some(next_selection) = selections_iter.peek() {
8352 if next_selection.range().len() == selection.range().len() {
8353 let next_selected_text = buffer
8354 .text_for_range(next_selection.range())
8355 .collect::<String>();
8356 if Some(next_selected_text) != selected_text {
8357 same_text_selected = false;
8358 selected_text = None;
8359 }
8360 } else {
8361 same_text_selected = false;
8362 selected_text = None;
8363 }
8364 }
8365 }
8366 }
8367
8368 if only_carets {
8369 for selection in &mut selections {
8370 let word_range = movement::surrounding_word(
8371 display_map,
8372 selection.start.to_display_point(display_map),
8373 );
8374 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8375 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8376 selection.goal = SelectionGoal::None;
8377 selection.reversed = false;
8378 select_next_match_ranges(
8379 self,
8380 selection.start..selection.end,
8381 replace_newest,
8382 autoscroll,
8383 cx,
8384 );
8385 }
8386
8387 if selections.len() == 1 {
8388 let selection = selections
8389 .last()
8390 .expect("ensured that there's only one selection");
8391 let query = buffer
8392 .text_for_range(selection.start..selection.end)
8393 .collect::<String>();
8394 let is_empty = query.is_empty();
8395 let select_state = SelectNextState {
8396 query: AhoCorasick::new(&[query])?,
8397 wordwise: true,
8398 done: is_empty,
8399 };
8400 self.select_next_state = Some(select_state);
8401 } else {
8402 self.select_next_state = None;
8403 }
8404 } else if let Some(selected_text) = selected_text {
8405 self.select_next_state = Some(SelectNextState {
8406 query: AhoCorasick::new(&[selected_text])?,
8407 wordwise: false,
8408 done: false,
8409 });
8410 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8411 }
8412 }
8413 Ok(())
8414 }
8415
8416 pub fn select_all_matches(
8417 &mut self,
8418 _action: &SelectAllMatches,
8419 cx: &mut ViewContext<Self>,
8420 ) -> Result<()> {
8421 self.push_to_selection_history();
8422 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8423
8424 self.select_next_match_internal(&display_map, false, None, cx)?;
8425 let Some(select_next_state) = self.select_next_state.as_mut() else {
8426 return Ok(());
8427 };
8428 if select_next_state.done {
8429 return Ok(());
8430 }
8431
8432 let mut new_selections = self.selections.all::<usize>(cx);
8433
8434 let buffer = &display_map.buffer_snapshot;
8435 let query_matches = select_next_state
8436 .query
8437 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8438
8439 for query_match in query_matches {
8440 let query_match = query_match.unwrap(); // can only fail due to I/O
8441 let offset_range = query_match.start()..query_match.end();
8442 let display_range = offset_range.start.to_display_point(&display_map)
8443 ..offset_range.end.to_display_point(&display_map);
8444
8445 if !select_next_state.wordwise
8446 || (!movement::is_inside_word(&display_map, display_range.start)
8447 && !movement::is_inside_word(&display_map, display_range.end))
8448 {
8449 self.selections.change_with(cx, |selections| {
8450 new_selections.push(Selection {
8451 id: selections.new_selection_id(),
8452 start: offset_range.start,
8453 end: offset_range.end,
8454 reversed: false,
8455 goal: SelectionGoal::None,
8456 });
8457 });
8458 }
8459 }
8460
8461 new_selections.sort_by_key(|selection| selection.start);
8462 let mut ix = 0;
8463 while ix + 1 < new_selections.len() {
8464 let current_selection = &new_selections[ix];
8465 let next_selection = &new_selections[ix + 1];
8466 if current_selection.range().overlaps(&next_selection.range()) {
8467 if current_selection.id < next_selection.id {
8468 new_selections.remove(ix + 1);
8469 } else {
8470 new_selections.remove(ix);
8471 }
8472 } else {
8473 ix += 1;
8474 }
8475 }
8476
8477 select_next_state.done = true;
8478 self.unfold_ranges(
8479 new_selections.iter().map(|selection| selection.range()),
8480 false,
8481 false,
8482 cx,
8483 );
8484 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8485 selections.select(new_selections)
8486 });
8487
8488 Ok(())
8489 }
8490
8491 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8492 self.push_to_selection_history();
8493 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8494 self.select_next_match_internal(
8495 &display_map,
8496 action.replace_newest,
8497 Some(Autoscroll::newest()),
8498 cx,
8499 )?;
8500 Ok(())
8501 }
8502
8503 pub fn select_previous(
8504 &mut self,
8505 action: &SelectPrevious,
8506 cx: &mut ViewContext<Self>,
8507 ) -> Result<()> {
8508 self.push_to_selection_history();
8509 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8510 let buffer = &display_map.buffer_snapshot;
8511 let mut selections = self.selections.all::<usize>(cx);
8512 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8513 let query = &select_prev_state.query;
8514 if !select_prev_state.done {
8515 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8516 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8517 let mut next_selected_range = None;
8518 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8519 let bytes_before_last_selection =
8520 buffer.reversed_bytes_in_range(0..last_selection.start);
8521 let bytes_after_first_selection =
8522 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8523 let query_matches = query
8524 .stream_find_iter(bytes_before_last_selection)
8525 .map(|result| (last_selection.start, result))
8526 .chain(
8527 query
8528 .stream_find_iter(bytes_after_first_selection)
8529 .map(|result| (buffer.len(), result)),
8530 );
8531 for (end_offset, query_match) in query_matches {
8532 let query_match = query_match.unwrap(); // can only fail due to I/O
8533 let offset_range =
8534 end_offset - query_match.end()..end_offset - query_match.start();
8535 let display_range = offset_range.start.to_display_point(&display_map)
8536 ..offset_range.end.to_display_point(&display_map);
8537
8538 if !select_prev_state.wordwise
8539 || (!movement::is_inside_word(&display_map, display_range.start)
8540 && !movement::is_inside_word(&display_map, display_range.end))
8541 {
8542 next_selected_range = Some(offset_range);
8543 break;
8544 }
8545 }
8546
8547 if let Some(next_selected_range) = next_selected_range {
8548 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8549 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8550 if action.replace_newest {
8551 s.delete(s.newest_anchor().id);
8552 }
8553 s.insert_range(next_selected_range);
8554 });
8555 } else {
8556 select_prev_state.done = true;
8557 }
8558 }
8559
8560 self.select_prev_state = Some(select_prev_state);
8561 } else {
8562 let mut only_carets = true;
8563 let mut same_text_selected = true;
8564 let mut selected_text = None;
8565
8566 let mut selections_iter = selections.iter().peekable();
8567 while let Some(selection) = selections_iter.next() {
8568 if selection.start != selection.end {
8569 only_carets = false;
8570 }
8571
8572 if same_text_selected {
8573 if selected_text.is_none() {
8574 selected_text =
8575 Some(buffer.text_for_range(selection.range()).collect::<String>());
8576 }
8577
8578 if let Some(next_selection) = selections_iter.peek() {
8579 if next_selection.range().len() == selection.range().len() {
8580 let next_selected_text = buffer
8581 .text_for_range(next_selection.range())
8582 .collect::<String>();
8583 if Some(next_selected_text) != selected_text {
8584 same_text_selected = false;
8585 selected_text = None;
8586 }
8587 } else {
8588 same_text_selected = false;
8589 selected_text = None;
8590 }
8591 }
8592 }
8593 }
8594
8595 if only_carets {
8596 for selection in &mut selections {
8597 let word_range = movement::surrounding_word(
8598 &display_map,
8599 selection.start.to_display_point(&display_map),
8600 );
8601 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8602 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8603 selection.goal = SelectionGoal::None;
8604 selection.reversed = false;
8605 }
8606 if selections.len() == 1 {
8607 let selection = selections
8608 .last()
8609 .expect("ensured that there's only one selection");
8610 let query = buffer
8611 .text_for_range(selection.start..selection.end)
8612 .collect::<String>();
8613 let is_empty = query.is_empty();
8614 let select_state = SelectNextState {
8615 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8616 wordwise: true,
8617 done: is_empty,
8618 };
8619 self.select_prev_state = Some(select_state);
8620 } else {
8621 self.select_prev_state = None;
8622 }
8623
8624 self.unfold_ranges(
8625 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8626 false,
8627 true,
8628 cx,
8629 );
8630 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8631 s.select(selections);
8632 });
8633 } else if let Some(selected_text) = selected_text {
8634 self.select_prev_state = Some(SelectNextState {
8635 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8636 wordwise: false,
8637 done: false,
8638 });
8639 self.select_previous(action, cx)?;
8640 }
8641 }
8642 Ok(())
8643 }
8644
8645 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8646 let text_layout_details = &self.text_layout_details(cx);
8647 self.transact(cx, |this, cx| {
8648 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8649 let mut edits = Vec::new();
8650 let mut selection_edit_ranges = Vec::new();
8651 let mut last_toggled_row = None;
8652 let snapshot = this.buffer.read(cx).read(cx);
8653 let empty_str: Arc<str> = Arc::default();
8654 let mut suffixes_inserted = Vec::new();
8655
8656 fn comment_prefix_range(
8657 snapshot: &MultiBufferSnapshot,
8658 row: MultiBufferRow,
8659 comment_prefix: &str,
8660 comment_prefix_whitespace: &str,
8661 ) -> Range<Point> {
8662 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8663
8664 let mut line_bytes = snapshot
8665 .bytes_in_range(start..snapshot.max_point())
8666 .flatten()
8667 .copied();
8668
8669 // If this line currently begins with the line comment prefix, then record
8670 // the range containing the prefix.
8671 if line_bytes
8672 .by_ref()
8673 .take(comment_prefix.len())
8674 .eq(comment_prefix.bytes())
8675 {
8676 // Include any whitespace that matches the comment prefix.
8677 let matching_whitespace_len = line_bytes
8678 .zip(comment_prefix_whitespace.bytes())
8679 .take_while(|(a, b)| a == b)
8680 .count() as u32;
8681 let end = Point::new(
8682 start.row,
8683 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8684 );
8685 start..end
8686 } else {
8687 start..start
8688 }
8689 }
8690
8691 fn comment_suffix_range(
8692 snapshot: &MultiBufferSnapshot,
8693 row: MultiBufferRow,
8694 comment_suffix: &str,
8695 comment_suffix_has_leading_space: bool,
8696 ) -> Range<Point> {
8697 let end = Point::new(row.0, snapshot.line_len(row));
8698 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8699
8700 let mut line_end_bytes = snapshot
8701 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8702 .flatten()
8703 .copied();
8704
8705 let leading_space_len = if suffix_start_column > 0
8706 && line_end_bytes.next() == Some(b' ')
8707 && comment_suffix_has_leading_space
8708 {
8709 1
8710 } else {
8711 0
8712 };
8713
8714 // If this line currently begins with the line comment prefix, then record
8715 // the range containing the prefix.
8716 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8717 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8718 start..end
8719 } else {
8720 end..end
8721 }
8722 }
8723
8724 // TODO: Handle selections that cross excerpts
8725 for selection in &mut selections {
8726 let start_column = snapshot
8727 .indent_size_for_line(MultiBufferRow(selection.start.row))
8728 .len;
8729 let language = if let Some(language) =
8730 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8731 {
8732 language
8733 } else {
8734 continue;
8735 };
8736
8737 selection_edit_ranges.clear();
8738
8739 // If multiple selections contain a given row, avoid processing that
8740 // row more than once.
8741 let mut start_row = MultiBufferRow(selection.start.row);
8742 if last_toggled_row == Some(start_row) {
8743 start_row = start_row.next_row();
8744 }
8745 let end_row =
8746 if selection.end.row > selection.start.row && selection.end.column == 0 {
8747 MultiBufferRow(selection.end.row - 1)
8748 } else {
8749 MultiBufferRow(selection.end.row)
8750 };
8751 last_toggled_row = Some(end_row);
8752
8753 if start_row > end_row {
8754 continue;
8755 }
8756
8757 // If the language has line comments, toggle those.
8758 let full_comment_prefixes = language.line_comment_prefixes();
8759 if !full_comment_prefixes.is_empty() {
8760 let first_prefix = full_comment_prefixes
8761 .first()
8762 .expect("prefixes is non-empty");
8763 let prefix_trimmed_lengths = full_comment_prefixes
8764 .iter()
8765 .map(|p| p.trim_end_matches(' ').len())
8766 .collect::<SmallVec<[usize; 4]>>();
8767
8768 let mut all_selection_lines_are_comments = true;
8769
8770 for row in start_row.0..=end_row.0 {
8771 let row = MultiBufferRow(row);
8772 if start_row < end_row && snapshot.is_line_blank(row) {
8773 continue;
8774 }
8775
8776 let prefix_range = full_comment_prefixes
8777 .iter()
8778 .zip(prefix_trimmed_lengths.iter().copied())
8779 .map(|(prefix, trimmed_prefix_len)| {
8780 comment_prefix_range(
8781 snapshot.deref(),
8782 row,
8783 &prefix[..trimmed_prefix_len],
8784 &prefix[trimmed_prefix_len..],
8785 )
8786 })
8787 .max_by_key(|range| range.end.column - range.start.column)
8788 .expect("prefixes is non-empty");
8789
8790 if prefix_range.is_empty() {
8791 all_selection_lines_are_comments = false;
8792 }
8793
8794 selection_edit_ranges.push(prefix_range);
8795 }
8796
8797 if all_selection_lines_are_comments {
8798 edits.extend(
8799 selection_edit_ranges
8800 .iter()
8801 .cloned()
8802 .map(|range| (range, empty_str.clone())),
8803 );
8804 } else {
8805 let min_column = selection_edit_ranges
8806 .iter()
8807 .map(|range| range.start.column)
8808 .min()
8809 .unwrap_or(0);
8810 edits.extend(selection_edit_ranges.iter().map(|range| {
8811 let position = Point::new(range.start.row, min_column);
8812 (position..position, first_prefix.clone())
8813 }));
8814 }
8815 } else if let Some((full_comment_prefix, comment_suffix)) =
8816 language.block_comment_delimiters()
8817 {
8818 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8819 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8820 let prefix_range = comment_prefix_range(
8821 snapshot.deref(),
8822 start_row,
8823 comment_prefix,
8824 comment_prefix_whitespace,
8825 );
8826 let suffix_range = comment_suffix_range(
8827 snapshot.deref(),
8828 end_row,
8829 comment_suffix.trim_start_matches(' '),
8830 comment_suffix.starts_with(' '),
8831 );
8832
8833 if prefix_range.is_empty() || suffix_range.is_empty() {
8834 edits.push((
8835 prefix_range.start..prefix_range.start,
8836 full_comment_prefix.clone(),
8837 ));
8838 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8839 suffixes_inserted.push((end_row, comment_suffix.len()));
8840 } else {
8841 edits.push((prefix_range, empty_str.clone()));
8842 edits.push((suffix_range, empty_str.clone()));
8843 }
8844 } else {
8845 continue;
8846 }
8847 }
8848
8849 drop(snapshot);
8850 this.buffer.update(cx, |buffer, cx| {
8851 buffer.edit(edits, None, cx);
8852 });
8853
8854 // Adjust selections so that they end before any comment suffixes that
8855 // were inserted.
8856 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8857 let mut selections = this.selections.all::<Point>(cx);
8858 let snapshot = this.buffer.read(cx).read(cx);
8859 for selection in &mut selections {
8860 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8861 match row.cmp(&MultiBufferRow(selection.end.row)) {
8862 Ordering::Less => {
8863 suffixes_inserted.next();
8864 continue;
8865 }
8866 Ordering::Greater => break,
8867 Ordering::Equal => {
8868 if selection.end.column == snapshot.line_len(row) {
8869 if selection.is_empty() {
8870 selection.start.column -= suffix_len as u32;
8871 }
8872 selection.end.column -= suffix_len as u32;
8873 }
8874 break;
8875 }
8876 }
8877 }
8878 }
8879
8880 drop(snapshot);
8881 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8882
8883 let selections = this.selections.all::<Point>(cx);
8884 let selections_on_single_row = selections.windows(2).all(|selections| {
8885 selections[0].start.row == selections[1].start.row
8886 && selections[0].end.row == selections[1].end.row
8887 && selections[0].start.row == selections[0].end.row
8888 });
8889 let selections_selecting = selections
8890 .iter()
8891 .any(|selection| selection.start != selection.end);
8892 let advance_downwards = action.advance_downwards
8893 && selections_on_single_row
8894 && !selections_selecting
8895 && !matches!(this.mode, EditorMode::SingleLine { .. });
8896
8897 if advance_downwards {
8898 let snapshot = this.buffer.read(cx).snapshot(cx);
8899
8900 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8901 s.move_cursors_with(|display_snapshot, display_point, _| {
8902 let mut point = display_point.to_point(display_snapshot);
8903 point.row += 1;
8904 point = snapshot.clip_point(point, Bias::Left);
8905 let display_point = point.to_display_point(display_snapshot);
8906 let goal = SelectionGoal::HorizontalPosition(
8907 display_snapshot
8908 .x_for_display_point(display_point, text_layout_details)
8909 .into(),
8910 );
8911 (display_point, goal)
8912 })
8913 });
8914 }
8915 });
8916 }
8917
8918 pub fn select_enclosing_symbol(
8919 &mut self,
8920 _: &SelectEnclosingSymbol,
8921 cx: &mut ViewContext<Self>,
8922 ) {
8923 let buffer = self.buffer.read(cx).snapshot(cx);
8924 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8925
8926 fn update_selection(
8927 selection: &Selection<usize>,
8928 buffer_snap: &MultiBufferSnapshot,
8929 ) -> Option<Selection<usize>> {
8930 let cursor = selection.head();
8931 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8932 for symbol in symbols.iter().rev() {
8933 let start = symbol.range.start.to_offset(buffer_snap);
8934 let end = symbol.range.end.to_offset(buffer_snap);
8935 let new_range = start..end;
8936 if start < selection.start || end > selection.end {
8937 return Some(Selection {
8938 id: selection.id,
8939 start: new_range.start,
8940 end: new_range.end,
8941 goal: SelectionGoal::None,
8942 reversed: selection.reversed,
8943 });
8944 }
8945 }
8946 None
8947 }
8948
8949 let mut selected_larger_symbol = false;
8950 let new_selections = old_selections
8951 .iter()
8952 .map(|selection| match update_selection(selection, &buffer) {
8953 Some(new_selection) => {
8954 if new_selection.range() != selection.range() {
8955 selected_larger_symbol = true;
8956 }
8957 new_selection
8958 }
8959 None => selection.clone(),
8960 })
8961 .collect::<Vec<_>>();
8962
8963 if selected_larger_symbol {
8964 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8965 s.select(new_selections);
8966 });
8967 }
8968 }
8969
8970 pub fn select_larger_syntax_node(
8971 &mut self,
8972 _: &SelectLargerSyntaxNode,
8973 cx: &mut ViewContext<Self>,
8974 ) {
8975 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8976 let buffer = self.buffer.read(cx).snapshot(cx);
8977 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8978
8979 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8980 let mut selected_larger_node = false;
8981 let new_selections = old_selections
8982 .iter()
8983 .map(|selection| {
8984 let old_range = selection.start..selection.end;
8985 let mut new_range = old_range.clone();
8986 while let Some(containing_range) =
8987 buffer.range_for_syntax_ancestor(new_range.clone())
8988 {
8989 new_range = containing_range;
8990 if !display_map.intersects_fold(new_range.start)
8991 && !display_map.intersects_fold(new_range.end)
8992 {
8993 break;
8994 }
8995 }
8996
8997 selected_larger_node |= new_range != old_range;
8998 Selection {
8999 id: selection.id,
9000 start: new_range.start,
9001 end: new_range.end,
9002 goal: SelectionGoal::None,
9003 reversed: selection.reversed,
9004 }
9005 })
9006 .collect::<Vec<_>>();
9007
9008 if selected_larger_node {
9009 stack.push(old_selections);
9010 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9011 s.select(new_selections);
9012 });
9013 }
9014 self.select_larger_syntax_node_stack = stack;
9015 }
9016
9017 pub fn select_smaller_syntax_node(
9018 &mut self,
9019 _: &SelectSmallerSyntaxNode,
9020 cx: &mut ViewContext<Self>,
9021 ) {
9022 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
9023 if let Some(selections) = stack.pop() {
9024 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9025 s.select(selections.to_vec());
9026 });
9027 }
9028 self.select_larger_syntax_node_stack = stack;
9029 }
9030
9031 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
9032 if !EditorSettings::get_global(cx).gutter.runnables {
9033 self.clear_tasks();
9034 return Task::ready(());
9035 }
9036 let project = self.project.clone();
9037 cx.spawn(|this, mut cx| async move {
9038 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
9039 this.display_map.update(cx, |map, cx| map.snapshot(cx))
9040 }) else {
9041 return;
9042 };
9043
9044 let Some(project) = project else {
9045 return;
9046 };
9047
9048 let hide_runnables = project
9049 .update(&mut cx, |project, cx| {
9050 // Do not display any test indicators in non-dev server remote projects.
9051 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9052 })
9053 .unwrap_or(true);
9054 if hide_runnables {
9055 return;
9056 }
9057 let new_rows =
9058 cx.background_executor()
9059 .spawn({
9060 let snapshot = display_snapshot.clone();
9061 async move {
9062 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9063 }
9064 })
9065 .await;
9066 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9067
9068 this.update(&mut cx, |this, _| {
9069 this.clear_tasks();
9070 for (key, value) in rows {
9071 this.insert_tasks(key, value);
9072 }
9073 })
9074 .ok();
9075 })
9076 }
9077 fn fetch_runnable_ranges(
9078 snapshot: &DisplaySnapshot,
9079 range: Range<Anchor>,
9080 ) -> Vec<language::RunnableRange> {
9081 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9082 }
9083
9084 fn runnable_rows(
9085 project: Model<Project>,
9086 snapshot: DisplaySnapshot,
9087 runnable_ranges: Vec<RunnableRange>,
9088 mut cx: AsyncWindowContext,
9089 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9090 runnable_ranges
9091 .into_iter()
9092 .filter_map(|mut runnable| {
9093 let tasks = cx
9094 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9095 .ok()?;
9096 if tasks.is_empty() {
9097 return None;
9098 }
9099
9100 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9101
9102 let row = snapshot
9103 .buffer_snapshot
9104 .buffer_line_for_row(MultiBufferRow(point.row))?
9105 .1
9106 .start
9107 .row;
9108
9109 let context_range =
9110 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9111 Some((
9112 (runnable.buffer_id, row),
9113 RunnableTasks {
9114 templates: tasks,
9115 offset: MultiBufferOffset(runnable.run_range.start),
9116 context_range,
9117 column: point.column,
9118 extra_variables: runnable.extra_captures,
9119 },
9120 ))
9121 })
9122 .collect()
9123 }
9124
9125 fn templates_with_tags(
9126 project: &Model<Project>,
9127 runnable: &mut Runnable,
9128 cx: &WindowContext<'_>,
9129 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9130 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9131 let (worktree_id, file) = project
9132 .buffer_for_id(runnable.buffer, cx)
9133 .and_then(|buffer| buffer.read(cx).file())
9134 .map(|file| (file.worktree_id(cx), file.clone()))
9135 .unzip();
9136
9137 (project.task_inventory().clone(), worktree_id, file)
9138 });
9139
9140 let inventory = inventory.read(cx);
9141 let tags = mem::take(&mut runnable.tags);
9142 let mut tags: Vec<_> = tags
9143 .into_iter()
9144 .flat_map(|tag| {
9145 let tag = tag.0.clone();
9146 inventory
9147 .list_tasks(
9148 file.clone(),
9149 Some(runnable.language.clone()),
9150 worktree_id,
9151 cx,
9152 )
9153 .into_iter()
9154 .filter(move |(_, template)| {
9155 template.tags.iter().any(|source_tag| source_tag == &tag)
9156 })
9157 })
9158 .sorted_by_key(|(kind, _)| kind.to_owned())
9159 .collect();
9160 if let Some((leading_tag_source, _)) = tags.first() {
9161 // Strongest source wins; if we have worktree tag binding, prefer that to
9162 // global and language bindings;
9163 // if we have a global binding, prefer that to language binding.
9164 let first_mismatch = tags
9165 .iter()
9166 .position(|(tag_source, _)| tag_source != leading_tag_source);
9167 if let Some(index) = first_mismatch {
9168 tags.truncate(index);
9169 }
9170 }
9171
9172 tags
9173 }
9174
9175 pub fn move_to_enclosing_bracket(
9176 &mut self,
9177 _: &MoveToEnclosingBracket,
9178 cx: &mut ViewContext<Self>,
9179 ) {
9180 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9181 s.move_offsets_with(|snapshot, selection| {
9182 let Some(enclosing_bracket_ranges) =
9183 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9184 else {
9185 return;
9186 };
9187
9188 let mut best_length = usize::MAX;
9189 let mut best_inside = false;
9190 let mut best_in_bracket_range = false;
9191 let mut best_destination = None;
9192 for (open, close) in enclosing_bracket_ranges {
9193 let close = close.to_inclusive();
9194 let length = close.end() - open.start;
9195 let inside = selection.start >= open.end && selection.end <= *close.start();
9196 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9197 || close.contains(&selection.head());
9198
9199 // If best is next to a bracket and current isn't, skip
9200 if !in_bracket_range && best_in_bracket_range {
9201 continue;
9202 }
9203
9204 // Prefer smaller lengths unless best is inside and current isn't
9205 if length > best_length && (best_inside || !inside) {
9206 continue;
9207 }
9208
9209 best_length = length;
9210 best_inside = inside;
9211 best_in_bracket_range = in_bracket_range;
9212 best_destination = Some(
9213 if close.contains(&selection.start) && close.contains(&selection.end) {
9214 if inside {
9215 open.end
9216 } else {
9217 open.start
9218 }
9219 } else if inside {
9220 *close.start()
9221 } else {
9222 *close.end()
9223 },
9224 );
9225 }
9226
9227 if let Some(destination) = best_destination {
9228 selection.collapse_to(destination, SelectionGoal::None);
9229 }
9230 })
9231 });
9232 }
9233
9234 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9235 self.end_selection(cx);
9236 self.selection_history.mode = SelectionHistoryMode::Undoing;
9237 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9238 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9239 self.select_next_state = entry.select_next_state;
9240 self.select_prev_state = entry.select_prev_state;
9241 self.add_selections_state = entry.add_selections_state;
9242 self.request_autoscroll(Autoscroll::newest(), cx);
9243 }
9244 self.selection_history.mode = SelectionHistoryMode::Normal;
9245 }
9246
9247 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9248 self.end_selection(cx);
9249 self.selection_history.mode = SelectionHistoryMode::Redoing;
9250 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9251 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9252 self.select_next_state = entry.select_next_state;
9253 self.select_prev_state = entry.select_prev_state;
9254 self.add_selections_state = entry.add_selections_state;
9255 self.request_autoscroll(Autoscroll::newest(), cx);
9256 }
9257 self.selection_history.mode = SelectionHistoryMode::Normal;
9258 }
9259
9260 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9261 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9262 }
9263
9264 pub fn expand_excerpts_down(
9265 &mut self,
9266 action: &ExpandExcerptsDown,
9267 cx: &mut ViewContext<Self>,
9268 ) {
9269 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9270 }
9271
9272 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9273 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9274 }
9275
9276 pub fn expand_excerpts_for_direction(
9277 &mut self,
9278 lines: u32,
9279 direction: ExpandExcerptDirection,
9280 cx: &mut ViewContext<Self>,
9281 ) {
9282 let selections = self.selections.disjoint_anchors();
9283
9284 let lines = if lines == 0 {
9285 EditorSettings::get_global(cx).expand_excerpt_lines
9286 } else {
9287 lines
9288 };
9289
9290 self.buffer.update(cx, |buffer, cx| {
9291 buffer.expand_excerpts(
9292 selections
9293 .iter()
9294 .map(|selection| selection.head().excerpt_id)
9295 .dedup(),
9296 lines,
9297 direction,
9298 cx,
9299 )
9300 })
9301 }
9302
9303 pub fn expand_excerpt(
9304 &mut self,
9305 excerpt: ExcerptId,
9306 direction: ExpandExcerptDirection,
9307 cx: &mut ViewContext<Self>,
9308 ) {
9309 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9310 self.buffer.update(cx, |buffer, cx| {
9311 buffer.expand_excerpts([excerpt], lines, direction, cx)
9312 })
9313 }
9314
9315 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9316 self.go_to_diagnostic_impl(Direction::Next, cx)
9317 }
9318
9319 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9320 self.go_to_diagnostic_impl(Direction::Prev, cx)
9321 }
9322
9323 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9324 let buffer = self.buffer.read(cx).snapshot(cx);
9325 let selection = self.selections.newest::<usize>(cx);
9326
9327 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9328 if direction == Direction::Next {
9329 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9330 let (group_id, jump_to) = popover.activation_info();
9331 if self.activate_diagnostics(group_id, cx) {
9332 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9333 let mut new_selection = s.newest_anchor().clone();
9334 new_selection.collapse_to(jump_to, SelectionGoal::None);
9335 s.select_anchors(vec![new_selection.clone()]);
9336 });
9337 }
9338 return;
9339 }
9340 }
9341
9342 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9343 active_diagnostics
9344 .primary_range
9345 .to_offset(&buffer)
9346 .to_inclusive()
9347 });
9348 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9349 if active_primary_range.contains(&selection.head()) {
9350 *active_primary_range.start()
9351 } else {
9352 selection.head()
9353 }
9354 } else {
9355 selection.head()
9356 };
9357 let snapshot = self.snapshot(cx);
9358 loop {
9359 let diagnostics = if direction == Direction::Prev {
9360 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9361 } else {
9362 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9363 }
9364 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9365 let group = diagnostics
9366 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9367 // be sorted in a stable way
9368 // skip until we are at current active diagnostic, if it exists
9369 .skip_while(|entry| {
9370 (match direction {
9371 Direction::Prev => entry.range.start >= search_start,
9372 Direction::Next => entry.range.start <= search_start,
9373 }) && self
9374 .active_diagnostics
9375 .as_ref()
9376 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9377 })
9378 .find_map(|entry| {
9379 if entry.diagnostic.is_primary
9380 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9381 && !entry.range.is_empty()
9382 // if we match with the active diagnostic, skip it
9383 && Some(entry.diagnostic.group_id)
9384 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9385 {
9386 Some((entry.range, entry.diagnostic.group_id))
9387 } else {
9388 None
9389 }
9390 });
9391
9392 if let Some((primary_range, group_id)) = group {
9393 if self.activate_diagnostics(group_id, cx) {
9394 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9395 s.select(vec![Selection {
9396 id: selection.id,
9397 start: primary_range.start,
9398 end: primary_range.start,
9399 reversed: false,
9400 goal: SelectionGoal::None,
9401 }]);
9402 });
9403 }
9404 break;
9405 } else {
9406 // Cycle around to the start of the buffer, potentially moving back to the start of
9407 // the currently active diagnostic.
9408 active_primary_range.take();
9409 if direction == Direction::Prev {
9410 if search_start == buffer.len() {
9411 break;
9412 } else {
9413 search_start = buffer.len();
9414 }
9415 } else if search_start == 0 {
9416 break;
9417 } else {
9418 search_start = 0;
9419 }
9420 }
9421 }
9422 }
9423
9424 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9425 let snapshot = self
9426 .display_map
9427 .update(cx, |display_map, cx| display_map.snapshot(cx));
9428 let selection = self.selections.newest::<Point>(cx);
9429 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9430 }
9431
9432 fn go_to_hunk_after_position(
9433 &mut self,
9434 snapshot: &DisplaySnapshot,
9435 position: Point,
9436 cx: &mut ViewContext<'_, Editor>,
9437 ) -> Option<MultiBufferDiffHunk> {
9438 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9439 snapshot,
9440 position,
9441 false,
9442 snapshot
9443 .buffer_snapshot
9444 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9445 cx,
9446 ) {
9447 return Some(hunk);
9448 }
9449
9450 let wrapped_point = Point::zero();
9451 self.go_to_next_hunk_in_direction(
9452 snapshot,
9453 wrapped_point,
9454 true,
9455 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9456 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9457 ),
9458 cx,
9459 )
9460 }
9461
9462 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9463 let snapshot = self
9464 .display_map
9465 .update(cx, |display_map, cx| display_map.snapshot(cx));
9466 let selection = self.selections.newest::<Point>(cx);
9467
9468 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9469 }
9470
9471 fn go_to_hunk_before_position(
9472 &mut self,
9473 snapshot: &DisplaySnapshot,
9474 position: Point,
9475 cx: &mut ViewContext<'_, Editor>,
9476 ) -> Option<MultiBufferDiffHunk> {
9477 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9478 snapshot,
9479 position,
9480 false,
9481 snapshot
9482 .buffer_snapshot
9483 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9484 cx,
9485 ) {
9486 return Some(hunk);
9487 }
9488
9489 let wrapped_point = snapshot.buffer_snapshot.max_point();
9490 self.go_to_next_hunk_in_direction(
9491 snapshot,
9492 wrapped_point,
9493 true,
9494 snapshot
9495 .buffer_snapshot
9496 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9497 cx,
9498 )
9499 }
9500
9501 fn go_to_next_hunk_in_direction(
9502 &mut self,
9503 snapshot: &DisplaySnapshot,
9504 initial_point: Point,
9505 is_wrapped: bool,
9506 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9507 cx: &mut ViewContext<Editor>,
9508 ) -> Option<MultiBufferDiffHunk> {
9509 let display_point = initial_point.to_display_point(snapshot);
9510 let mut hunks = hunks
9511 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9512 .filter(|(display_hunk, _)| {
9513 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9514 })
9515 .dedup();
9516
9517 if let Some((display_hunk, hunk)) = hunks.next() {
9518 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9519 let row = display_hunk.start_display_row();
9520 let point = DisplayPoint::new(row, 0);
9521 s.select_display_ranges([point..point]);
9522 });
9523
9524 Some(hunk)
9525 } else {
9526 None
9527 }
9528 }
9529
9530 pub fn go_to_definition(
9531 &mut self,
9532 _: &GoToDefinition,
9533 cx: &mut ViewContext<Self>,
9534 ) -> Task<Result<Navigated>> {
9535 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9536 cx.spawn(|editor, mut cx| async move {
9537 if definition.await? == Navigated::Yes {
9538 return Ok(Navigated::Yes);
9539 }
9540 match editor.update(&mut cx, |editor, cx| {
9541 editor.find_all_references(&FindAllReferences, cx)
9542 })? {
9543 Some(references) => references.await,
9544 None => Ok(Navigated::No),
9545 }
9546 })
9547 }
9548
9549 pub fn go_to_declaration(
9550 &mut self,
9551 _: &GoToDeclaration,
9552 cx: &mut ViewContext<Self>,
9553 ) -> Task<Result<Navigated>> {
9554 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9555 }
9556
9557 pub fn go_to_declaration_split(
9558 &mut self,
9559 _: &GoToDeclaration,
9560 cx: &mut ViewContext<Self>,
9561 ) -> Task<Result<Navigated>> {
9562 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9563 }
9564
9565 pub fn go_to_implementation(
9566 &mut self,
9567 _: &GoToImplementation,
9568 cx: &mut ViewContext<Self>,
9569 ) -> Task<Result<Navigated>> {
9570 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9571 }
9572
9573 pub fn go_to_implementation_split(
9574 &mut self,
9575 _: &GoToImplementationSplit,
9576 cx: &mut ViewContext<Self>,
9577 ) -> Task<Result<Navigated>> {
9578 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9579 }
9580
9581 pub fn go_to_type_definition(
9582 &mut self,
9583 _: &GoToTypeDefinition,
9584 cx: &mut ViewContext<Self>,
9585 ) -> Task<Result<Navigated>> {
9586 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9587 }
9588
9589 pub fn go_to_definition_split(
9590 &mut self,
9591 _: &GoToDefinitionSplit,
9592 cx: &mut ViewContext<Self>,
9593 ) -> Task<Result<Navigated>> {
9594 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9595 }
9596
9597 pub fn go_to_type_definition_split(
9598 &mut self,
9599 _: &GoToTypeDefinitionSplit,
9600 cx: &mut ViewContext<Self>,
9601 ) -> Task<Result<Navigated>> {
9602 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9603 }
9604
9605 fn go_to_definition_of_kind(
9606 &mut self,
9607 kind: GotoDefinitionKind,
9608 split: bool,
9609 cx: &mut ViewContext<Self>,
9610 ) -> Task<Result<Navigated>> {
9611 let Some(workspace) = self.workspace() else {
9612 return Task::ready(Ok(Navigated::No));
9613 };
9614 let buffer = self.buffer.read(cx);
9615 let head = self.selections.newest::<usize>(cx).head();
9616 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9617 text_anchor
9618 } else {
9619 return Task::ready(Ok(Navigated::No));
9620 };
9621
9622 let project = workspace.read(cx).project().clone();
9623 let definitions = project.update(cx, |project, cx| match kind {
9624 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9625 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9626 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9627 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9628 });
9629
9630 cx.spawn(|editor, mut cx| async move {
9631 let definitions = definitions.await?;
9632 let navigated = editor
9633 .update(&mut cx, |editor, cx| {
9634 editor.navigate_to_hover_links(
9635 Some(kind),
9636 definitions
9637 .into_iter()
9638 .filter(|location| {
9639 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9640 })
9641 .map(HoverLink::Text)
9642 .collect::<Vec<_>>(),
9643 split,
9644 cx,
9645 )
9646 })?
9647 .await?;
9648 anyhow::Ok(navigated)
9649 })
9650 }
9651
9652 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9653 let position = self.selections.newest_anchor().head();
9654 let Some((buffer, buffer_position)) =
9655 self.buffer.read(cx).text_anchor_for_position(position, cx)
9656 else {
9657 return;
9658 };
9659
9660 cx.spawn(|editor, mut cx| async move {
9661 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9662 editor.update(&mut cx, |_, cx| {
9663 cx.open_url(&url);
9664 })
9665 } else {
9666 Ok(())
9667 }
9668 })
9669 .detach();
9670 }
9671
9672 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9673 let Some(workspace) = self.workspace() else {
9674 return;
9675 };
9676
9677 let position = self.selections.newest_anchor().head();
9678
9679 let Some((buffer, buffer_position)) =
9680 self.buffer.read(cx).text_anchor_for_position(position, cx)
9681 else {
9682 return;
9683 };
9684
9685 let Some(project) = self.project.clone() else {
9686 return;
9687 };
9688
9689 cx.spawn(|_, mut cx| async move {
9690 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9691
9692 if let Some((_, path)) = result {
9693 workspace
9694 .update(&mut cx, |workspace, cx| {
9695 workspace.open_resolved_path(path, cx)
9696 })?
9697 .await?;
9698 }
9699 anyhow::Ok(())
9700 })
9701 .detach();
9702 }
9703
9704 pub(crate) fn navigate_to_hover_links(
9705 &mut self,
9706 kind: Option<GotoDefinitionKind>,
9707 mut definitions: Vec<HoverLink>,
9708 split: bool,
9709 cx: &mut ViewContext<Editor>,
9710 ) -> Task<Result<Navigated>> {
9711 // If there is one definition, just open it directly
9712 if definitions.len() == 1 {
9713 let definition = definitions.pop().unwrap();
9714
9715 enum TargetTaskResult {
9716 Location(Option<Location>),
9717 AlreadyNavigated,
9718 }
9719
9720 let target_task = match definition {
9721 HoverLink::Text(link) => {
9722 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9723 }
9724 HoverLink::InlayHint(lsp_location, server_id) => {
9725 let computation = self.compute_target_location(lsp_location, server_id, cx);
9726 cx.background_executor().spawn(async move {
9727 let location = computation.await?;
9728 Ok(TargetTaskResult::Location(location))
9729 })
9730 }
9731 HoverLink::Url(url) => {
9732 cx.open_url(&url);
9733 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9734 }
9735 HoverLink::File(path) => {
9736 if let Some(workspace) = self.workspace() {
9737 cx.spawn(|_, mut cx| async move {
9738 workspace
9739 .update(&mut cx, |workspace, cx| {
9740 workspace.open_resolved_path(path, cx)
9741 })?
9742 .await
9743 .map(|_| TargetTaskResult::AlreadyNavigated)
9744 })
9745 } else {
9746 Task::ready(Ok(TargetTaskResult::Location(None)))
9747 }
9748 }
9749 };
9750 cx.spawn(|editor, mut cx| async move {
9751 let target = match target_task.await.context("target resolution task")? {
9752 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9753 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9754 TargetTaskResult::Location(Some(target)) => target,
9755 };
9756
9757 editor.update(&mut cx, |editor, cx| {
9758 let Some(workspace) = editor.workspace() else {
9759 return Navigated::No;
9760 };
9761 let pane = workspace.read(cx).active_pane().clone();
9762
9763 let range = target.range.to_offset(target.buffer.read(cx));
9764 let range = editor.range_for_match(&range);
9765
9766 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9767 let buffer = target.buffer.read(cx);
9768 let range = check_multiline_range(buffer, range);
9769 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9770 s.select_ranges([range]);
9771 });
9772 } else {
9773 cx.window_context().defer(move |cx| {
9774 let target_editor: View<Self> =
9775 workspace.update(cx, |workspace, cx| {
9776 let pane = if split {
9777 workspace.adjacent_pane(cx)
9778 } else {
9779 workspace.active_pane().clone()
9780 };
9781
9782 workspace.open_project_item(
9783 pane,
9784 target.buffer.clone(),
9785 true,
9786 true,
9787 cx,
9788 )
9789 });
9790 target_editor.update(cx, |target_editor, cx| {
9791 // When selecting a definition in a different buffer, disable the nav history
9792 // to avoid creating a history entry at the previous cursor location.
9793 pane.update(cx, |pane, _| pane.disable_history());
9794 let buffer = target.buffer.read(cx);
9795 let range = check_multiline_range(buffer, range);
9796 target_editor.change_selections(
9797 Some(Autoscroll::focused()),
9798 cx,
9799 |s| {
9800 s.select_ranges([range]);
9801 },
9802 );
9803 pane.update(cx, |pane, _| pane.enable_history());
9804 });
9805 });
9806 }
9807 Navigated::Yes
9808 })
9809 })
9810 } else if !definitions.is_empty() {
9811 cx.spawn(|editor, mut cx| async move {
9812 let (title, location_tasks, workspace) = editor
9813 .update(&mut cx, |editor, cx| {
9814 let tab_kind = match kind {
9815 Some(GotoDefinitionKind::Implementation) => "Implementations",
9816 _ => "Definitions",
9817 };
9818 let title = definitions
9819 .iter()
9820 .find_map(|definition| match definition {
9821 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9822 let buffer = origin.buffer.read(cx);
9823 format!(
9824 "{} for {}",
9825 tab_kind,
9826 buffer
9827 .text_for_range(origin.range.clone())
9828 .collect::<String>()
9829 )
9830 }),
9831 HoverLink::InlayHint(_, _) => None,
9832 HoverLink::Url(_) => None,
9833 HoverLink::File(_) => None,
9834 })
9835 .unwrap_or(tab_kind.to_string());
9836 let location_tasks = definitions
9837 .into_iter()
9838 .map(|definition| match definition {
9839 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9840 HoverLink::InlayHint(lsp_location, server_id) => {
9841 editor.compute_target_location(lsp_location, server_id, cx)
9842 }
9843 HoverLink::Url(_) => Task::ready(Ok(None)),
9844 HoverLink::File(_) => Task::ready(Ok(None)),
9845 })
9846 .collect::<Vec<_>>();
9847 (title, location_tasks, editor.workspace().clone())
9848 })
9849 .context("location tasks preparation")?;
9850
9851 let locations = future::join_all(location_tasks)
9852 .await
9853 .into_iter()
9854 .filter_map(|location| location.transpose())
9855 .collect::<Result<_>>()
9856 .context("location tasks")?;
9857
9858 let Some(workspace) = workspace else {
9859 return Ok(Navigated::No);
9860 };
9861 let opened = workspace
9862 .update(&mut cx, |workspace, cx| {
9863 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9864 })
9865 .ok();
9866
9867 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9868 })
9869 } else {
9870 Task::ready(Ok(Navigated::No))
9871 }
9872 }
9873
9874 fn compute_target_location(
9875 &self,
9876 lsp_location: lsp::Location,
9877 server_id: LanguageServerId,
9878 cx: &mut ViewContext<Editor>,
9879 ) -> Task<anyhow::Result<Option<Location>>> {
9880 let Some(project) = self.project.clone() else {
9881 return Task::Ready(Some(Ok(None)));
9882 };
9883
9884 cx.spawn(move |editor, mut cx| async move {
9885 let location_task = editor.update(&mut cx, |editor, cx| {
9886 project.update(cx, |project, cx| {
9887 let language_server_name =
9888 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9889 project
9890 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9891 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9892 });
9893 language_server_name.map(|language_server_name| {
9894 project.open_local_buffer_via_lsp(
9895 lsp_location.uri.clone(),
9896 server_id,
9897 language_server_name,
9898 cx,
9899 )
9900 })
9901 })
9902 })?;
9903 let location = match location_task {
9904 Some(task) => Some({
9905 let target_buffer_handle = task.await.context("open local buffer")?;
9906 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9907 let target_start = target_buffer
9908 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9909 let target_end = target_buffer
9910 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9911 target_buffer.anchor_after(target_start)
9912 ..target_buffer.anchor_before(target_end)
9913 })?;
9914 Location {
9915 buffer: target_buffer_handle,
9916 range,
9917 }
9918 }),
9919 None => None,
9920 };
9921 Ok(location)
9922 })
9923 }
9924
9925 pub fn find_all_references(
9926 &mut self,
9927 _: &FindAllReferences,
9928 cx: &mut ViewContext<Self>,
9929 ) -> Option<Task<Result<Navigated>>> {
9930 let multi_buffer = self.buffer.read(cx);
9931 let selection = self.selections.newest::<usize>(cx);
9932 let head = selection.head();
9933
9934 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9935 let head_anchor = multi_buffer_snapshot.anchor_at(
9936 head,
9937 if head < selection.tail() {
9938 Bias::Right
9939 } else {
9940 Bias::Left
9941 },
9942 );
9943
9944 match self
9945 .find_all_references_task_sources
9946 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9947 {
9948 Ok(_) => {
9949 log::info!(
9950 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9951 );
9952 return None;
9953 }
9954 Err(i) => {
9955 self.find_all_references_task_sources.insert(i, head_anchor);
9956 }
9957 }
9958
9959 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9960 let workspace = self.workspace()?;
9961 let project = workspace.read(cx).project().clone();
9962 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9963 Some(cx.spawn(|editor, mut cx| async move {
9964 let _cleanup = defer({
9965 let mut cx = cx.clone();
9966 move || {
9967 let _ = editor.update(&mut cx, |editor, _| {
9968 if let Ok(i) =
9969 editor
9970 .find_all_references_task_sources
9971 .binary_search_by(|anchor| {
9972 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9973 })
9974 {
9975 editor.find_all_references_task_sources.remove(i);
9976 }
9977 });
9978 }
9979 });
9980
9981 let locations = references.await?;
9982 if locations.is_empty() {
9983 return anyhow::Ok(Navigated::No);
9984 }
9985
9986 workspace.update(&mut cx, |workspace, cx| {
9987 let title = locations
9988 .first()
9989 .as_ref()
9990 .map(|location| {
9991 let buffer = location.buffer.read(cx);
9992 format!(
9993 "References to `{}`",
9994 buffer
9995 .text_for_range(location.range.clone())
9996 .collect::<String>()
9997 )
9998 })
9999 .unwrap();
10000 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
10001 Navigated::Yes
10002 })
10003 }))
10004 }
10005
10006 /// Opens a multibuffer with the given project locations in it
10007 pub fn open_locations_in_multibuffer(
10008 workspace: &mut Workspace,
10009 mut locations: Vec<Location>,
10010 title: String,
10011 split: bool,
10012 cx: &mut ViewContext<Workspace>,
10013 ) {
10014 // If there are multiple definitions, open them in a multibuffer
10015 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
10016 let mut locations = locations.into_iter().peekable();
10017 let mut ranges_to_highlight = Vec::new();
10018 let capability = workspace.project().read(cx).capability();
10019
10020 let excerpt_buffer = cx.new_model(|cx| {
10021 let mut multibuffer = MultiBuffer::new(capability);
10022 while let Some(location) = locations.next() {
10023 let buffer = location.buffer.read(cx);
10024 let mut ranges_for_buffer = Vec::new();
10025 let range = location.range.to_offset(buffer);
10026 ranges_for_buffer.push(range.clone());
10027
10028 while let Some(next_location) = locations.peek() {
10029 if next_location.buffer == location.buffer {
10030 ranges_for_buffer.push(next_location.range.to_offset(buffer));
10031 locations.next();
10032 } else {
10033 break;
10034 }
10035 }
10036
10037 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
10038 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
10039 location.buffer.clone(),
10040 ranges_for_buffer,
10041 DEFAULT_MULTIBUFFER_CONTEXT,
10042 cx,
10043 ))
10044 }
10045
10046 multibuffer.with_title(title)
10047 });
10048
10049 let editor = cx.new_view(|cx| {
10050 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10051 });
10052 editor.update(cx, |editor, cx| {
10053 if let Some(first_range) = ranges_to_highlight.first() {
10054 editor.change_selections(None, cx, |selections| {
10055 selections.clear_disjoint();
10056 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10057 });
10058 }
10059 editor.highlight_background::<Self>(
10060 &ranges_to_highlight,
10061 |theme| theme.editor_highlighted_line_background,
10062 cx,
10063 );
10064 });
10065
10066 let item = Box::new(editor);
10067 let item_id = item.item_id();
10068
10069 if split {
10070 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10071 } else {
10072 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10073 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10074 pane.close_current_preview_item(cx)
10075 } else {
10076 None
10077 }
10078 });
10079 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10080 }
10081 workspace.active_pane().update(cx, |pane, cx| {
10082 pane.set_preview_item_id(Some(item_id), cx);
10083 });
10084 }
10085
10086 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10087 use language::ToOffset as _;
10088
10089 let project = self.project.clone()?;
10090 let selection = self.selections.newest_anchor().clone();
10091 let (cursor_buffer, cursor_buffer_position) = self
10092 .buffer
10093 .read(cx)
10094 .text_anchor_for_position(selection.head(), cx)?;
10095 let (tail_buffer, cursor_buffer_position_end) = self
10096 .buffer
10097 .read(cx)
10098 .text_anchor_for_position(selection.tail(), cx)?;
10099 if tail_buffer != cursor_buffer {
10100 return None;
10101 }
10102
10103 let snapshot = cursor_buffer.read(cx).snapshot();
10104 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10105 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10106 let prepare_rename = project.update(cx, |project, cx| {
10107 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
10108 });
10109 drop(snapshot);
10110
10111 Some(cx.spawn(|this, mut cx| async move {
10112 let rename_range = if let Some(range) = prepare_rename.await? {
10113 Some(range)
10114 } else {
10115 this.update(&mut cx, |this, cx| {
10116 let buffer = this.buffer.read(cx).snapshot(cx);
10117 let mut buffer_highlights = this
10118 .document_highlights_for_position(selection.head(), &buffer)
10119 .filter(|highlight| {
10120 highlight.start.excerpt_id == selection.head().excerpt_id
10121 && highlight.end.excerpt_id == selection.head().excerpt_id
10122 });
10123 buffer_highlights
10124 .next()
10125 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10126 })?
10127 };
10128 if let Some(rename_range) = rename_range {
10129 this.update(&mut cx, |this, cx| {
10130 let snapshot = cursor_buffer.read(cx).snapshot();
10131 let rename_buffer_range = rename_range.to_offset(&snapshot);
10132 let cursor_offset_in_rename_range =
10133 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10134 let cursor_offset_in_rename_range_end =
10135 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10136
10137 this.take_rename(false, cx);
10138 let buffer = this.buffer.read(cx).read(cx);
10139 let cursor_offset = selection.head().to_offset(&buffer);
10140 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10141 let rename_end = rename_start + rename_buffer_range.len();
10142 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10143 let mut old_highlight_id = None;
10144 let old_name: Arc<str> = buffer
10145 .chunks(rename_start..rename_end, true)
10146 .map(|chunk| {
10147 if old_highlight_id.is_none() {
10148 old_highlight_id = chunk.syntax_highlight_id;
10149 }
10150 chunk.text
10151 })
10152 .collect::<String>()
10153 .into();
10154
10155 drop(buffer);
10156
10157 // Position the selection in the rename editor so that it matches the current selection.
10158 this.show_local_selections = false;
10159 let rename_editor = cx.new_view(|cx| {
10160 let mut editor = Editor::single_line(cx);
10161 editor.buffer.update(cx, |buffer, cx| {
10162 buffer.edit([(0..0, old_name.clone())], None, cx)
10163 });
10164 let rename_selection_range = match cursor_offset_in_rename_range
10165 .cmp(&cursor_offset_in_rename_range_end)
10166 {
10167 Ordering::Equal => {
10168 editor.select_all(&SelectAll, cx);
10169 return editor;
10170 }
10171 Ordering::Less => {
10172 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10173 }
10174 Ordering::Greater => {
10175 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10176 }
10177 };
10178 if rename_selection_range.end > old_name.len() {
10179 editor.select_all(&SelectAll, cx);
10180 } else {
10181 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10182 s.select_ranges([rename_selection_range]);
10183 });
10184 }
10185 editor
10186 });
10187 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10188 if e == &EditorEvent::Focused {
10189 cx.emit(EditorEvent::FocusedIn)
10190 }
10191 })
10192 .detach();
10193
10194 let write_highlights =
10195 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10196 let read_highlights =
10197 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10198 let ranges = write_highlights
10199 .iter()
10200 .flat_map(|(_, ranges)| ranges.iter())
10201 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10202 .cloned()
10203 .collect();
10204
10205 this.highlight_text::<Rename>(
10206 ranges,
10207 HighlightStyle {
10208 fade_out: Some(0.6),
10209 ..Default::default()
10210 },
10211 cx,
10212 );
10213 let rename_focus_handle = rename_editor.focus_handle(cx);
10214 cx.focus(&rename_focus_handle);
10215 let block_id = this.insert_blocks(
10216 [BlockProperties {
10217 style: BlockStyle::Flex,
10218 position: range.start,
10219 height: 1,
10220 render: Box::new({
10221 let rename_editor = rename_editor.clone();
10222 move |cx: &mut BlockContext| {
10223 let mut text_style = cx.editor_style.text.clone();
10224 if let Some(highlight_style) = old_highlight_id
10225 .and_then(|h| h.style(&cx.editor_style.syntax))
10226 {
10227 text_style = text_style.highlight(highlight_style);
10228 }
10229 div()
10230 .pl(cx.anchor_x)
10231 .child(EditorElement::new(
10232 &rename_editor,
10233 EditorStyle {
10234 background: cx.theme().system().transparent,
10235 local_player: cx.editor_style.local_player,
10236 text: text_style,
10237 scrollbar_width: cx.editor_style.scrollbar_width,
10238 syntax: cx.editor_style.syntax.clone(),
10239 status: cx.editor_style.status.clone(),
10240 inlay_hints_style: HighlightStyle {
10241 font_weight: Some(FontWeight::BOLD),
10242 ..make_inlay_hints_style(cx)
10243 },
10244 suggestions_style: HighlightStyle {
10245 color: Some(cx.theme().status().predictive),
10246 ..HighlightStyle::default()
10247 },
10248 ..EditorStyle::default()
10249 },
10250 ))
10251 .into_any_element()
10252 }
10253 }),
10254 disposition: BlockDisposition::Below,
10255 priority: 0,
10256 }],
10257 Some(Autoscroll::fit()),
10258 cx,
10259 )[0];
10260 this.pending_rename = Some(RenameState {
10261 range,
10262 old_name,
10263 editor: rename_editor,
10264 block_id,
10265 });
10266 })?;
10267 }
10268
10269 Ok(())
10270 }))
10271 }
10272
10273 pub fn confirm_rename(
10274 &mut self,
10275 _: &ConfirmRename,
10276 cx: &mut ViewContext<Self>,
10277 ) -> Option<Task<Result<()>>> {
10278 let rename = self.take_rename(false, cx)?;
10279 let workspace = self.workspace()?;
10280 let (start_buffer, start) = self
10281 .buffer
10282 .read(cx)
10283 .text_anchor_for_position(rename.range.start, cx)?;
10284 let (end_buffer, end) = self
10285 .buffer
10286 .read(cx)
10287 .text_anchor_for_position(rename.range.end, cx)?;
10288 if start_buffer != end_buffer {
10289 return None;
10290 }
10291
10292 let buffer = start_buffer;
10293 let range = start..end;
10294 let old_name = rename.old_name;
10295 let new_name = rename.editor.read(cx).text(cx);
10296
10297 let rename = workspace
10298 .read(cx)
10299 .project()
10300 .clone()
10301 .update(cx, |project, cx| {
10302 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10303 });
10304 let workspace = workspace.downgrade();
10305
10306 Some(cx.spawn(|editor, mut cx| async move {
10307 let project_transaction = rename.await?;
10308 Self::open_project_transaction(
10309 &editor,
10310 workspace,
10311 project_transaction,
10312 format!("Rename: {} → {}", old_name, new_name),
10313 cx.clone(),
10314 )
10315 .await?;
10316
10317 editor.update(&mut cx, |editor, cx| {
10318 editor.refresh_document_highlights(cx);
10319 })?;
10320 Ok(())
10321 }))
10322 }
10323
10324 fn take_rename(
10325 &mut self,
10326 moving_cursor: bool,
10327 cx: &mut ViewContext<Self>,
10328 ) -> Option<RenameState> {
10329 let rename = self.pending_rename.take()?;
10330 if rename.editor.focus_handle(cx).is_focused(cx) {
10331 cx.focus(&self.focus_handle);
10332 }
10333
10334 self.remove_blocks(
10335 [rename.block_id].into_iter().collect(),
10336 Some(Autoscroll::fit()),
10337 cx,
10338 );
10339 self.clear_highlights::<Rename>(cx);
10340 self.show_local_selections = true;
10341
10342 if moving_cursor {
10343 let rename_editor = rename.editor.read(cx);
10344 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10345
10346 // Update the selection to match the position of the selection inside
10347 // the rename editor.
10348 let snapshot = self.buffer.read(cx).read(cx);
10349 let rename_range = rename.range.to_offset(&snapshot);
10350 let cursor_in_editor = snapshot
10351 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10352 .min(rename_range.end);
10353 drop(snapshot);
10354
10355 self.change_selections(None, cx, |s| {
10356 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10357 });
10358 } else {
10359 self.refresh_document_highlights(cx);
10360 }
10361
10362 Some(rename)
10363 }
10364
10365 pub fn pending_rename(&self) -> Option<&RenameState> {
10366 self.pending_rename.as_ref()
10367 }
10368
10369 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10370 let project = match &self.project {
10371 Some(project) => project.clone(),
10372 None => return None,
10373 };
10374
10375 Some(self.perform_format(project, FormatTrigger::Manual, cx))
10376 }
10377
10378 fn perform_format(
10379 &mut self,
10380 project: Model<Project>,
10381 trigger: FormatTrigger,
10382 cx: &mut ViewContext<Self>,
10383 ) -> Task<Result<()>> {
10384 let buffer = self.buffer().clone();
10385 let mut buffers = buffer.read(cx).all_buffers();
10386 if trigger == FormatTrigger::Save {
10387 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10388 }
10389
10390 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10391 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10392
10393 cx.spawn(|_, mut cx| async move {
10394 let transaction = futures::select_biased! {
10395 () = timeout => {
10396 log::warn!("timed out waiting for formatting");
10397 None
10398 }
10399 transaction = format.log_err().fuse() => transaction,
10400 };
10401
10402 buffer
10403 .update(&mut cx, |buffer, cx| {
10404 if let Some(transaction) = transaction {
10405 if !buffer.is_singleton() {
10406 buffer.push_transaction(&transaction.0, cx);
10407 }
10408 }
10409
10410 cx.notify();
10411 })
10412 .ok();
10413
10414 Ok(())
10415 })
10416 }
10417
10418 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10419 if let Some(project) = self.project.clone() {
10420 self.buffer.update(cx, |multi_buffer, cx| {
10421 project.update(cx, |project, cx| {
10422 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10423 });
10424 })
10425 }
10426 }
10427
10428 fn cancel_language_server_work(
10429 &mut self,
10430 _: &CancelLanguageServerWork,
10431 cx: &mut ViewContext<Self>,
10432 ) {
10433 if let Some(project) = self.project.clone() {
10434 self.buffer.update(cx, |multi_buffer, cx| {
10435 project.update(cx, |project, cx| {
10436 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10437 });
10438 })
10439 }
10440 }
10441
10442 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10443 cx.show_character_palette();
10444 }
10445
10446 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10447 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10448 let buffer = self.buffer.read(cx).snapshot(cx);
10449 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10450 let is_valid = buffer
10451 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10452 .any(|entry| {
10453 entry.diagnostic.is_primary
10454 && !entry.range.is_empty()
10455 && entry.range.start == primary_range_start
10456 && entry.diagnostic.message == active_diagnostics.primary_message
10457 });
10458
10459 if is_valid != active_diagnostics.is_valid {
10460 active_diagnostics.is_valid = is_valid;
10461 let mut new_styles = HashMap::default();
10462 for (block_id, diagnostic) in &active_diagnostics.blocks {
10463 new_styles.insert(
10464 *block_id,
10465 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10466 );
10467 }
10468 self.display_map.update(cx, |display_map, _cx| {
10469 display_map.replace_blocks(new_styles)
10470 });
10471 }
10472 }
10473 }
10474
10475 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10476 self.dismiss_diagnostics(cx);
10477 let snapshot = self.snapshot(cx);
10478 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10479 let buffer = self.buffer.read(cx).snapshot(cx);
10480
10481 let mut primary_range = None;
10482 let mut primary_message = None;
10483 let mut group_end = Point::zero();
10484 let diagnostic_group = buffer
10485 .diagnostic_group::<MultiBufferPoint>(group_id)
10486 .filter_map(|entry| {
10487 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10488 && (entry.range.start.row == entry.range.end.row
10489 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10490 {
10491 return None;
10492 }
10493 if entry.range.end > group_end {
10494 group_end = entry.range.end;
10495 }
10496 if entry.diagnostic.is_primary {
10497 primary_range = Some(entry.range.clone());
10498 primary_message = Some(entry.diagnostic.message.clone());
10499 }
10500 Some(entry)
10501 })
10502 .collect::<Vec<_>>();
10503 let primary_range = primary_range?;
10504 let primary_message = primary_message?;
10505 let primary_range =
10506 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10507
10508 let blocks = display_map
10509 .insert_blocks(
10510 diagnostic_group.iter().map(|entry| {
10511 let diagnostic = entry.diagnostic.clone();
10512 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10513 BlockProperties {
10514 style: BlockStyle::Fixed,
10515 position: buffer.anchor_after(entry.range.start),
10516 height: message_height,
10517 render: diagnostic_block_renderer(diagnostic, None, true, true),
10518 disposition: BlockDisposition::Below,
10519 priority: 0,
10520 }
10521 }),
10522 cx,
10523 )
10524 .into_iter()
10525 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10526 .collect();
10527
10528 Some(ActiveDiagnosticGroup {
10529 primary_range,
10530 primary_message,
10531 group_id,
10532 blocks,
10533 is_valid: true,
10534 })
10535 });
10536 self.active_diagnostics.is_some()
10537 }
10538
10539 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10540 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10541 self.display_map.update(cx, |display_map, cx| {
10542 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10543 });
10544 cx.notify();
10545 }
10546 }
10547
10548 pub fn set_selections_from_remote(
10549 &mut self,
10550 selections: Vec<Selection<Anchor>>,
10551 pending_selection: Option<Selection<Anchor>>,
10552 cx: &mut ViewContext<Self>,
10553 ) {
10554 let old_cursor_position = self.selections.newest_anchor().head();
10555 self.selections.change_with(cx, |s| {
10556 s.select_anchors(selections);
10557 if let Some(pending_selection) = pending_selection {
10558 s.set_pending(pending_selection, SelectMode::Character);
10559 } else {
10560 s.clear_pending();
10561 }
10562 });
10563 self.selections_did_change(false, &old_cursor_position, true, cx);
10564 }
10565
10566 fn push_to_selection_history(&mut self) {
10567 self.selection_history.push(SelectionHistoryEntry {
10568 selections: self.selections.disjoint_anchors(),
10569 select_next_state: self.select_next_state.clone(),
10570 select_prev_state: self.select_prev_state.clone(),
10571 add_selections_state: self.add_selections_state.clone(),
10572 });
10573 }
10574
10575 pub fn transact(
10576 &mut self,
10577 cx: &mut ViewContext<Self>,
10578 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10579 ) -> Option<TransactionId> {
10580 self.start_transaction_at(Instant::now(), cx);
10581 update(self, cx);
10582 self.end_transaction_at(Instant::now(), cx)
10583 }
10584
10585 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10586 self.end_selection(cx);
10587 if let Some(tx_id) = self
10588 .buffer
10589 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10590 {
10591 self.selection_history
10592 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10593 cx.emit(EditorEvent::TransactionBegun {
10594 transaction_id: tx_id,
10595 })
10596 }
10597 }
10598
10599 fn end_transaction_at(
10600 &mut self,
10601 now: Instant,
10602 cx: &mut ViewContext<Self>,
10603 ) -> Option<TransactionId> {
10604 if let Some(transaction_id) = self
10605 .buffer
10606 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10607 {
10608 if let Some((_, end_selections)) =
10609 self.selection_history.transaction_mut(transaction_id)
10610 {
10611 *end_selections = Some(self.selections.disjoint_anchors());
10612 } else {
10613 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10614 }
10615
10616 cx.emit(EditorEvent::Edited { transaction_id });
10617 Some(transaction_id)
10618 } else {
10619 None
10620 }
10621 }
10622
10623 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10624 let selection = self.selections.newest::<Point>(cx);
10625
10626 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10627 let range = if selection.is_empty() {
10628 let point = selection.head().to_display_point(&display_map);
10629 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10630 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10631 .to_point(&display_map);
10632 start..end
10633 } else {
10634 selection.range()
10635 };
10636 if display_map.folds_in_range(range).next().is_some() {
10637 self.unfold_lines(&Default::default(), cx)
10638 } else {
10639 self.fold(&Default::default(), cx)
10640 }
10641 }
10642
10643 pub fn toggle_fold_recursive(
10644 &mut self,
10645 _: &actions::ToggleFoldRecursive,
10646 cx: &mut ViewContext<Self>,
10647 ) {
10648 let selection = self.selections.newest::<Point>(cx);
10649
10650 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10651 let range = if selection.is_empty() {
10652 let point = selection.head().to_display_point(&display_map);
10653 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10654 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10655 .to_point(&display_map);
10656 start..end
10657 } else {
10658 selection.range()
10659 };
10660 if display_map.folds_in_range(range).next().is_some() {
10661 self.unfold_recursive(&Default::default(), cx)
10662 } else {
10663 self.fold_recursive(&Default::default(), cx)
10664 }
10665 }
10666
10667 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10668 let mut fold_ranges = Vec::new();
10669 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10670 let selections = self.selections.all_adjusted(cx);
10671
10672 for selection in selections {
10673 let range = selection.range().sorted();
10674 let buffer_start_row = range.start.row;
10675
10676 if range.start.row != range.end.row {
10677 let mut found = false;
10678 let mut row = range.start.row;
10679 while row <= range.end.row {
10680 if let Some((foldable_range, fold_text)) =
10681 { display_map.foldable_range(MultiBufferRow(row)) }
10682 {
10683 found = true;
10684 row = foldable_range.end.row + 1;
10685 fold_ranges.push((foldable_range, fold_text));
10686 } else {
10687 row += 1
10688 }
10689 }
10690 if found {
10691 continue;
10692 }
10693 }
10694
10695 for row in (0..=range.start.row).rev() {
10696 if let Some((foldable_range, fold_text)) =
10697 display_map.foldable_range(MultiBufferRow(row))
10698 {
10699 if foldable_range.end.row >= buffer_start_row {
10700 fold_ranges.push((foldable_range, fold_text));
10701 if row <= range.start.row {
10702 break;
10703 }
10704 }
10705 }
10706 }
10707 }
10708
10709 self.fold_ranges(fold_ranges, true, cx);
10710 }
10711
10712 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10713 let mut fold_ranges = Vec::new();
10714 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10715
10716 for row in 0..display_map.max_buffer_row().0 {
10717 if let Some((foldable_range, fold_text)) =
10718 display_map.foldable_range(MultiBufferRow(row))
10719 {
10720 fold_ranges.push((foldable_range, fold_text));
10721 }
10722 }
10723
10724 self.fold_ranges(fold_ranges, true, cx);
10725 }
10726
10727 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, 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 let selections = self.selections.all_adjusted(cx);
10731
10732 for selection in selections {
10733 let range = selection.range().sorted();
10734 let buffer_start_row = range.start.row;
10735
10736 if range.start.row != range.end.row {
10737 let mut found = false;
10738 for row in range.start.row..=range.end.row {
10739 if let Some((foldable_range, fold_text)) =
10740 { display_map.foldable_range(MultiBufferRow(row)) }
10741 {
10742 found = true;
10743 fold_ranges.push((foldable_range, fold_text));
10744 }
10745 }
10746 if found {
10747 continue;
10748 }
10749 }
10750
10751 for row in (0..=range.start.row).rev() {
10752 if let Some((foldable_range, fold_text)) =
10753 display_map.foldable_range(MultiBufferRow(row))
10754 {
10755 if foldable_range.end.row >= buffer_start_row {
10756 fold_ranges.push((foldable_range, fold_text));
10757 } else {
10758 break;
10759 }
10760 }
10761 }
10762 }
10763
10764 self.fold_ranges(fold_ranges, true, cx);
10765 }
10766
10767 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10768 let buffer_row = fold_at.buffer_row;
10769 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10770
10771 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10772 let autoscroll = self
10773 .selections
10774 .all::<Point>(cx)
10775 .iter()
10776 .any(|selection| fold_range.overlaps(&selection.range()));
10777
10778 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10779 }
10780 }
10781
10782 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10783 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10784 let buffer = &display_map.buffer_snapshot;
10785 let selections = self.selections.all::<Point>(cx);
10786 let ranges = selections
10787 .iter()
10788 .map(|s| {
10789 let range = s.display_range(&display_map).sorted();
10790 let mut start = range.start.to_point(&display_map);
10791 let mut end = range.end.to_point(&display_map);
10792 start.column = 0;
10793 end.column = buffer.line_len(MultiBufferRow(end.row));
10794 start..end
10795 })
10796 .collect::<Vec<_>>();
10797
10798 self.unfold_ranges(ranges, true, true, cx);
10799 }
10800
10801 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10802 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10803 let selections = self.selections.all::<Point>(cx);
10804 let ranges = selections
10805 .iter()
10806 .map(|s| {
10807 let mut range = s.display_range(&display_map).sorted();
10808 *range.start.column_mut() = 0;
10809 *range.end.column_mut() = display_map.line_len(range.end.row());
10810 let start = range.start.to_point(&display_map);
10811 let end = range.end.to_point(&display_map);
10812 start..end
10813 })
10814 .collect::<Vec<_>>();
10815
10816 self.unfold_ranges(ranges, true, true, cx);
10817 }
10818
10819 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10820 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10821
10822 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10823 ..Point::new(
10824 unfold_at.buffer_row.0,
10825 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10826 );
10827
10828 let autoscroll = self
10829 .selections
10830 .all::<Point>(cx)
10831 .iter()
10832 .any(|selection| RangeExt::overlaps(&selection.range(), &intersection_range));
10833
10834 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10835 }
10836
10837 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10838 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10839 self.unfold_ranges(
10840 [Point::zero()..display_map.max_point().to_point(&display_map)],
10841 true,
10842 true,
10843 cx,
10844 );
10845 }
10846
10847 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10848 let selections = self.selections.all::<Point>(cx);
10849 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10850 let line_mode = self.selections.line_mode;
10851 let ranges = selections.into_iter().map(|s| {
10852 if line_mode {
10853 let start = Point::new(s.start.row, 0);
10854 let end = Point::new(
10855 s.end.row,
10856 display_map
10857 .buffer_snapshot
10858 .line_len(MultiBufferRow(s.end.row)),
10859 );
10860 (start..end, display_map.fold_placeholder.clone())
10861 } else {
10862 (s.start..s.end, display_map.fold_placeholder.clone())
10863 }
10864 });
10865 self.fold_ranges(ranges, true, cx);
10866 }
10867
10868 pub fn fold_ranges<T: ToOffset + Clone>(
10869 &mut self,
10870 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10871 auto_scroll: bool,
10872 cx: &mut ViewContext<Self>,
10873 ) {
10874 let mut fold_ranges = Vec::new();
10875 let mut buffers_affected = HashMap::default();
10876 let multi_buffer = self.buffer().read(cx);
10877 for (fold_range, fold_text) in ranges {
10878 if let Some((_, buffer, _)) =
10879 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10880 {
10881 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10882 };
10883 fold_ranges.push((fold_range, fold_text));
10884 }
10885
10886 let mut ranges = fold_ranges.into_iter().peekable();
10887 if ranges.peek().is_some() {
10888 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10889
10890 if auto_scroll {
10891 self.request_autoscroll(Autoscroll::fit(), cx);
10892 }
10893
10894 for buffer in buffers_affected.into_values() {
10895 self.sync_expanded_diff_hunks(buffer, cx);
10896 }
10897
10898 cx.notify();
10899
10900 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10901 // Clear diagnostics block when folding a range that contains it.
10902 let snapshot = self.snapshot(cx);
10903 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10904 drop(snapshot);
10905 self.active_diagnostics = Some(active_diagnostics);
10906 self.dismiss_diagnostics(cx);
10907 } else {
10908 self.active_diagnostics = Some(active_diagnostics);
10909 }
10910 }
10911
10912 self.scrollbar_marker_state.dirty = true;
10913 }
10914 }
10915
10916 pub fn unfold_ranges<T: ToOffset + Clone>(
10917 &mut self,
10918 ranges: impl IntoIterator<Item = Range<T>>,
10919 inclusive: bool,
10920 auto_scroll: bool,
10921 cx: &mut ViewContext<Self>,
10922 ) {
10923 let mut unfold_ranges = Vec::new();
10924 let mut buffers_affected = HashMap::default();
10925 let multi_buffer = self.buffer().read(cx);
10926 for range in ranges {
10927 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10928 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10929 };
10930 unfold_ranges.push(range);
10931 }
10932
10933 let mut ranges = unfold_ranges.into_iter().peekable();
10934 if ranges.peek().is_some() {
10935 self.display_map
10936 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10937 if auto_scroll {
10938 self.request_autoscroll(Autoscroll::fit(), cx);
10939 }
10940
10941 for buffer in buffers_affected.into_values() {
10942 self.sync_expanded_diff_hunks(buffer, cx);
10943 }
10944
10945 cx.notify();
10946 self.scrollbar_marker_state.dirty = true;
10947 self.active_indent_guides_state.dirty = true;
10948 }
10949 }
10950
10951 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10952 self.display_map.read(cx).fold_placeholder.clone()
10953 }
10954
10955 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10956 if hovered != self.gutter_hovered {
10957 self.gutter_hovered = hovered;
10958 cx.notify();
10959 }
10960 }
10961
10962 pub fn insert_blocks(
10963 &mut self,
10964 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10965 autoscroll: Option<Autoscroll>,
10966 cx: &mut ViewContext<Self>,
10967 ) -> Vec<CustomBlockId> {
10968 let blocks = self
10969 .display_map
10970 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10971 if let Some(autoscroll) = autoscroll {
10972 self.request_autoscroll(autoscroll, cx);
10973 }
10974 cx.notify();
10975 blocks
10976 }
10977
10978 pub fn resize_blocks(
10979 &mut self,
10980 heights: HashMap<CustomBlockId, u32>,
10981 autoscroll: Option<Autoscroll>,
10982 cx: &mut ViewContext<Self>,
10983 ) {
10984 self.display_map
10985 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10986 if let Some(autoscroll) = autoscroll {
10987 self.request_autoscroll(autoscroll, cx);
10988 }
10989 cx.notify();
10990 }
10991
10992 pub fn replace_blocks(
10993 &mut self,
10994 renderers: HashMap<CustomBlockId, RenderBlock>,
10995 autoscroll: Option<Autoscroll>,
10996 cx: &mut ViewContext<Self>,
10997 ) {
10998 self.display_map
10999 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
11000 if let Some(autoscroll) = autoscroll {
11001 self.request_autoscroll(autoscroll, cx);
11002 }
11003 cx.notify();
11004 }
11005
11006 pub fn remove_blocks(
11007 &mut self,
11008 block_ids: HashSet<CustomBlockId>,
11009 autoscroll: Option<Autoscroll>,
11010 cx: &mut ViewContext<Self>,
11011 ) {
11012 self.display_map.update(cx, |display_map, cx| {
11013 display_map.remove_blocks(block_ids, cx)
11014 });
11015 if let Some(autoscroll) = autoscroll {
11016 self.request_autoscroll(autoscroll, cx);
11017 }
11018 cx.notify();
11019 }
11020
11021 pub fn row_for_block(
11022 &self,
11023 block_id: CustomBlockId,
11024 cx: &mut ViewContext<Self>,
11025 ) -> Option<DisplayRow> {
11026 self.display_map
11027 .update(cx, |map, cx| map.row_for_block(block_id, cx))
11028 }
11029
11030 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
11031 self.focused_block = Some(focused_block);
11032 }
11033
11034 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
11035 self.focused_block.take()
11036 }
11037
11038 pub fn insert_creases(
11039 &mut self,
11040 creases: impl IntoIterator<Item = Crease>,
11041 cx: &mut ViewContext<Self>,
11042 ) -> Vec<CreaseId> {
11043 self.display_map
11044 .update(cx, |map, cx| map.insert_creases(creases, cx))
11045 }
11046
11047 pub fn remove_creases(
11048 &mut self,
11049 ids: impl IntoIterator<Item = CreaseId>,
11050 cx: &mut ViewContext<Self>,
11051 ) {
11052 self.display_map
11053 .update(cx, |map, cx| map.remove_creases(ids, cx));
11054 }
11055
11056 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11057 self.display_map
11058 .update(cx, |map, cx| map.snapshot(cx))
11059 .longest_row()
11060 }
11061
11062 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11063 self.display_map
11064 .update(cx, |map, cx| map.snapshot(cx))
11065 .max_point()
11066 }
11067
11068 pub fn text(&self, cx: &AppContext) -> String {
11069 self.buffer.read(cx).read(cx).text()
11070 }
11071
11072 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11073 let text = self.text(cx);
11074 let text = text.trim();
11075
11076 if text.is_empty() {
11077 return None;
11078 }
11079
11080 Some(text.to_string())
11081 }
11082
11083 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11084 self.transact(cx, |this, cx| {
11085 this.buffer
11086 .read(cx)
11087 .as_singleton()
11088 .expect("you can only call set_text on editors for singleton buffers")
11089 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11090 });
11091 }
11092
11093 pub fn display_text(&self, cx: &mut AppContext) -> String {
11094 self.display_map
11095 .update(cx, |map, cx| map.snapshot(cx))
11096 .text()
11097 }
11098
11099 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11100 let mut wrap_guides = smallvec::smallvec![];
11101
11102 if self.show_wrap_guides == Some(false) {
11103 return wrap_guides;
11104 }
11105
11106 let settings = self.buffer.read(cx).settings_at(0, cx);
11107 if settings.show_wrap_guides {
11108 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11109 wrap_guides.push((soft_wrap as usize, true));
11110 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11111 wrap_guides.push((soft_wrap as usize, true));
11112 }
11113 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11114 }
11115
11116 wrap_guides
11117 }
11118
11119 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11120 let settings = self.buffer.read(cx).settings_at(0, cx);
11121 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11122 match mode {
11123 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11124 SoftWrap::None
11125 }
11126 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11127 language_settings::SoftWrap::PreferredLineLength => {
11128 SoftWrap::Column(settings.preferred_line_length)
11129 }
11130 language_settings::SoftWrap::Bounded => {
11131 SoftWrap::Bounded(settings.preferred_line_length)
11132 }
11133 }
11134 }
11135
11136 pub fn set_soft_wrap_mode(
11137 &mut self,
11138 mode: language_settings::SoftWrap,
11139 cx: &mut ViewContext<Self>,
11140 ) {
11141 self.soft_wrap_mode_override = Some(mode);
11142 cx.notify();
11143 }
11144
11145 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11146 let rem_size = cx.rem_size();
11147 self.display_map.update(cx, |map, cx| {
11148 map.set_font(
11149 style.text.font(),
11150 style.text.font_size.to_pixels(rem_size),
11151 cx,
11152 )
11153 });
11154 self.style = Some(style);
11155 }
11156
11157 pub fn style(&self) -> Option<&EditorStyle> {
11158 self.style.as_ref()
11159 }
11160
11161 // Called by the element. This method is not designed to be called outside of the editor
11162 // element's layout code because it does not notify when rewrapping is computed synchronously.
11163 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11164 self.display_map
11165 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11166 }
11167
11168 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11169 if self.soft_wrap_mode_override.is_some() {
11170 self.soft_wrap_mode_override.take();
11171 } else {
11172 let soft_wrap = match self.soft_wrap_mode(cx) {
11173 SoftWrap::GitDiff => return,
11174 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11175 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11176 language_settings::SoftWrap::None
11177 }
11178 };
11179 self.soft_wrap_mode_override = Some(soft_wrap);
11180 }
11181 cx.notify();
11182 }
11183
11184 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11185 let Some(workspace) = self.workspace() else {
11186 return;
11187 };
11188 let fs = workspace.read(cx).app_state().fs.clone();
11189 let current_show = TabBarSettings::get_global(cx).show;
11190 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11191 setting.show = Some(!current_show);
11192 });
11193 }
11194
11195 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11196 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11197 self.buffer
11198 .read(cx)
11199 .settings_at(0, cx)
11200 .indent_guides
11201 .enabled
11202 });
11203 self.show_indent_guides = Some(!currently_enabled);
11204 cx.notify();
11205 }
11206
11207 fn should_show_indent_guides(&self) -> Option<bool> {
11208 self.show_indent_guides
11209 }
11210
11211 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11212 let mut editor_settings = EditorSettings::get_global(cx).clone();
11213 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11214 EditorSettings::override_global(editor_settings, cx);
11215 }
11216
11217 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11218 self.use_relative_line_numbers
11219 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11220 }
11221
11222 pub fn toggle_relative_line_numbers(
11223 &mut self,
11224 _: &ToggleRelativeLineNumbers,
11225 cx: &mut ViewContext<Self>,
11226 ) {
11227 let is_relative = self.should_use_relative_line_numbers(cx);
11228 self.set_relative_line_number(Some(!is_relative), cx)
11229 }
11230
11231 pub fn set_relative_line_number(
11232 &mut self,
11233 is_relative: Option<bool>,
11234 cx: &mut ViewContext<Self>,
11235 ) {
11236 self.use_relative_line_numbers = is_relative;
11237 cx.notify();
11238 }
11239
11240 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11241 self.show_gutter = show_gutter;
11242 cx.notify();
11243 }
11244
11245 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11246 self.show_line_numbers = Some(show_line_numbers);
11247 cx.notify();
11248 }
11249
11250 pub fn set_show_git_diff_gutter(
11251 &mut self,
11252 show_git_diff_gutter: bool,
11253 cx: &mut ViewContext<Self>,
11254 ) {
11255 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11256 cx.notify();
11257 }
11258
11259 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11260 self.show_code_actions = Some(show_code_actions);
11261 cx.notify();
11262 }
11263
11264 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11265 self.show_runnables = Some(show_runnables);
11266 cx.notify();
11267 }
11268
11269 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11270 if self.display_map.read(cx).masked != masked {
11271 self.display_map.update(cx, |map, _| map.masked = masked);
11272 }
11273 cx.notify()
11274 }
11275
11276 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11277 self.show_wrap_guides = Some(show_wrap_guides);
11278 cx.notify();
11279 }
11280
11281 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11282 self.show_indent_guides = Some(show_indent_guides);
11283 cx.notify();
11284 }
11285
11286 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11287 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11288 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11289 if let Some(dir) = file.abs_path(cx).parent() {
11290 return Some(dir.to_owned());
11291 }
11292 }
11293
11294 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11295 return Some(project_path.path.to_path_buf());
11296 }
11297 }
11298
11299 None
11300 }
11301
11302 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11303 self.active_excerpt(cx)?
11304 .1
11305 .read(cx)
11306 .file()
11307 .and_then(|f| f.as_local())
11308 }
11309
11310 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11311 if let Some(target) = self.target_file(cx) {
11312 cx.reveal_path(&target.abs_path(cx));
11313 }
11314 }
11315
11316 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11317 if let Some(file) = self.target_file(cx) {
11318 if let Some(path) = file.abs_path(cx).to_str() {
11319 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11320 }
11321 }
11322 }
11323
11324 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11325 if let Some(file) = self.target_file(cx) {
11326 if let Some(path) = file.path().to_str() {
11327 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11328 }
11329 }
11330 }
11331
11332 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11333 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11334
11335 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11336 self.start_git_blame(true, cx);
11337 }
11338
11339 cx.notify();
11340 }
11341
11342 pub fn toggle_git_blame_inline(
11343 &mut self,
11344 _: &ToggleGitBlameInline,
11345 cx: &mut ViewContext<Self>,
11346 ) {
11347 self.toggle_git_blame_inline_internal(true, cx);
11348 cx.notify();
11349 }
11350
11351 pub fn git_blame_inline_enabled(&self) -> bool {
11352 self.git_blame_inline_enabled
11353 }
11354
11355 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11356 self.show_selection_menu = self
11357 .show_selection_menu
11358 .map(|show_selections_menu| !show_selections_menu)
11359 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11360
11361 cx.notify();
11362 }
11363
11364 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11365 self.show_selection_menu
11366 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11367 }
11368
11369 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11370 if let Some(project) = self.project.as_ref() {
11371 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11372 return;
11373 };
11374
11375 if buffer.read(cx).file().is_none() {
11376 return;
11377 }
11378
11379 let focused = self.focus_handle(cx).contains_focused(cx);
11380
11381 let project = project.clone();
11382 let blame =
11383 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11384 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11385 self.blame = Some(blame);
11386 }
11387 }
11388
11389 fn toggle_git_blame_inline_internal(
11390 &mut self,
11391 user_triggered: bool,
11392 cx: &mut ViewContext<Self>,
11393 ) {
11394 if self.git_blame_inline_enabled {
11395 self.git_blame_inline_enabled = false;
11396 self.show_git_blame_inline = false;
11397 self.show_git_blame_inline_delay_task.take();
11398 } else {
11399 self.git_blame_inline_enabled = true;
11400 self.start_git_blame_inline(user_triggered, cx);
11401 }
11402
11403 cx.notify();
11404 }
11405
11406 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11407 self.start_git_blame(user_triggered, cx);
11408
11409 if ProjectSettings::get_global(cx)
11410 .git
11411 .inline_blame_delay()
11412 .is_some()
11413 {
11414 self.start_inline_blame_timer(cx);
11415 } else {
11416 self.show_git_blame_inline = true
11417 }
11418 }
11419
11420 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11421 self.blame.as_ref()
11422 }
11423
11424 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11425 self.show_git_blame_gutter && self.has_blame_entries(cx)
11426 }
11427
11428 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11429 self.show_git_blame_inline
11430 && self.focus_handle.is_focused(cx)
11431 && !self.newest_selection_head_on_empty_line(cx)
11432 && self.has_blame_entries(cx)
11433 }
11434
11435 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11436 self.blame()
11437 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11438 }
11439
11440 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11441 let cursor_anchor = self.selections.newest_anchor().head();
11442
11443 let snapshot = self.buffer.read(cx).snapshot(cx);
11444 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11445
11446 snapshot.line_len(buffer_row) == 0
11447 }
11448
11449 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11450 let (path, selection, repo) = maybe!({
11451 let project_handle = self.project.as_ref()?.clone();
11452 let project = project_handle.read(cx);
11453
11454 let selection = self.selections.newest::<Point>(cx);
11455 let selection_range = selection.range();
11456
11457 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11458 (buffer, selection_range.start.row..selection_range.end.row)
11459 } else {
11460 let buffer_ranges = self
11461 .buffer()
11462 .read(cx)
11463 .range_to_buffer_ranges(selection_range, cx);
11464
11465 let (buffer, range, _) = if selection.reversed {
11466 buffer_ranges.first()
11467 } else {
11468 buffer_ranges.last()
11469 }?;
11470
11471 let snapshot = buffer.read(cx).snapshot();
11472 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11473 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11474 (buffer.clone(), selection)
11475 };
11476
11477 let path = buffer
11478 .read(cx)
11479 .file()?
11480 .as_local()?
11481 .path()
11482 .to_str()?
11483 .to_string();
11484 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11485 Some((path, selection, repo))
11486 })
11487 .ok_or_else(|| anyhow!("unable to open git repository"))?;
11488
11489 const REMOTE_NAME: &str = "origin";
11490 let origin_url = repo
11491 .remote_url(REMOTE_NAME)
11492 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11493 let sha = repo
11494 .head_sha()
11495 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11496
11497 let (provider, remote) =
11498 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11499 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11500
11501 Ok(provider.build_permalink(
11502 remote,
11503 BuildPermalinkParams {
11504 sha: &sha,
11505 path: &path,
11506 selection: Some(selection),
11507 },
11508 ))
11509 }
11510
11511 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11512 let permalink = self.get_permalink_to_line(cx);
11513
11514 match permalink {
11515 Ok(permalink) => {
11516 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11517 }
11518 Err(err) => {
11519 let message = format!("Failed to copy permalink: {err}");
11520
11521 Err::<(), anyhow::Error>(err).log_err();
11522
11523 if let Some(workspace) = self.workspace() {
11524 workspace.update(cx, |workspace, cx| {
11525 struct CopyPermalinkToLine;
11526
11527 workspace.show_toast(
11528 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11529 cx,
11530 )
11531 })
11532 }
11533 }
11534 }
11535 }
11536
11537 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11538 if let Some(file) = self.target_file(cx) {
11539 if let Some(path) = file.path().to_str() {
11540 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11541 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11542 }
11543 }
11544 }
11545
11546 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11547 let permalink = self.get_permalink_to_line(cx);
11548
11549 match permalink {
11550 Ok(permalink) => {
11551 cx.open_url(permalink.as_ref());
11552 }
11553 Err(err) => {
11554 let message = format!("Failed to open permalink: {err}");
11555
11556 Err::<(), anyhow::Error>(err).log_err();
11557
11558 if let Some(workspace) = self.workspace() {
11559 workspace.update(cx, |workspace, cx| {
11560 struct OpenPermalinkToLine;
11561
11562 workspace.show_toast(
11563 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11564 cx,
11565 )
11566 })
11567 }
11568 }
11569 }
11570 }
11571
11572 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11573 /// last highlight added will be used.
11574 ///
11575 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11576 pub fn highlight_rows<T: 'static>(
11577 &mut self,
11578 range: Range<Anchor>,
11579 color: Hsla,
11580 should_autoscroll: bool,
11581 cx: &mut ViewContext<Self>,
11582 ) {
11583 let snapshot = self.buffer().read(cx).snapshot(cx);
11584 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11585 let ix = row_highlights.binary_search_by(|highlight| {
11586 Ordering::Equal
11587 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11588 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11589 });
11590
11591 if let Err(mut ix) = ix {
11592 let index = post_inc(&mut self.highlight_order);
11593
11594 // If this range intersects with the preceding highlight, then merge it with
11595 // the preceding highlight. Otherwise insert a new highlight.
11596 let mut merged = false;
11597 if ix > 0 {
11598 let prev_highlight = &mut row_highlights[ix - 1];
11599 if prev_highlight
11600 .range
11601 .end
11602 .cmp(&range.start, &snapshot)
11603 .is_ge()
11604 {
11605 ix -= 1;
11606 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11607 prev_highlight.range.end = range.end;
11608 }
11609 merged = true;
11610 prev_highlight.index = index;
11611 prev_highlight.color = color;
11612 prev_highlight.should_autoscroll = should_autoscroll;
11613 }
11614 }
11615
11616 if !merged {
11617 row_highlights.insert(
11618 ix,
11619 RowHighlight {
11620 range: range.clone(),
11621 index,
11622 color,
11623 should_autoscroll,
11624 },
11625 );
11626 }
11627
11628 // If any of the following highlights intersect with this one, merge them.
11629 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11630 let highlight = &row_highlights[ix];
11631 if next_highlight
11632 .range
11633 .start
11634 .cmp(&highlight.range.end, &snapshot)
11635 .is_le()
11636 {
11637 if next_highlight
11638 .range
11639 .end
11640 .cmp(&highlight.range.end, &snapshot)
11641 .is_gt()
11642 {
11643 row_highlights[ix].range.end = next_highlight.range.end;
11644 }
11645 row_highlights.remove(ix + 1);
11646 } else {
11647 break;
11648 }
11649 }
11650 }
11651 }
11652
11653 /// Remove any highlighted row ranges of the given type that intersect the
11654 /// given ranges.
11655 pub fn remove_highlighted_rows<T: 'static>(
11656 &mut self,
11657 ranges_to_remove: Vec<Range<Anchor>>,
11658 cx: &mut ViewContext<Self>,
11659 ) {
11660 let snapshot = self.buffer().read(cx).snapshot(cx);
11661 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11662 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11663 row_highlights.retain(|highlight| {
11664 while let Some(range_to_remove) = ranges_to_remove.peek() {
11665 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11666 Ordering::Less | Ordering::Equal => {
11667 ranges_to_remove.next();
11668 }
11669 Ordering::Greater => {
11670 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11671 Ordering::Less | Ordering::Equal => {
11672 return false;
11673 }
11674 Ordering::Greater => break,
11675 }
11676 }
11677 }
11678 }
11679
11680 true
11681 })
11682 }
11683
11684 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11685 pub fn clear_row_highlights<T: 'static>(&mut self) {
11686 self.highlighted_rows.remove(&TypeId::of::<T>());
11687 }
11688
11689 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11690 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11691 self.highlighted_rows
11692 .get(&TypeId::of::<T>())
11693 .map_or(&[] as &[_], |vec| vec.as_slice())
11694 .iter()
11695 .map(|highlight| (highlight.range.clone(), highlight.color))
11696 }
11697
11698 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11699 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11700 /// Allows to ignore certain kinds of highlights.
11701 pub fn highlighted_display_rows(
11702 &mut self,
11703 cx: &mut WindowContext,
11704 ) -> BTreeMap<DisplayRow, Hsla> {
11705 let snapshot = self.snapshot(cx);
11706 let mut used_highlight_orders = HashMap::default();
11707 self.highlighted_rows
11708 .iter()
11709 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11710 .fold(
11711 BTreeMap::<DisplayRow, Hsla>::new(),
11712 |mut unique_rows, highlight| {
11713 let start = highlight.range.start.to_display_point(&snapshot);
11714 let end = highlight.range.end.to_display_point(&snapshot);
11715 let start_row = start.row().0;
11716 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11717 && end.column() == 0
11718 {
11719 end.row().0.saturating_sub(1)
11720 } else {
11721 end.row().0
11722 };
11723 for row in start_row..=end_row {
11724 let used_index =
11725 used_highlight_orders.entry(row).or_insert(highlight.index);
11726 if highlight.index >= *used_index {
11727 *used_index = highlight.index;
11728 unique_rows.insert(DisplayRow(row), highlight.color);
11729 }
11730 }
11731 unique_rows
11732 },
11733 )
11734 }
11735
11736 pub fn highlighted_display_row_for_autoscroll(
11737 &self,
11738 snapshot: &DisplaySnapshot,
11739 ) -> Option<DisplayRow> {
11740 self.highlighted_rows
11741 .values()
11742 .flat_map(|highlighted_rows| highlighted_rows.iter())
11743 .filter_map(|highlight| {
11744 if highlight.should_autoscroll {
11745 Some(highlight.range.start.to_display_point(snapshot).row())
11746 } else {
11747 None
11748 }
11749 })
11750 .min()
11751 }
11752
11753 pub fn set_search_within_ranges(
11754 &mut self,
11755 ranges: &[Range<Anchor>],
11756 cx: &mut ViewContext<Self>,
11757 ) {
11758 self.highlight_background::<SearchWithinRange>(
11759 ranges,
11760 |colors| colors.editor_document_highlight_read_background,
11761 cx,
11762 )
11763 }
11764
11765 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11766 self.breadcrumb_header = Some(new_header);
11767 }
11768
11769 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11770 self.clear_background_highlights::<SearchWithinRange>(cx);
11771 }
11772
11773 pub fn highlight_background<T: 'static>(
11774 &mut self,
11775 ranges: &[Range<Anchor>],
11776 color_fetcher: fn(&ThemeColors) -> Hsla,
11777 cx: &mut ViewContext<Self>,
11778 ) {
11779 self.background_highlights
11780 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11781 self.scrollbar_marker_state.dirty = true;
11782 cx.notify();
11783 }
11784
11785 pub fn clear_background_highlights<T: 'static>(
11786 &mut self,
11787 cx: &mut ViewContext<Self>,
11788 ) -> Option<BackgroundHighlight> {
11789 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11790 if !text_highlights.1.is_empty() {
11791 self.scrollbar_marker_state.dirty = true;
11792 cx.notify();
11793 }
11794 Some(text_highlights)
11795 }
11796
11797 pub fn highlight_gutter<T: 'static>(
11798 &mut self,
11799 ranges: &[Range<Anchor>],
11800 color_fetcher: fn(&AppContext) -> Hsla,
11801 cx: &mut ViewContext<Self>,
11802 ) {
11803 self.gutter_highlights
11804 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11805 cx.notify();
11806 }
11807
11808 pub fn clear_gutter_highlights<T: 'static>(
11809 &mut self,
11810 cx: &mut ViewContext<Self>,
11811 ) -> Option<GutterHighlight> {
11812 cx.notify();
11813 self.gutter_highlights.remove(&TypeId::of::<T>())
11814 }
11815
11816 #[cfg(feature = "test-support")]
11817 pub fn all_text_background_highlights(
11818 &mut self,
11819 cx: &mut ViewContext<Self>,
11820 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11821 let snapshot = self.snapshot(cx);
11822 let buffer = &snapshot.buffer_snapshot;
11823 let start = buffer.anchor_before(0);
11824 let end = buffer.anchor_after(buffer.len());
11825 let theme = cx.theme().colors();
11826 self.background_highlights_in_range(start..end, &snapshot, theme)
11827 }
11828
11829 #[cfg(feature = "test-support")]
11830 pub fn search_background_highlights(
11831 &mut self,
11832 cx: &mut ViewContext<Self>,
11833 ) -> Vec<Range<Point>> {
11834 let snapshot = self.buffer().read(cx).snapshot(cx);
11835
11836 let highlights = self
11837 .background_highlights
11838 .get(&TypeId::of::<items::BufferSearchHighlights>());
11839
11840 if let Some((_color, ranges)) = highlights {
11841 ranges
11842 .iter()
11843 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11844 .collect_vec()
11845 } else {
11846 vec![]
11847 }
11848 }
11849
11850 fn document_highlights_for_position<'a>(
11851 &'a self,
11852 position: Anchor,
11853 buffer: &'a MultiBufferSnapshot,
11854 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11855 let read_highlights = self
11856 .background_highlights
11857 .get(&TypeId::of::<DocumentHighlightRead>())
11858 .map(|h| &h.1);
11859 let write_highlights = self
11860 .background_highlights
11861 .get(&TypeId::of::<DocumentHighlightWrite>())
11862 .map(|h| &h.1);
11863 let left_position = position.bias_left(buffer);
11864 let right_position = position.bias_right(buffer);
11865 read_highlights
11866 .into_iter()
11867 .chain(write_highlights)
11868 .flat_map(move |ranges| {
11869 let start_ix = match ranges.binary_search_by(|probe| {
11870 let cmp = probe.end.cmp(&left_position, buffer);
11871 if cmp.is_ge() {
11872 Ordering::Greater
11873 } else {
11874 Ordering::Less
11875 }
11876 }) {
11877 Ok(i) | Err(i) => i,
11878 };
11879
11880 ranges[start_ix..]
11881 .iter()
11882 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11883 })
11884 }
11885
11886 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11887 self.background_highlights
11888 .get(&TypeId::of::<T>())
11889 .map_or(false, |(_, highlights)| !highlights.is_empty())
11890 }
11891
11892 pub fn background_highlights_in_range(
11893 &self,
11894 search_range: Range<Anchor>,
11895 display_snapshot: &DisplaySnapshot,
11896 theme: &ThemeColors,
11897 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11898 let mut results = Vec::new();
11899 for (color_fetcher, ranges) in self.background_highlights.values() {
11900 let color = color_fetcher(theme);
11901 let start_ix = match ranges.binary_search_by(|probe| {
11902 let cmp = probe
11903 .end
11904 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11905 if cmp.is_gt() {
11906 Ordering::Greater
11907 } else {
11908 Ordering::Less
11909 }
11910 }) {
11911 Ok(i) | Err(i) => i,
11912 };
11913 for range in &ranges[start_ix..] {
11914 if range
11915 .start
11916 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11917 .is_ge()
11918 {
11919 break;
11920 }
11921
11922 let start = range.start.to_display_point(display_snapshot);
11923 let end = range.end.to_display_point(display_snapshot);
11924 results.push((start..end, color))
11925 }
11926 }
11927 results
11928 }
11929
11930 pub fn background_highlight_row_ranges<T: 'static>(
11931 &self,
11932 search_range: Range<Anchor>,
11933 display_snapshot: &DisplaySnapshot,
11934 count: usize,
11935 ) -> Vec<RangeInclusive<DisplayPoint>> {
11936 let mut results = Vec::new();
11937 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11938 return vec![];
11939 };
11940
11941 let start_ix = match ranges.binary_search_by(|probe| {
11942 let cmp = probe
11943 .end
11944 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11945 if cmp.is_gt() {
11946 Ordering::Greater
11947 } else {
11948 Ordering::Less
11949 }
11950 }) {
11951 Ok(i) | Err(i) => i,
11952 };
11953 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11954 if let (Some(start_display), Some(end_display)) = (start, end) {
11955 results.push(
11956 start_display.to_display_point(display_snapshot)
11957 ..=end_display.to_display_point(display_snapshot),
11958 );
11959 }
11960 };
11961 let mut start_row: Option<Point> = None;
11962 let mut end_row: Option<Point> = None;
11963 if ranges.len() > count {
11964 return Vec::new();
11965 }
11966 for range in &ranges[start_ix..] {
11967 if range
11968 .start
11969 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11970 .is_ge()
11971 {
11972 break;
11973 }
11974 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11975 if let Some(current_row) = &end_row {
11976 if end.row == current_row.row {
11977 continue;
11978 }
11979 }
11980 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11981 if start_row.is_none() {
11982 assert_eq!(end_row, None);
11983 start_row = Some(start);
11984 end_row = Some(end);
11985 continue;
11986 }
11987 if let Some(current_end) = end_row.as_mut() {
11988 if start.row > current_end.row + 1 {
11989 push_region(start_row, end_row);
11990 start_row = Some(start);
11991 end_row = Some(end);
11992 } else {
11993 // Merge two hunks.
11994 *current_end = end;
11995 }
11996 } else {
11997 unreachable!();
11998 }
11999 }
12000 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
12001 push_region(start_row, end_row);
12002 results
12003 }
12004
12005 pub fn gutter_highlights_in_range(
12006 &self,
12007 search_range: Range<Anchor>,
12008 display_snapshot: &DisplaySnapshot,
12009 cx: &AppContext,
12010 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
12011 let mut results = Vec::new();
12012 for (color_fetcher, ranges) in self.gutter_highlights.values() {
12013 let color = color_fetcher(cx);
12014 let start_ix = match ranges.binary_search_by(|probe| {
12015 let cmp = probe
12016 .end
12017 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
12018 if cmp.is_gt() {
12019 Ordering::Greater
12020 } else {
12021 Ordering::Less
12022 }
12023 }) {
12024 Ok(i) | Err(i) => i,
12025 };
12026 for range in &ranges[start_ix..] {
12027 if range
12028 .start
12029 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
12030 .is_ge()
12031 {
12032 break;
12033 }
12034
12035 let start = range.start.to_display_point(display_snapshot);
12036 let end = range.end.to_display_point(display_snapshot);
12037 results.push((start..end, color))
12038 }
12039 }
12040 results
12041 }
12042
12043 /// Get the text ranges corresponding to the redaction query
12044 pub fn redacted_ranges(
12045 &self,
12046 search_range: Range<Anchor>,
12047 display_snapshot: &DisplaySnapshot,
12048 cx: &WindowContext,
12049 ) -> Vec<Range<DisplayPoint>> {
12050 display_snapshot
12051 .buffer_snapshot
12052 .redacted_ranges(search_range, |file| {
12053 if let Some(file) = file {
12054 file.is_private()
12055 && EditorSettings::get(
12056 Some(SettingsLocation {
12057 worktree_id: file.worktree_id(cx),
12058 path: file.path().as_ref(),
12059 }),
12060 cx,
12061 )
12062 .redact_private_values
12063 } else {
12064 false
12065 }
12066 })
12067 .map(|range| {
12068 range.start.to_display_point(display_snapshot)
12069 ..range.end.to_display_point(display_snapshot)
12070 })
12071 .collect()
12072 }
12073
12074 pub fn highlight_text<T: 'static>(
12075 &mut self,
12076 ranges: Vec<Range<Anchor>>,
12077 style: HighlightStyle,
12078 cx: &mut ViewContext<Self>,
12079 ) {
12080 self.display_map.update(cx, |map, _| {
12081 map.highlight_text(TypeId::of::<T>(), ranges, style)
12082 });
12083 cx.notify();
12084 }
12085
12086 pub(crate) fn highlight_inlays<T: 'static>(
12087 &mut self,
12088 highlights: Vec<InlayHighlight>,
12089 style: HighlightStyle,
12090 cx: &mut ViewContext<Self>,
12091 ) {
12092 self.display_map.update(cx, |map, _| {
12093 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12094 });
12095 cx.notify();
12096 }
12097
12098 pub fn text_highlights<'a, T: 'static>(
12099 &'a self,
12100 cx: &'a AppContext,
12101 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12102 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12103 }
12104
12105 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12106 let cleared = self
12107 .display_map
12108 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12109 if cleared {
12110 cx.notify();
12111 }
12112 }
12113
12114 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12115 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12116 && self.focus_handle.is_focused(cx)
12117 }
12118
12119 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12120 self.show_cursor_when_unfocused = is_enabled;
12121 cx.notify();
12122 }
12123
12124 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12125 cx.notify();
12126 }
12127
12128 fn on_buffer_event(
12129 &mut self,
12130 multibuffer: Model<MultiBuffer>,
12131 event: &multi_buffer::Event,
12132 cx: &mut ViewContext<Self>,
12133 ) {
12134 match event {
12135 multi_buffer::Event::Edited {
12136 singleton_buffer_edited,
12137 } => {
12138 self.scrollbar_marker_state.dirty = true;
12139 self.active_indent_guides_state.dirty = true;
12140 self.refresh_active_diagnostics(cx);
12141 self.refresh_code_actions(cx);
12142 if self.has_active_inline_completion(cx) {
12143 self.update_visible_inline_completion(cx);
12144 }
12145 cx.emit(EditorEvent::BufferEdited);
12146 cx.emit(SearchEvent::MatchesInvalidated);
12147 if *singleton_buffer_edited {
12148 if let Some(project) = &self.project {
12149 let project = project.read(cx);
12150 #[allow(clippy::mutable_key_type)]
12151 let languages_affected = multibuffer
12152 .read(cx)
12153 .all_buffers()
12154 .into_iter()
12155 .filter_map(|buffer| {
12156 let buffer = buffer.read(cx);
12157 let language = buffer.language()?;
12158 if project.is_local()
12159 && project.language_servers_for_buffer(buffer, cx).count() == 0
12160 {
12161 None
12162 } else {
12163 Some(language)
12164 }
12165 })
12166 .cloned()
12167 .collect::<HashSet<_>>();
12168 if !languages_affected.is_empty() {
12169 self.refresh_inlay_hints(
12170 InlayHintRefreshReason::BufferEdited(languages_affected),
12171 cx,
12172 );
12173 }
12174 }
12175 }
12176
12177 let Some(project) = &self.project else { return };
12178 let (telemetry, is_via_ssh) = {
12179 let project = project.read(cx);
12180 let telemetry = project.client().telemetry().clone();
12181 let is_via_ssh = project.is_via_ssh();
12182 (telemetry, is_via_ssh)
12183 };
12184 refresh_linked_ranges(self, cx);
12185 telemetry.log_edit_event("editor", is_via_ssh);
12186 }
12187 multi_buffer::Event::ExcerptsAdded {
12188 buffer,
12189 predecessor,
12190 excerpts,
12191 } => {
12192 self.tasks_update_task = Some(self.refresh_runnables(cx));
12193 cx.emit(EditorEvent::ExcerptsAdded {
12194 buffer: buffer.clone(),
12195 predecessor: *predecessor,
12196 excerpts: excerpts.clone(),
12197 });
12198 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12199 }
12200 multi_buffer::Event::ExcerptsRemoved { ids } => {
12201 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12202 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12203 }
12204 multi_buffer::Event::ExcerptsEdited { ids } => {
12205 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12206 }
12207 multi_buffer::Event::ExcerptsExpanded { ids } => {
12208 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12209 }
12210 multi_buffer::Event::Reparsed(buffer_id) => {
12211 self.tasks_update_task = Some(self.refresh_runnables(cx));
12212
12213 cx.emit(EditorEvent::Reparsed(*buffer_id));
12214 }
12215 multi_buffer::Event::LanguageChanged(buffer_id) => {
12216 linked_editing_ranges::refresh_linked_ranges(self, cx);
12217 cx.emit(EditorEvent::Reparsed(*buffer_id));
12218 cx.notify();
12219 }
12220 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12221 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12222 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12223 cx.emit(EditorEvent::TitleChanged)
12224 }
12225 multi_buffer::Event::DiffBaseChanged => {
12226 self.scrollbar_marker_state.dirty = true;
12227 cx.emit(EditorEvent::DiffBaseChanged);
12228 cx.notify();
12229 }
12230 multi_buffer::Event::DiffUpdated { buffer } => {
12231 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12232 cx.notify();
12233 }
12234 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12235 multi_buffer::Event::DiagnosticsUpdated => {
12236 self.refresh_active_diagnostics(cx);
12237 self.scrollbar_marker_state.dirty = true;
12238 cx.notify();
12239 }
12240 _ => {}
12241 };
12242 }
12243
12244 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12245 cx.notify();
12246 }
12247
12248 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12249 self.tasks_update_task = Some(self.refresh_runnables(cx));
12250 self.refresh_inline_completion(true, false, cx);
12251 self.refresh_inlay_hints(
12252 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12253 self.selections.newest_anchor().head(),
12254 &self.buffer.read(cx).snapshot(cx),
12255 cx,
12256 )),
12257 cx,
12258 );
12259
12260 let old_cursor_shape = self.cursor_shape;
12261
12262 {
12263 let editor_settings = EditorSettings::get_global(cx);
12264 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12265 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12266 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12267 }
12268
12269 if old_cursor_shape != self.cursor_shape {
12270 cx.emit(EditorEvent::CursorShapeChanged);
12271 }
12272
12273 let project_settings = ProjectSettings::get_global(cx);
12274 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12275
12276 if self.mode == EditorMode::Full {
12277 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12278 if self.git_blame_inline_enabled != inline_blame_enabled {
12279 self.toggle_git_blame_inline_internal(false, cx);
12280 }
12281 }
12282
12283 cx.notify();
12284 }
12285
12286 pub fn set_searchable(&mut self, searchable: bool) {
12287 self.searchable = searchable;
12288 }
12289
12290 pub fn searchable(&self) -> bool {
12291 self.searchable
12292 }
12293
12294 fn open_proposed_changes_editor(
12295 &mut self,
12296 _: &OpenProposedChangesEditor,
12297 cx: &mut ViewContext<Self>,
12298 ) {
12299 let Some(workspace) = self.workspace() else {
12300 cx.propagate();
12301 return;
12302 };
12303
12304 let buffer = self.buffer.read(cx);
12305 let mut new_selections_by_buffer = HashMap::default();
12306 for selection in self.selections.all::<usize>(cx) {
12307 for (buffer, range, _) in
12308 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12309 {
12310 let mut range = range.to_point(buffer.read(cx));
12311 range.start.column = 0;
12312 range.end.column = buffer.read(cx).line_len(range.end.row);
12313 new_selections_by_buffer
12314 .entry(buffer)
12315 .or_insert(Vec::new())
12316 .push(range)
12317 }
12318 }
12319
12320 let proposed_changes_buffers = new_selections_by_buffer
12321 .into_iter()
12322 .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
12323 .collect::<Vec<_>>();
12324 let proposed_changes_editor = cx.new_view(|cx| {
12325 ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
12326 });
12327
12328 cx.window_context().defer(move |cx| {
12329 workspace.update(cx, |workspace, cx| {
12330 workspace.active_pane().update(cx, |pane, cx| {
12331 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12332 });
12333 });
12334 });
12335 }
12336
12337 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12338 self.open_excerpts_common(true, cx)
12339 }
12340
12341 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12342 self.open_excerpts_common(false, cx)
12343 }
12344
12345 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12346 let buffer = self.buffer.read(cx);
12347 if buffer.is_singleton() {
12348 cx.propagate();
12349 return;
12350 }
12351
12352 let Some(workspace) = self.workspace() else {
12353 cx.propagate();
12354 return;
12355 };
12356
12357 let mut new_selections_by_buffer = HashMap::default();
12358 for selection in self.selections.all::<usize>(cx) {
12359 for (buffer, mut range, _) in
12360 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12361 {
12362 if selection.reversed {
12363 mem::swap(&mut range.start, &mut range.end);
12364 }
12365 new_selections_by_buffer
12366 .entry(buffer)
12367 .or_insert(Vec::new())
12368 .push(range)
12369 }
12370 }
12371
12372 // We defer the pane interaction because we ourselves are a workspace item
12373 // and activating a new item causes the pane to call a method on us reentrantly,
12374 // which panics if we're on the stack.
12375 cx.window_context().defer(move |cx| {
12376 workspace.update(cx, |workspace, cx| {
12377 let pane = if split {
12378 workspace.adjacent_pane(cx)
12379 } else {
12380 workspace.active_pane().clone()
12381 };
12382
12383 for (buffer, ranges) in new_selections_by_buffer {
12384 let editor =
12385 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12386 editor.update(cx, |editor, cx| {
12387 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12388 s.select_ranges(ranges);
12389 });
12390 });
12391 }
12392 })
12393 });
12394 }
12395
12396 fn jump(
12397 &mut self,
12398 path: ProjectPath,
12399 position: Point,
12400 anchor: language::Anchor,
12401 offset_from_top: u32,
12402 cx: &mut ViewContext<Self>,
12403 ) {
12404 let workspace = self.workspace();
12405 cx.spawn(|_, mut cx| async move {
12406 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12407 let editor = workspace.update(&mut cx, |workspace, cx| {
12408 // Reset the preview item id before opening the new item
12409 workspace.active_pane().update(cx, |pane, cx| {
12410 pane.set_preview_item_id(None, cx);
12411 });
12412 workspace.open_path_preview(path, None, true, true, cx)
12413 })?;
12414 let editor = editor
12415 .await?
12416 .downcast::<Editor>()
12417 .ok_or_else(|| anyhow!("opened item was not an editor"))?
12418 .downgrade();
12419 editor.update(&mut cx, |editor, cx| {
12420 let buffer = editor
12421 .buffer()
12422 .read(cx)
12423 .as_singleton()
12424 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12425 let buffer = buffer.read(cx);
12426 let cursor = if buffer.can_resolve(&anchor) {
12427 language::ToPoint::to_point(&anchor, buffer)
12428 } else {
12429 buffer.clip_point(position, Bias::Left)
12430 };
12431
12432 let nav_history = editor.nav_history.take();
12433 editor.change_selections(
12434 Some(Autoscroll::top_relative(offset_from_top as usize)),
12435 cx,
12436 |s| {
12437 s.select_ranges([cursor..cursor]);
12438 },
12439 );
12440 editor.nav_history = nav_history;
12441
12442 anyhow::Ok(())
12443 })??;
12444
12445 anyhow::Ok(())
12446 })
12447 .detach_and_log_err(cx);
12448 }
12449
12450 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12451 let snapshot = self.buffer.read(cx).read(cx);
12452 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12453 Some(
12454 ranges
12455 .iter()
12456 .map(move |range| {
12457 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12458 })
12459 .collect(),
12460 )
12461 }
12462
12463 fn selection_replacement_ranges(
12464 &self,
12465 range: Range<OffsetUtf16>,
12466 cx: &AppContext,
12467 ) -> Vec<Range<OffsetUtf16>> {
12468 let selections = self.selections.all::<OffsetUtf16>(cx);
12469 let newest_selection = selections
12470 .iter()
12471 .max_by_key(|selection| selection.id)
12472 .unwrap();
12473 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12474 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12475 let snapshot = self.buffer.read(cx).read(cx);
12476 selections
12477 .into_iter()
12478 .map(|mut selection| {
12479 selection.start.0 =
12480 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12481 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12482 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12483 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12484 })
12485 .collect()
12486 }
12487
12488 fn report_editor_event(
12489 &self,
12490 operation: &'static str,
12491 file_extension: Option<String>,
12492 cx: &AppContext,
12493 ) {
12494 if cfg!(any(test, feature = "test-support")) {
12495 return;
12496 }
12497
12498 let Some(project) = &self.project else { return };
12499
12500 // If None, we are in a file without an extension
12501 let file = self
12502 .buffer
12503 .read(cx)
12504 .as_singleton()
12505 .and_then(|b| b.read(cx).file());
12506 let file_extension = file_extension.or(file
12507 .as_ref()
12508 .and_then(|file| Path::new(file.file_name(cx)).extension())
12509 .and_then(|e| e.to_str())
12510 .map(|a| a.to_string()));
12511
12512 let vim_mode = cx
12513 .global::<SettingsStore>()
12514 .raw_user_settings()
12515 .get("vim_mode")
12516 == Some(&serde_json::Value::Bool(true));
12517
12518 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12519 == language::language_settings::InlineCompletionProvider::Copilot;
12520 let copilot_enabled_for_language = self
12521 .buffer
12522 .read(cx)
12523 .settings_at(0, cx)
12524 .show_inline_completions;
12525
12526 let project = project.read(cx);
12527 let telemetry = project.client().telemetry().clone();
12528 telemetry.report_editor_event(
12529 file_extension,
12530 vim_mode,
12531 operation,
12532 copilot_enabled,
12533 copilot_enabled_for_language,
12534 project.is_via_ssh(),
12535 )
12536 }
12537
12538 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12539 /// with each line being an array of {text, highlight} objects.
12540 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12541 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12542 return;
12543 };
12544
12545 #[derive(Serialize)]
12546 struct Chunk<'a> {
12547 text: String,
12548 highlight: Option<&'a str>,
12549 }
12550
12551 let snapshot = buffer.read(cx).snapshot();
12552 let range = self
12553 .selected_text_range(false, cx)
12554 .and_then(|selection| {
12555 if selection.range.is_empty() {
12556 None
12557 } else {
12558 Some(selection.range)
12559 }
12560 })
12561 .unwrap_or_else(|| 0..snapshot.len());
12562
12563 let chunks = snapshot.chunks(range, true);
12564 let mut lines = Vec::new();
12565 let mut line: VecDeque<Chunk> = VecDeque::new();
12566
12567 let Some(style) = self.style.as_ref() else {
12568 return;
12569 };
12570
12571 for chunk in chunks {
12572 let highlight = chunk
12573 .syntax_highlight_id
12574 .and_then(|id| id.name(&style.syntax));
12575 let mut chunk_lines = chunk.text.split('\n').peekable();
12576 while let Some(text) = chunk_lines.next() {
12577 let mut merged_with_last_token = false;
12578 if let Some(last_token) = line.back_mut() {
12579 if last_token.highlight == highlight {
12580 last_token.text.push_str(text);
12581 merged_with_last_token = true;
12582 }
12583 }
12584
12585 if !merged_with_last_token {
12586 line.push_back(Chunk {
12587 text: text.into(),
12588 highlight,
12589 });
12590 }
12591
12592 if chunk_lines.peek().is_some() {
12593 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12594 line.pop_front();
12595 }
12596 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12597 line.pop_back();
12598 }
12599
12600 lines.push(mem::take(&mut line));
12601 }
12602 }
12603 }
12604
12605 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12606 return;
12607 };
12608 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12609 }
12610
12611 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12612 &self.inlay_hint_cache
12613 }
12614
12615 pub fn replay_insert_event(
12616 &mut self,
12617 text: &str,
12618 relative_utf16_range: Option<Range<isize>>,
12619 cx: &mut ViewContext<Self>,
12620 ) {
12621 if !self.input_enabled {
12622 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12623 return;
12624 }
12625 if let Some(relative_utf16_range) = relative_utf16_range {
12626 let selections = self.selections.all::<OffsetUtf16>(cx);
12627 self.change_selections(None, cx, |s| {
12628 let new_ranges = selections.into_iter().map(|range| {
12629 let start = OffsetUtf16(
12630 range
12631 .head()
12632 .0
12633 .saturating_add_signed(relative_utf16_range.start),
12634 );
12635 let end = OffsetUtf16(
12636 range
12637 .head()
12638 .0
12639 .saturating_add_signed(relative_utf16_range.end),
12640 );
12641 start..end
12642 });
12643 s.select_ranges(new_ranges);
12644 });
12645 }
12646
12647 self.handle_input(text, cx);
12648 }
12649
12650 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12651 let Some(project) = self.project.as_ref() else {
12652 return false;
12653 };
12654 let project = project.read(cx);
12655
12656 let mut supports = false;
12657 self.buffer().read(cx).for_each_buffer(|buffer| {
12658 if !supports {
12659 supports = project
12660 .language_servers_for_buffer(buffer.read(cx), cx)
12661 .any(
12662 |(_, server)| match server.capabilities().inlay_hint_provider {
12663 Some(lsp::OneOf::Left(enabled)) => enabled,
12664 Some(lsp::OneOf::Right(_)) => true,
12665 None => false,
12666 },
12667 )
12668 }
12669 });
12670 supports
12671 }
12672
12673 pub fn focus(&self, cx: &mut WindowContext) {
12674 cx.focus(&self.focus_handle)
12675 }
12676
12677 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12678 self.focus_handle.is_focused(cx)
12679 }
12680
12681 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12682 cx.emit(EditorEvent::Focused);
12683
12684 if let Some(descendant) = self
12685 .last_focused_descendant
12686 .take()
12687 .and_then(|descendant| descendant.upgrade())
12688 {
12689 cx.focus(&descendant);
12690 } else {
12691 if let Some(blame) = self.blame.as_ref() {
12692 blame.update(cx, GitBlame::focus)
12693 }
12694
12695 self.blink_manager.update(cx, BlinkManager::enable);
12696 self.show_cursor_names(cx);
12697 self.buffer.update(cx, |buffer, cx| {
12698 buffer.finalize_last_transaction(cx);
12699 if self.leader_peer_id.is_none() {
12700 buffer.set_active_selections(
12701 &self.selections.disjoint_anchors(),
12702 self.selections.line_mode,
12703 self.cursor_shape,
12704 cx,
12705 );
12706 }
12707 });
12708 }
12709 }
12710
12711 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12712 cx.emit(EditorEvent::FocusedIn)
12713 }
12714
12715 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12716 if event.blurred != self.focus_handle {
12717 self.last_focused_descendant = Some(event.blurred);
12718 }
12719 }
12720
12721 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12722 self.blink_manager.update(cx, BlinkManager::disable);
12723 self.buffer
12724 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12725
12726 if let Some(blame) = self.blame.as_ref() {
12727 blame.update(cx, GitBlame::blur)
12728 }
12729 if !self.hover_state.focused(cx) {
12730 hide_hover(self, cx);
12731 }
12732
12733 self.hide_context_menu(cx);
12734 cx.emit(EditorEvent::Blurred);
12735 cx.notify();
12736 }
12737
12738 pub fn register_action<A: Action>(
12739 &mut self,
12740 listener: impl Fn(&A, &mut WindowContext) + 'static,
12741 ) -> Subscription {
12742 let id = self.next_editor_action_id.post_inc();
12743 let listener = Arc::new(listener);
12744 self.editor_actions.borrow_mut().insert(
12745 id,
12746 Box::new(move |cx| {
12747 let cx = cx.window_context();
12748 let listener = listener.clone();
12749 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12750 let action = action.downcast_ref().unwrap();
12751 if phase == DispatchPhase::Bubble {
12752 listener(action, cx)
12753 }
12754 })
12755 }),
12756 );
12757
12758 let editor_actions = self.editor_actions.clone();
12759 Subscription::new(move || {
12760 editor_actions.borrow_mut().remove(&id);
12761 })
12762 }
12763
12764 pub fn file_header_size(&self) -> u32 {
12765 self.file_header_size
12766 }
12767
12768 pub fn revert(
12769 &mut self,
12770 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12771 cx: &mut ViewContext<Self>,
12772 ) {
12773 self.buffer().update(cx, |multi_buffer, cx| {
12774 for (buffer_id, changes) in revert_changes {
12775 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12776 buffer.update(cx, |buffer, cx| {
12777 buffer.edit(
12778 changes.into_iter().map(|(range, text)| {
12779 (range, text.to_string().map(Arc::<str>::from))
12780 }),
12781 None,
12782 cx,
12783 );
12784 });
12785 }
12786 }
12787 });
12788 self.change_selections(None, cx, |selections| selections.refresh());
12789 }
12790
12791 pub fn to_pixel_point(
12792 &mut self,
12793 source: multi_buffer::Anchor,
12794 editor_snapshot: &EditorSnapshot,
12795 cx: &mut ViewContext<Self>,
12796 ) -> Option<gpui::Point<Pixels>> {
12797 let source_point = source.to_display_point(editor_snapshot);
12798 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12799 }
12800
12801 pub fn display_to_pixel_point(
12802 &mut self,
12803 source: DisplayPoint,
12804 editor_snapshot: &EditorSnapshot,
12805 cx: &mut ViewContext<Self>,
12806 ) -> Option<gpui::Point<Pixels>> {
12807 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12808 let text_layout_details = self.text_layout_details(cx);
12809 let scroll_top = text_layout_details
12810 .scroll_anchor
12811 .scroll_position(editor_snapshot)
12812 .y;
12813
12814 if source.row().as_f32() < scroll_top.floor() {
12815 return None;
12816 }
12817 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12818 let source_y = line_height * (source.row().as_f32() - scroll_top);
12819 Some(gpui::Point::new(source_x, source_y))
12820 }
12821
12822 pub fn has_active_completions_menu(&self) -> bool {
12823 self.context_menu.read().as_ref().map_or(false, |menu| {
12824 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12825 })
12826 }
12827
12828 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12829 self.addons
12830 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12831 }
12832
12833 pub fn unregister_addon<T: Addon>(&mut self) {
12834 self.addons.remove(&std::any::TypeId::of::<T>());
12835 }
12836
12837 pub fn addon<T: Addon>(&self) -> Option<&T> {
12838 let type_id = std::any::TypeId::of::<T>();
12839 self.addons
12840 .get(&type_id)
12841 .and_then(|item| item.to_any().downcast_ref::<T>())
12842 }
12843}
12844
12845fn hunks_for_selections(
12846 multi_buffer_snapshot: &MultiBufferSnapshot,
12847 selections: &[Selection<Anchor>],
12848) -> Vec<MultiBufferDiffHunk> {
12849 let buffer_rows_for_selections = selections.iter().map(|selection| {
12850 let head = selection.head();
12851 let tail = selection.tail();
12852 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12853 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12854 if start > end {
12855 end..start
12856 } else {
12857 start..end
12858 }
12859 });
12860
12861 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12862}
12863
12864pub fn hunks_for_rows(
12865 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12866 multi_buffer_snapshot: &MultiBufferSnapshot,
12867) -> Vec<MultiBufferDiffHunk> {
12868 let mut hunks = Vec::new();
12869 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12870 HashMap::default();
12871 for selected_multi_buffer_rows in rows {
12872 let query_rows =
12873 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12874 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12875 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12876 // when the caret is just above or just below the deleted hunk.
12877 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12878 let related_to_selection = if allow_adjacent {
12879 hunk.row_range.overlaps(&query_rows)
12880 || hunk.row_range.start == query_rows.end
12881 || hunk.row_range.end == query_rows.start
12882 } else {
12883 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12884 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12885 hunk.row_range.overlaps(&selected_multi_buffer_rows)
12886 || selected_multi_buffer_rows.end == hunk.row_range.start
12887 };
12888 if related_to_selection {
12889 if !processed_buffer_rows
12890 .entry(hunk.buffer_id)
12891 .or_default()
12892 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12893 {
12894 continue;
12895 }
12896 hunks.push(hunk);
12897 }
12898 }
12899 }
12900
12901 hunks
12902}
12903
12904pub trait CollaborationHub {
12905 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12906 fn user_participant_indices<'a>(
12907 &self,
12908 cx: &'a AppContext,
12909 ) -> &'a HashMap<u64, ParticipantIndex>;
12910 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12911}
12912
12913impl CollaborationHub for Model<Project> {
12914 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12915 self.read(cx).collaborators()
12916 }
12917
12918 fn user_participant_indices<'a>(
12919 &self,
12920 cx: &'a AppContext,
12921 ) -> &'a HashMap<u64, ParticipantIndex> {
12922 self.read(cx).user_store().read(cx).participant_indices()
12923 }
12924
12925 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12926 let this = self.read(cx);
12927 let user_ids = this.collaborators().values().map(|c| c.user_id);
12928 this.user_store().read_with(cx, |user_store, cx| {
12929 user_store.participant_names(user_ids, cx)
12930 })
12931 }
12932}
12933
12934pub trait CompletionProvider {
12935 fn completions(
12936 &self,
12937 buffer: &Model<Buffer>,
12938 buffer_position: text::Anchor,
12939 trigger: CompletionContext,
12940 cx: &mut ViewContext<Editor>,
12941 ) -> Task<Result<Vec<Completion>>>;
12942
12943 fn resolve_completions(
12944 &self,
12945 buffer: Model<Buffer>,
12946 completion_indices: Vec<usize>,
12947 completions: Arc<RwLock<Box<[Completion]>>>,
12948 cx: &mut ViewContext<Editor>,
12949 ) -> Task<Result<bool>>;
12950
12951 fn apply_additional_edits_for_completion(
12952 &self,
12953 buffer: Model<Buffer>,
12954 completion: Completion,
12955 push_to_history: bool,
12956 cx: &mut ViewContext<Editor>,
12957 ) -> Task<Result<Option<language::Transaction>>>;
12958
12959 fn is_completion_trigger(
12960 &self,
12961 buffer: &Model<Buffer>,
12962 position: language::Anchor,
12963 text: &str,
12964 trigger_in_words: bool,
12965 cx: &mut ViewContext<Editor>,
12966 ) -> bool;
12967
12968 fn sort_completions(&self) -> bool {
12969 true
12970 }
12971}
12972
12973pub trait CodeActionProvider {
12974 fn code_actions(
12975 &self,
12976 buffer: &Model<Buffer>,
12977 range: Range<text::Anchor>,
12978 cx: &mut WindowContext,
12979 ) -> Task<Result<Vec<CodeAction>>>;
12980
12981 fn apply_code_action(
12982 &self,
12983 buffer_handle: Model<Buffer>,
12984 action: CodeAction,
12985 excerpt_id: ExcerptId,
12986 push_to_history: bool,
12987 cx: &mut WindowContext,
12988 ) -> Task<Result<ProjectTransaction>>;
12989}
12990
12991impl CodeActionProvider for Model<Project> {
12992 fn code_actions(
12993 &self,
12994 buffer: &Model<Buffer>,
12995 range: Range<text::Anchor>,
12996 cx: &mut WindowContext,
12997 ) -> Task<Result<Vec<CodeAction>>> {
12998 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
12999 }
13000
13001 fn apply_code_action(
13002 &self,
13003 buffer_handle: Model<Buffer>,
13004 action: CodeAction,
13005 _excerpt_id: ExcerptId,
13006 push_to_history: bool,
13007 cx: &mut WindowContext,
13008 ) -> Task<Result<ProjectTransaction>> {
13009 self.update(cx, |project, cx| {
13010 project.apply_code_action(buffer_handle, action, push_to_history, cx)
13011 })
13012 }
13013}
13014
13015fn snippet_completions(
13016 project: &Project,
13017 buffer: &Model<Buffer>,
13018 buffer_position: text::Anchor,
13019 cx: &mut AppContext,
13020) -> Vec<Completion> {
13021 let language = buffer.read(cx).language_at(buffer_position);
13022 let language_name = language.as_ref().map(|language| language.lsp_id());
13023 let snippet_store = project.snippets().read(cx);
13024 let snippets = snippet_store.snippets_for(language_name, cx);
13025
13026 if snippets.is_empty() {
13027 return vec![];
13028 }
13029 let snapshot = buffer.read(cx).text_snapshot();
13030 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
13031
13032 let mut lines = chunks.lines();
13033 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
13034 return vec![];
13035 };
13036
13037 let scope = language.map(|language| language.default_scope());
13038 let classifier = CharClassifier::new(scope).for_completion(true);
13039 let mut last_word = line_at
13040 .chars()
13041 .rev()
13042 .take_while(|c| classifier.is_word(*c))
13043 .collect::<String>();
13044 last_word = last_word.chars().rev().collect();
13045 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
13046 let to_lsp = |point: &text::Anchor| {
13047 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
13048 point_to_lsp(end)
13049 };
13050 let lsp_end = to_lsp(&buffer_position);
13051 snippets
13052 .into_iter()
13053 .filter_map(|snippet| {
13054 let matching_prefix = snippet
13055 .prefix
13056 .iter()
13057 .find(|prefix| prefix.starts_with(&last_word))?;
13058 let start = as_offset - last_word.len();
13059 let start = snapshot.anchor_before(start);
13060 let range = start..buffer_position;
13061 let lsp_start = to_lsp(&start);
13062 let lsp_range = lsp::Range {
13063 start: lsp_start,
13064 end: lsp_end,
13065 };
13066 Some(Completion {
13067 old_range: range,
13068 new_text: snippet.body.clone(),
13069 label: CodeLabel {
13070 text: matching_prefix.clone(),
13071 runs: vec![],
13072 filter_range: 0..matching_prefix.len(),
13073 },
13074 server_id: LanguageServerId(usize::MAX),
13075 documentation: snippet.description.clone().map(Documentation::SingleLine),
13076 lsp_completion: lsp::CompletionItem {
13077 label: snippet.prefix.first().unwrap().clone(),
13078 kind: Some(CompletionItemKind::SNIPPET),
13079 label_details: snippet.description.as_ref().map(|description| {
13080 lsp::CompletionItemLabelDetails {
13081 detail: Some(description.clone()),
13082 description: None,
13083 }
13084 }),
13085 insert_text_format: Some(InsertTextFormat::SNIPPET),
13086 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13087 lsp::InsertReplaceEdit {
13088 new_text: snippet.body.clone(),
13089 insert: lsp_range,
13090 replace: lsp_range,
13091 },
13092 )),
13093 filter_text: Some(snippet.body.clone()),
13094 sort_text: Some(char::MAX.to_string()),
13095 ..Default::default()
13096 },
13097 confirm: None,
13098 })
13099 })
13100 .collect()
13101}
13102
13103impl CompletionProvider for Model<Project> {
13104 fn completions(
13105 &self,
13106 buffer: &Model<Buffer>,
13107 buffer_position: text::Anchor,
13108 options: CompletionContext,
13109 cx: &mut ViewContext<Editor>,
13110 ) -> Task<Result<Vec<Completion>>> {
13111 self.update(cx, |project, cx| {
13112 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13113 let project_completions = project.completions(buffer, buffer_position, options, cx);
13114 cx.background_executor().spawn(async move {
13115 let mut completions = project_completions.await?;
13116 //let snippets = snippets.into_iter().;
13117 completions.extend(snippets);
13118 Ok(completions)
13119 })
13120 })
13121 }
13122
13123 fn resolve_completions(
13124 &self,
13125 buffer: Model<Buffer>,
13126 completion_indices: Vec<usize>,
13127 completions: Arc<RwLock<Box<[Completion]>>>,
13128 cx: &mut ViewContext<Editor>,
13129 ) -> Task<Result<bool>> {
13130 self.update(cx, |project, cx| {
13131 project.resolve_completions(buffer, completion_indices, completions, cx)
13132 })
13133 }
13134
13135 fn apply_additional_edits_for_completion(
13136 &self,
13137 buffer: Model<Buffer>,
13138 completion: Completion,
13139 push_to_history: bool,
13140 cx: &mut ViewContext<Editor>,
13141 ) -> Task<Result<Option<language::Transaction>>> {
13142 self.update(cx, |project, cx| {
13143 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13144 })
13145 }
13146
13147 fn is_completion_trigger(
13148 &self,
13149 buffer: &Model<Buffer>,
13150 position: language::Anchor,
13151 text: &str,
13152 trigger_in_words: bool,
13153 cx: &mut ViewContext<Editor>,
13154 ) -> bool {
13155 if !EditorSettings::get_global(cx).show_completions_on_input {
13156 return false;
13157 }
13158
13159 let mut chars = text.chars();
13160 let char = if let Some(char) = chars.next() {
13161 char
13162 } else {
13163 return false;
13164 };
13165 if chars.next().is_some() {
13166 return false;
13167 }
13168
13169 let buffer = buffer.read(cx);
13170 let classifier = buffer
13171 .snapshot()
13172 .char_classifier_at(position)
13173 .for_completion(true);
13174 if trigger_in_words && classifier.is_word(char) {
13175 return true;
13176 }
13177
13178 buffer
13179 .completion_triggers()
13180 .iter()
13181 .any(|string| string == text)
13182 }
13183}
13184
13185fn inlay_hint_settings(
13186 location: Anchor,
13187 snapshot: &MultiBufferSnapshot,
13188 cx: &mut ViewContext<'_, Editor>,
13189) -> InlayHintSettings {
13190 let file = snapshot.file_at(location);
13191 let language = snapshot.language_at(location);
13192 let settings = all_language_settings(file, cx);
13193 settings
13194 .language(language.map(|l| l.name()).as_ref())
13195 .inlay_hints
13196}
13197
13198fn consume_contiguous_rows(
13199 contiguous_row_selections: &mut Vec<Selection<Point>>,
13200 selection: &Selection<Point>,
13201 display_map: &DisplaySnapshot,
13202 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13203) -> (MultiBufferRow, MultiBufferRow) {
13204 contiguous_row_selections.push(selection.clone());
13205 let start_row = MultiBufferRow(selection.start.row);
13206 let mut end_row = ending_row(selection, display_map);
13207
13208 while let Some(next_selection) = selections.peek() {
13209 if next_selection.start.row <= end_row.0 {
13210 end_row = ending_row(next_selection, display_map);
13211 contiguous_row_selections.push(selections.next().unwrap().clone());
13212 } else {
13213 break;
13214 }
13215 }
13216 (start_row, end_row)
13217}
13218
13219fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13220 if next_selection.end.column > 0 || next_selection.is_empty() {
13221 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13222 } else {
13223 MultiBufferRow(next_selection.end.row)
13224 }
13225}
13226
13227impl EditorSnapshot {
13228 pub fn remote_selections_in_range<'a>(
13229 &'a self,
13230 range: &'a Range<Anchor>,
13231 collaboration_hub: &dyn CollaborationHub,
13232 cx: &'a AppContext,
13233 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13234 let participant_names = collaboration_hub.user_names(cx);
13235 let participant_indices = collaboration_hub.user_participant_indices(cx);
13236 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13237 let collaborators_by_replica_id = collaborators_by_peer_id
13238 .iter()
13239 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13240 .collect::<HashMap<_, _>>();
13241 self.buffer_snapshot
13242 .selections_in_range(range, false)
13243 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13244 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13245 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13246 let user_name = participant_names.get(&collaborator.user_id).cloned();
13247 Some(RemoteSelection {
13248 replica_id,
13249 selection,
13250 cursor_shape,
13251 line_mode,
13252 participant_index,
13253 peer_id: collaborator.peer_id,
13254 user_name,
13255 })
13256 })
13257 }
13258
13259 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13260 self.display_snapshot.buffer_snapshot.language_at(position)
13261 }
13262
13263 pub fn is_focused(&self) -> bool {
13264 self.is_focused
13265 }
13266
13267 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13268 self.placeholder_text.as_ref()
13269 }
13270
13271 pub fn scroll_position(&self) -> gpui::Point<f32> {
13272 self.scroll_anchor.scroll_position(&self.display_snapshot)
13273 }
13274
13275 fn gutter_dimensions(
13276 &self,
13277 font_id: FontId,
13278 font_size: Pixels,
13279 em_width: Pixels,
13280 em_advance: Pixels,
13281 max_line_number_width: Pixels,
13282 cx: &AppContext,
13283 ) -> GutterDimensions {
13284 if !self.show_gutter {
13285 return GutterDimensions::default();
13286 }
13287 let descent = cx.text_system().descent(font_id, font_size);
13288
13289 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13290 matches!(
13291 ProjectSettings::get_global(cx).git.git_gutter,
13292 Some(GitGutterSetting::TrackedFiles)
13293 )
13294 });
13295 let gutter_settings = EditorSettings::get_global(cx).gutter;
13296 let show_line_numbers = self
13297 .show_line_numbers
13298 .unwrap_or(gutter_settings.line_numbers);
13299 let line_gutter_width = if show_line_numbers {
13300 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13301 let min_width_for_number_on_gutter = em_advance * 4.0;
13302 max_line_number_width.max(min_width_for_number_on_gutter)
13303 } else {
13304 0.0.into()
13305 };
13306
13307 let show_code_actions = self
13308 .show_code_actions
13309 .unwrap_or(gutter_settings.code_actions);
13310
13311 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13312
13313 let git_blame_entries_width =
13314 self.git_blame_gutter_max_author_length
13315 .map(|max_author_length| {
13316 // Length of the author name, but also space for the commit hash,
13317 // the spacing and the timestamp.
13318 let max_char_count = max_author_length
13319 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13320 + 7 // length of commit sha
13321 + 14 // length of max relative timestamp ("60 minutes ago")
13322 + 4; // gaps and margins
13323
13324 em_advance * max_char_count
13325 });
13326
13327 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13328 left_padding += if show_code_actions || show_runnables {
13329 em_width * 3.0
13330 } else if show_git_gutter && show_line_numbers {
13331 em_width * 2.0
13332 } else if show_git_gutter || show_line_numbers {
13333 em_width
13334 } else {
13335 px(0.)
13336 };
13337
13338 let right_padding = if gutter_settings.folds && show_line_numbers {
13339 em_width * 4.0
13340 } else if gutter_settings.folds {
13341 em_width * 3.0
13342 } else if show_line_numbers {
13343 em_width
13344 } else {
13345 px(0.)
13346 };
13347
13348 GutterDimensions {
13349 left_padding,
13350 right_padding,
13351 width: line_gutter_width + left_padding + right_padding,
13352 margin: -descent,
13353 git_blame_entries_width,
13354 }
13355 }
13356
13357 pub fn render_fold_toggle(
13358 &self,
13359 buffer_row: MultiBufferRow,
13360 row_contains_cursor: bool,
13361 editor: View<Editor>,
13362 cx: &mut WindowContext,
13363 ) -> Option<AnyElement> {
13364 let folded = self.is_line_folded(buffer_row);
13365
13366 if let Some(crease) = self
13367 .crease_snapshot
13368 .query_row(buffer_row, &self.buffer_snapshot)
13369 {
13370 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13371 if folded {
13372 editor.update(cx, |editor, cx| {
13373 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13374 });
13375 } else {
13376 editor.update(cx, |editor, cx| {
13377 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13378 });
13379 }
13380 });
13381
13382 Some((crease.render_toggle)(
13383 buffer_row,
13384 folded,
13385 toggle_callback,
13386 cx,
13387 ))
13388 } else if folded
13389 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13390 {
13391 Some(
13392 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13393 .selected(folded)
13394 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13395 if folded {
13396 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13397 } else {
13398 this.fold_at(&FoldAt { buffer_row }, cx);
13399 }
13400 }))
13401 .into_any_element(),
13402 )
13403 } else {
13404 None
13405 }
13406 }
13407
13408 pub fn render_crease_trailer(
13409 &self,
13410 buffer_row: MultiBufferRow,
13411 cx: &mut WindowContext,
13412 ) -> Option<AnyElement> {
13413 let folded = self.is_line_folded(buffer_row);
13414 let crease = self
13415 .crease_snapshot
13416 .query_row(buffer_row, &self.buffer_snapshot)?;
13417 Some((crease.render_trailer)(buffer_row, folded, cx))
13418 }
13419}
13420
13421impl Deref for EditorSnapshot {
13422 type Target = DisplaySnapshot;
13423
13424 fn deref(&self) -> &Self::Target {
13425 &self.display_snapshot
13426 }
13427}
13428
13429#[derive(Clone, Debug, PartialEq, Eq)]
13430pub enum EditorEvent {
13431 InputIgnored {
13432 text: Arc<str>,
13433 },
13434 InputHandled {
13435 utf16_range_to_replace: Option<Range<isize>>,
13436 text: Arc<str>,
13437 },
13438 ExcerptsAdded {
13439 buffer: Model<Buffer>,
13440 predecessor: ExcerptId,
13441 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13442 },
13443 ExcerptsRemoved {
13444 ids: Vec<ExcerptId>,
13445 },
13446 ExcerptsEdited {
13447 ids: Vec<ExcerptId>,
13448 },
13449 ExcerptsExpanded {
13450 ids: Vec<ExcerptId>,
13451 },
13452 BufferEdited,
13453 Edited {
13454 transaction_id: clock::Lamport,
13455 },
13456 Reparsed(BufferId),
13457 Focused,
13458 FocusedIn,
13459 Blurred,
13460 DirtyChanged,
13461 Saved,
13462 TitleChanged,
13463 DiffBaseChanged,
13464 SelectionsChanged {
13465 local: bool,
13466 },
13467 ScrollPositionChanged {
13468 local: bool,
13469 autoscroll: bool,
13470 },
13471 Closed,
13472 TransactionUndone {
13473 transaction_id: clock::Lamport,
13474 },
13475 TransactionBegun {
13476 transaction_id: clock::Lamport,
13477 },
13478 CursorShapeChanged,
13479}
13480
13481impl EventEmitter<EditorEvent> for Editor {}
13482
13483impl FocusableView for Editor {
13484 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13485 self.focus_handle.clone()
13486 }
13487}
13488
13489impl Render for Editor {
13490 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13491 let settings = ThemeSettings::get_global(cx);
13492
13493 let text_style = match self.mode {
13494 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13495 color: cx.theme().colors().editor_foreground,
13496 font_family: settings.ui_font.family.clone(),
13497 font_features: settings.ui_font.features.clone(),
13498 font_fallbacks: settings.ui_font.fallbacks.clone(),
13499 font_size: rems(0.875).into(),
13500 font_weight: settings.ui_font.weight,
13501 line_height: relative(settings.buffer_line_height.value()),
13502 ..Default::default()
13503 },
13504 EditorMode::Full => TextStyle {
13505 color: cx.theme().colors().editor_foreground,
13506 font_family: settings.buffer_font.family.clone(),
13507 font_features: settings.buffer_font.features.clone(),
13508 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13509 font_size: settings.buffer_font_size(cx).into(),
13510 font_weight: settings.buffer_font.weight,
13511 line_height: relative(settings.buffer_line_height.value()),
13512 ..Default::default()
13513 },
13514 };
13515
13516 let background = match self.mode {
13517 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13518 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13519 EditorMode::Full => cx.theme().colors().editor_background,
13520 };
13521
13522 EditorElement::new(
13523 cx.view(),
13524 EditorStyle {
13525 background,
13526 local_player: cx.theme().players().local(),
13527 text: text_style,
13528 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13529 syntax: cx.theme().syntax().clone(),
13530 status: cx.theme().status().clone(),
13531 inlay_hints_style: make_inlay_hints_style(cx),
13532 suggestions_style: HighlightStyle {
13533 color: Some(cx.theme().status().predictive),
13534 ..HighlightStyle::default()
13535 },
13536 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13537 },
13538 )
13539 }
13540}
13541
13542impl ViewInputHandler for Editor {
13543 fn text_for_range(
13544 &mut self,
13545 range_utf16: Range<usize>,
13546 cx: &mut ViewContext<Self>,
13547 ) -> Option<String> {
13548 Some(
13549 self.buffer
13550 .read(cx)
13551 .read(cx)
13552 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13553 .collect(),
13554 )
13555 }
13556
13557 fn selected_text_range(
13558 &mut self,
13559 ignore_disabled_input: bool,
13560 cx: &mut ViewContext<Self>,
13561 ) -> Option<UTF16Selection> {
13562 // Prevent the IME menu from appearing when holding down an alphabetic key
13563 // while input is disabled.
13564 if !ignore_disabled_input && !self.input_enabled {
13565 return None;
13566 }
13567
13568 let selection = self.selections.newest::<OffsetUtf16>(cx);
13569 let range = selection.range();
13570
13571 Some(UTF16Selection {
13572 range: range.start.0..range.end.0,
13573 reversed: selection.reversed,
13574 })
13575 }
13576
13577 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13578 let snapshot = self.buffer.read(cx).read(cx);
13579 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13580 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13581 }
13582
13583 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13584 self.clear_highlights::<InputComposition>(cx);
13585 self.ime_transaction.take();
13586 }
13587
13588 fn replace_text_in_range(
13589 &mut self,
13590 range_utf16: Option<Range<usize>>,
13591 text: &str,
13592 cx: &mut ViewContext<Self>,
13593 ) {
13594 if !self.input_enabled {
13595 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13596 return;
13597 }
13598
13599 self.transact(cx, |this, cx| {
13600 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13601 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13602 Some(this.selection_replacement_ranges(range_utf16, cx))
13603 } else {
13604 this.marked_text_ranges(cx)
13605 };
13606
13607 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13608 let newest_selection_id = this.selections.newest_anchor().id;
13609 this.selections
13610 .all::<OffsetUtf16>(cx)
13611 .iter()
13612 .zip(ranges_to_replace.iter())
13613 .find_map(|(selection, range)| {
13614 if selection.id == newest_selection_id {
13615 Some(
13616 (range.start.0 as isize - selection.head().0 as isize)
13617 ..(range.end.0 as isize - selection.head().0 as isize),
13618 )
13619 } else {
13620 None
13621 }
13622 })
13623 });
13624
13625 cx.emit(EditorEvent::InputHandled {
13626 utf16_range_to_replace: range_to_replace,
13627 text: text.into(),
13628 });
13629
13630 if let Some(new_selected_ranges) = new_selected_ranges {
13631 this.change_selections(None, cx, |selections| {
13632 selections.select_ranges(new_selected_ranges)
13633 });
13634 this.backspace(&Default::default(), cx);
13635 }
13636
13637 this.handle_input(text, cx);
13638 });
13639
13640 if let Some(transaction) = self.ime_transaction {
13641 self.buffer.update(cx, |buffer, cx| {
13642 buffer.group_until_transaction(transaction, cx);
13643 });
13644 }
13645
13646 self.unmark_text(cx);
13647 }
13648
13649 fn replace_and_mark_text_in_range(
13650 &mut self,
13651 range_utf16: Option<Range<usize>>,
13652 text: &str,
13653 new_selected_range_utf16: Option<Range<usize>>,
13654 cx: &mut ViewContext<Self>,
13655 ) {
13656 if !self.input_enabled {
13657 return;
13658 }
13659
13660 let transaction = self.transact(cx, |this, cx| {
13661 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13662 let snapshot = this.buffer.read(cx).read(cx);
13663 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13664 for marked_range in &mut marked_ranges {
13665 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13666 marked_range.start.0 += relative_range_utf16.start;
13667 marked_range.start =
13668 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13669 marked_range.end =
13670 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13671 }
13672 }
13673 Some(marked_ranges)
13674 } else if let Some(range_utf16) = range_utf16 {
13675 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13676 Some(this.selection_replacement_ranges(range_utf16, cx))
13677 } else {
13678 None
13679 };
13680
13681 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13682 let newest_selection_id = this.selections.newest_anchor().id;
13683 this.selections
13684 .all::<OffsetUtf16>(cx)
13685 .iter()
13686 .zip(ranges_to_replace.iter())
13687 .find_map(|(selection, range)| {
13688 if selection.id == newest_selection_id {
13689 Some(
13690 (range.start.0 as isize - selection.head().0 as isize)
13691 ..(range.end.0 as isize - selection.head().0 as isize),
13692 )
13693 } else {
13694 None
13695 }
13696 })
13697 });
13698
13699 cx.emit(EditorEvent::InputHandled {
13700 utf16_range_to_replace: range_to_replace,
13701 text: text.into(),
13702 });
13703
13704 if let Some(ranges) = ranges_to_replace {
13705 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13706 }
13707
13708 let marked_ranges = {
13709 let snapshot = this.buffer.read(cx).read(cx);
13710 this.selections
13711 .disjoint_anchors()
13712 .iter()
13713 .map(|selection| {
13714 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13715 })
13716 .collect::<Vec<_>>()
13717 };
13718
13719 if text.is_empty() {
13720 this.unmark_text(cx);
13721 } else {
13722 this.highlight_text::<InputComposition>(
13723 marked_ranges.clone(),
13724 HighlightStyle {
13725 underline: Some(UnderlineStyle {
13726 thickness: px(1.),
13727 color: None,
13728 wavy: false,
13729 }),
13730 ..Default::default()
13731 },
13732 cx,
13733 );
13734 }
13735
13736 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13737 let use_autoclose = this.use_autoclose;
13738 let use_auto_surround = this.use_auto_surround;
13739 this.set_use_autoclose(false);
13740 this.set_use_auto_surround(false);
13741 this.handle_input(text, cx);
13742 this.set_use_autoclose(use_autoclose);
13743 this.set_use_auto_surround(use_auto_surround);
13744
13745 if let Some(new_selected_range) = new_selected_range_utf16 {
13746 let snapshot = this.buffer.read(cx).read(cx);
13747 let new_selected_ranges = marked_ranges
13748 .into_iter()
13749 .map(|marked_range| {
13750 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13751 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13752 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13753 snapshot.clip_offset_utf16(new_start, Bias::Left)
13754 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13755 })
13756 .collect::<Vec<_>>();
13757
13758 drop(snapshot);
13759 this.change_selections(None, cx, |selections| {
13760 selections.select_ranges(new_selected_ranges)
13761 });
13762 }
13763 });
13764
13765 self.ime_transaction = self.ime_transaction.or(transaction);
13766 if let Some(transaction) = self.ime_transaction {
13767 self.buffer.update(cx, |buffer, cx| {
13768 buffer.group_until_transaction(transaction, cx);
13769 });
13770 }
13771
13772 if self.text_highlights::<InputComposition>(cx).is_none() {
13773 self.ime_transaction.take();
13774 }
13775 }
13776
13777 fn bounds_for_range(
13778 &mut self,
13779 range_utf16: Range<usize>,
13780 element_bounds: gpui::Bounds<Pixels>,
13781 cx: &mut ViewContext<Self>,
13782 ) -> Option<gpui::Bounds<Pixels>> {
13783 let text_layout_details = self.text_layout_details(cx);
13784 let style = &text_layout_details.editor_style;
13785 let font_id = cx.text_system().resolve_font(&style.text.font());
13786 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13787 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13788
13789 let em_width = cx
13790 .text_system()
13791 .typographic_bounds(font_id, font_size, 'm')
13792 .unwrap()
13793 .size
13794 .width;
13795
13796 let snapshot = self.snapshot(cx);
13797 let scroll_position = snapshot.scroll_position();
13798 let scroll_left = scroll_position.x * em_width;
13799
13800 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13801 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13802 + self.gutter_dimensions.width;
13803 let y = line_height * (start.row().as_f32() - scroll_position.y);
13804
13805 Some(Bounds {
13806 origin: element_bounds.origin + point(x, y),
13807 size: size(em_width, line_height),
13808 })
13809 }
13810}
13811
13812trait SelectionExt {
13813 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13814 fn spanned_rows(
13815 &self,
13816 include_end_if_at_line_start: bool,
13817 map: &DisplaySnapshot,
13818 ) -> Range<MultiBufferRow>;
13819}
13820
13821impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13822 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13823 let start = self
13824 .start
13825 .to_point(&map.buffer_snapshot)
13826 .to_display_point(map);
13827 let end = self
13828 .end
13829 .to_point(&map.buffer_snapshot)
13830 .to_display_point(map);
13831 if self.reversed {
13832 end..start
13833 } else {
13834 start..end
13835 }
13836 }
13837
13838 fn spanned_rows(
13839 &self,
13840 include_end_if_at_line_start: bool,
13841 map: &DisplaySnapshot,
13842 ) -> Range<MultiBufferRow> {
13843 let start = self.start.to_point(&map.buffer_snapshot);
13844 let mut end = self.end.to_point(&map.buffer_snapshot);
13845 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13846 end.row -= 1;
13847 }
13848
13849 let buffer_start = map.prev_line_boundary(start).0;
13850 let buffer_end = map.next_line_boundary(end).0;
13851 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13852 }
13853}
13854
13855impl<T: InvalidationRegion> InvalidationStack<T> {
13856 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13857 where
13858 S: Clone + ToOffset,
13859 {
13860 while let Some(region) = self.last() {
13861 let all_selections_inside_invalidation_ranges =
13862 if selections.len() == region.ranges().len() {
13863 selections
13864 .iter()
13865 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13866 .all(|(selection, invalidation_range)| {
13867 let head = selection.head().to_offset(buffer);
13868 invalidation_range.start <= head && invalidation_range.end >= head
13869 })
13870 } else {
13871 false
13872 };
13873
13874 if all_selections_inside_invalidation_ranges {
13875 break;
13876 } else {
13877 self.pop();
13878 }
13879 }
13880 }
13881}
13882
13883impl<T> Default for InvalidationStack<T> {
13884 fn default() -> Self {
13885 Self(Default::default())
13886 }
13887}
13888
13889impl<T> Deref for InvalidationStack<T> {
13890 type Target = Vec<T>;
13891
13892 fn deref(&self) -> &Self::Target {
13893 &self.0
13894 }
13895}
13896
13897impl<T> DerefMut for InvalidationStack<T> {
13898 fn deref_mut(&mut self) -> &mut Self::Target {
13899 &mut self.0
13900 }
13901}
13902
13903impl InvalidationRegion for SnippetState {
13904 fn ranges(&self) -> &[Range<Anchor>] {
13905 &self.ranges[self.active_index]
13906 }
13907}
13908
13909pub fn diagnostic_block_renderer(
13910 diagnostic: Diagnostic,
13911 max_message_rows: Option<u8>,
13912 allow_closing: bool,
13913 _is_valid: bool,
13914) -> RenderBlock {
13915 let (text_without_backticks, code_ranges) =
13916 highlight_diagnostic_message(&diagnostic, max_message_rows);
13917
13918 Box::new(move |cx: &mut BlockContext| {
13919 let group_id: SharedString = cx.block_id.to_string().into();
13920
13921 let mut text_style = cx.text_style().clone();
13922 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13923 let theme_settings = ThemeSettings::get_global(cx);
13924 text_style.font_family = theme_settings.buffer_font.family.clone();
13925 text_style.font_style = theme_settings.buffer_font.style;
13926 text_style.font_features = theme_settings.buffer_font.features.clone();
13927 text_style.font_weight = theme_settings.buffer_font.weight;
13928
13929 let multi_line_diagnostic = diagnostic.message.contains('\n');
13930
13931 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13932 if multi_line_diagnostic {
13933 v_flex()
13934 } else {
13935 h_flex()
13936 }
13937 .when(allow_closing, |div| {
13938 div.children(diagnostic.is_primary.then(|| {
13939 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13940 .icon_color(Color::Muted)
13941 .size(ButtonSize::Compact)
13942 .style(ButtonStyle::Transparent)
13943 .visible_on_hover(group_id.clone())
13944 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13945 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13946 }))
13947 })
13948 .child(
13949 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13950 .icon_color(Color::Muted)
13951 .size(ButtonSize::Compact)
13952 .style(ButtonStyle::Transparent)
13953 .visible_on_hover(group_id.clone())
13954 .on_click({
13955 let message = diagnostic.message.clone();
13956 move |_click, cx| {
13957 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13958 }
13959 })
13960 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13961 )
13962 };
13963
13964 let icon_size = buttons(&diagnostic, cx.block_id)
13965 .into_any_element()
13966 .layout_as_root(AvailableSpace::min_size(), cx);
13967
13968 h_flex()
13969 .id(cx.block_id)
13970 .group(group_id.clone())
13971 .relative()
13972 .size_full()
13973 .pl(cx.gutter_dimensions.width)
13974 .w(cx.max_width + cx.gutter_dimensions.width)
13975 .child(
13976 div()
13977 .flex()
13978 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13979 .flex_shrink(),
13980 )
13981 .child(buttons(&diagnostic, cx.block_id))
13982 .child(div().flex().flex_shrink_0().child(
13983 StyledText::new(text_without_backticks.clone()).with_highlights(
13984 &text_style,
13985 code_ranges.iter().map(|range| {
13986 (
13987 range.clone(),
13988 HighlightStyle {
13989 font_weight: Some(FontWeight::BOLD),
13990 ..Default::default()
13991 },
13992 )
13993 }),
13994 ),
13995 ))
13996 .into_any_element()
13997 })
13998}
13999
14000pub fn highlight_diagnostic_message(
14001 diagnostic: &Diagnostic,
14002 mut max_message_rows: Option<u8>,
14003) -> (SharedString, Vec<Range<usize>>) {
14004 let mut text_without_backticks = String::new();
14005 let mut code_ranges = Vec::new();
14006
14007 if let Some(source) = &diagnostic.source {
14008 text_without_backticks.push_str(source);
14009 code_ranges.push(0..source.len());
14010 text_without_backticks.push_str(": ");
14011 }
14012
14013 let mut prev_offset = 0;
14014 let mut in_code_block = false;
14015 let has_row_limit = max_message_rows.is_some();
14016 let mut newline_indices = diagnostic
14017 .message
14018 .match_indices('\n')
14019 .filter(|_| has_row_limit)
14020 .map(|(ix, _)| ix)
14021 .fuse()
14022 .peekable();
14023
14024 for (quote_ix, _) in diagnostic
14025 .message
14026 .match_indices('`')
14027 .chain([(diagnostic.message.len(), "")])
14028 {
14029 let mut first_newline_ix = None;
14030 let mut last_newline_ix = None;
14031 while let Some(newline_ix) = newline_indices.peek() {
14032 if *newline_ix < quote_ix {
14033 if first_newline_ix.is_none() {
14034 first_newline_ix = Some(*newline_ix);
14035 }
14036 last_newline_ix = Some(*newline_ix);
14037
14038 if let Some(rows_left) = &mut max_message_rows {
14039 if *rows_left == 0 {
14040 break;
14041 } else {
14042 *rows_left -= 1;
14043 }
14044 }
14045 let _ = newline_indices.next();
14046 } else {
14047 break;
14048 }
14049 }
14050 let prev_len = text_without_backticks.len();
14051 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14052 text_without_backticks.push_str(new_text);
14053 if in_code_block {
14054 code_ranges.push(prev_len..text_without_backticks.len());
14055 }
14056 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14057 in_code_block = !in_code_block;
14058 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14059 text_without_backticks.push_str("...");
14060 break;
14061 }
14062 }
14063
14064 (text_without_backticks.into(), code_ranges)
14065}
14066
14067fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14068 match severity {
14069 DiagnosticSeverity::ERROR => colors.error,
14070 DiagnosticSeverity::WARNING => colors.warning,
14071 DiagnosticSeverity::INFORMATION => colors.info,
14072 DiagnosticSeverity::HINT => colors.info,
14073 _ => colors.ignored,
14074 }
14075}
14076
14077pub fn styled_runs_for_code_label<'a>(
14078 label: &'a CodeLabel,
14079 syntax_theme: &'a theme::SyntaxTheme,
14080) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14081 let fade_out = HighlightStyle {
14082 fade_out: Some(0.35),
14083 ..Default::default()
14084 };
14085
14086 let mut prev_end = label.filter_range.end;
14087 label
14088 .runs
14089 .iter()
14090 .enumerate()
14091 .flat_map(move |(ix, (range, highlight_id))| {
14092 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14093 style
14094 } else {
14095 return Default::default();
14096 };
14097 let mut muted_style = style;
14098 muted_style.highlight(fade_out);
14099
14100 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14101 if range.start >= label.filter_range.end {
14102 if range.start > prev_end {
14103 runs.push((prev_end..range.start, fade_out));
14104 }
14105 runs.push((range.clone(), muted_style));
14106 } else if range.end <= label.filter_range.end {
14107 runs.push((range.clone(), style));
14108 } else {
14109 runs.push((range.start..label.filter_range.end, style));
14110 runs.push((label.filter_range.end..range.end, muted_style));
14111 }
14112 prev_end = cmp::max(prev_end, range.end);
14113
14114 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14115 runs.push((prev_end..label.text.len(), fade_out));
14116 }
14117
14118 runs
14119 })
14120}
14121
14122pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14123 let mut prev_index = 0;
14124 let mut prev_codepoint: Option<char> = None;
14125 text.char_indices()
14126 .chain([(text.len(), '\0')])
14127 .filter_map(move |(index, codepoint)| {
14128 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14129 let is_boundary = index == text.len()
14130 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14131 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14132 if is_boundary {
14133 let chunk = &text[prev_index..index];
14134 prev_index = index;
14135 Some(chunk)
14136 } else {
14137 None
14138 }
14139 })
14140}
14141
14142pub trait RangeToAnchorExt: Sized {
14143 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14144
14145 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14146 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14147 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14148 }
14149}
14150
14151impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14152 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14153 let start_offset = self.start.to_offset(snapshot);
14154 let end_offset = self.end.to_offset(snapshot);
14155 if start_offset == end_offset {
14156 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14157 } else {
14158 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14159 }
14160 }
14161}
14162
14163pub trait RowExt {
14164 fn as_f32(&self) -> f32;
14165
14166 fn next_row(&self) -> Self;
14167
14168 fn previous_row(&self) -> Self;
14169
14170 fn minus(&self, other: Self) -> u32;
14171}
14172
14173impl RowExt for DisplayRow {
14174 fn as_f32(&self) -> f32 {
14175 self.0 as f32
14176 }
14177
14178 fn next_row(&self) -> Self {
14179 Self(self.0 + 1)
14180 }
14181
14182 fn previous_row(&self) -> Self {
14183 Self(self.0.saturating_sub(1))
14184 }
14185
14186 fn minus(&self, other: Self) -> u32 {
14187 self.0 - other.0
14188 }
14189}
14190
14191impl RowExt for MultiBufferRow {
14192 fn as_f32(&self) -> f32 {
14193 self.0 as f32
14194 }
14195
14196 fn next_row(&self) -> Self {
14197 Self(self.0 + 1)
14198 }
14199
14200 fn previous_row(&self) -> Self {
14201 Self(self.0.saturating_sub(1))
14202 }
14203
14204 fn minus(&self, other: Self) -> u32 {
14205 self.0 - other.0
14206 }
14207}
14208
14209trait RowRangeExt {
14210 type Row;
14211
14212 fn len(&self) -> usize;
14213
14214 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14215}
14216
14217impl RowRangeExt for Range<MultiBufferRow> {
14218 type Row = MultiBufferRow;
14219
14220 fn len(&self) -> usize {
14221 (self.end.0 - self.start.0) as usize
14222 }
14223
14224 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14225 (self.start.0..self.end.0).map(MultiBufferRow)
14226 }
14227}
14228
14229impl RowRangeExt for Range<DisplayRow> {
14230 type Row = DisplayRow;
14231
14232 fn len(&self) -> usize {
14233 (self.end.0 - self.start.0) as usize
14234 }
14235
14236 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14237 (self.start.0..self.end.0).map(DisplayRow)
14238 }
14239}
14240
14241fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14242 if hunk.diff_base_byte_range.is_empty() {
14243 DiffHunkStatus::Added
14244 } else if hunk.row_range.is_empty() {
14245 DiffHunkStatus::Removed
14246 } else {
14247 DiffHunkStatus::Modified
14248 }
14249}
14250
14251/// If select range has more than one line, we
14252/// just point the cursor to range.start.
14253fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14254 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14255 range
14256 } else {
14257 range.start..range.start
14258 }
14259}