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 div().min_w(px(220.)).max_w(px(540.)).child(
1232 ListItem::new(mat.candidate_id)
1233 .inset(true)
1234 .selected(item_ix == selected_item)
1235 .on_click(cx.listener(move |editor, _event, cx| {
1236 cx.stop_propagation();
1237 if let Some(task) = editor.confirm_completion(
1238 &ConfirmCompletion {
1239 item_ix: Some(item_ix),
1240 },
1241 cx,
1242 ) {
1243 task.detach_and_log_err(cx)
1244 }
1245 }))
1246 .child(h_flex().overflow_hidden().child(completion_label))
1247 .end_slot::<Label>(documentation_label),
1248 )
1249 })
1250 .collect()
1251 },
1252 )
1253 .occlude()
1254 .max_h(max_height)
1255 .track_scroll(self.scroll_handle.clone())
1256 .with_width_from_item(widest_completion_ix)
1257 .with_sizing_behavior(ListSizingBehavior::Infer);
1258
1259 Popover::new()
1260 .child(list)
1261 .when_some(multiline_docs, |popover, multiline_docs| {
1262 popover.aside(multiline_docs)
1263 })
1264 .into_any_element()
1265 }
1266
1267 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1268 let mut matches = if let Some(query) = query {
1269 fuzzy::match_strings(
1270 &self.match_candidates,
1271 query,
1272 query.chars().any(|c| c.is_uppercase()),
1273 100,
1274 &Default::default(),
1275 executor,
1276 )
1277 .await
1278 } else {
1279 self.match_candidates
1280 .iter()
1281 .enumerate()
1282 .map(|(candidate_id, candidate)| StringMatch {
1283 candidate_id,
1284 score: Default::default(),
1285 positions: Default::default(),
1286 string: candidate.string.clone(),
1287 })
1288 .collect()
1289 };
1290
1291 // Remove all candidates where the query's start does not match the start of any word in the candidate
1292 if let Some(query) = query {
1293 if let Some(query_start) = query.chars().next() {
1294 matches.retain(|string_match| {
1295 split_words(&string_match.string).any(|word| {
1296 // Check that the first codepoint of the word as lowercase matches the first
1297 // codepoint of the query as lowercase
1298 word.chars()
1299 .flat_map(|codepoint| codepoint.to_lowercase())
1300 .zip(query_start.to_lowercase())
1301 .all(|(word_cp, query_cp)| word_cp == query_cp)
1302 })
1303 });
1304 }
1305 }
1306
1307 let completions = self.completions.read();
1308 if self.sort_completions {
1309 matches.sort_unstable_by_key(|mat| {
1310 // We do want to strike a balance here between what the language server tells us
1311 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1312 // `Creat` and there is a local variable called `CreateComponent`).
1313 // So what we do is: we bucket all matches into two buckets
1314 // - Strong matches
1315 // - Weak matches
1316 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1317 // and the Weak matches are the rest.
1318 //
1319 // For the strong matches, we sort by the language-servers score first and for the weak
1320 // matches, we prefer our fuzzy finder first.
1321 //
1322 // The thinking behind that: it's useless to take the sort_text the language-server gives
1323 // us into account when it's obviously a bad match.
1324
1325 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1326 enum MatchScore<'a> {
1327 Strong {
1328 sort_text: Option<&'a str>,
1329 score: Reverse<OrderedFloat<f64>>,
1330 sort_key: (usize, &'a str),
1331 },
1332 Weak {
1333 score: Reverse<OrderedFloat<f64>>,
1334 sort_text: Option<&'a str>,
1335 sort_key: (usize, &'a str),
1336 },
1337 }
1338
1339 let completion = &completions[mat.candidate_id];
1340 let sort_key = completion.sort_key();
1341 let sort_text = completion.lsp_completion.sort_text.as_deref();
1342 let score = Reverse(OrderedFloat(mat.score));
1343
1344 if mat.score >= 0.2 {
1345 MatchScore::Strong {
1346 sort_text,
1347 score,
1348 sort_key,
1349 }
1350 } else {
1351 MatchScore::Weak {
1352 score,
1353 sort_text,
1354 sort_key,
1355 }
1356 }
1357 });
1358 }
1359
1360 for mat in &mut matches {
1361 let completion = &completions[mat.candidate_id];
1362 mat.string.clone_from(&completion.label.text);
1363 for position in &mut mat.positions {
1364 *position += completion.label.filter_range.start;
1365 }
1366 }
1367 drop(completions);
1368
1369 self.matches = matches.into();
1370 self.selected_item = 0;
1371 }
1372}
1373
1374struct AvailableCodeAction {
1375 excerpt_id: ExcerptId,
1376 action: CodeAction,
1377 provider: Arc<dyn CodeActionProvider>,
1378}
1379
1380#[derive(Clone)]
1381struct CodeActionContents {
1382 tasks: Option<Arc<ResolvedTasks>>,
1383 actions: Option<Arc<[AvailableCodeAction]>>,
1384}
1385
1386impl CodeActionContents {
1387 fn len(&self) -> usize {
1388 match (&self.tasks, &self.actions) {
1389 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1390 (Some(tasks), None) => tasks.templates.len(),
1391 (None, Some(actions)) => actions.len(),
1392 (None, None) => 0,
1393 }
1394 }
1395
1396 fn is_empty(&self) -> bool {
1397 match (&self.tasks, &self.actions) {
1398 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1399 (Some(tasks), None) => tasks.templates.is_empty(),
1400 (None, Some(actions)) => actions.is_empty(),
1401 (None, None) => true,
1402 }
1403 }
1404
1405 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1406 self.tasks
1407 .iter()
1408 .flat_map(|tasks| {
1409 tasks
1410 .templates
1411 .iter()
1412 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1413 })
1414 .chain(self.actions.iter().flat_map(|actions| {
1415 actions.iter().map(|available| CodeActionsItem::CodeAction {
1416 excerpt_id: available.excerpt_id,
1417 action: available.action.clone(),
1418 provider: available.provider.clone(),
1419 })
1420 }))
1421 }
1422 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1423 match (&self.tasks, &self.actions) {
1424 (Some(tasks), Some(actions)) => {
1425 if index < tasks.templates.len() {
1426 tasks
1427 .templates
1428 .get(index)
1429 .cloned()
1430 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1431 } else {
1432 actions.get(index - tasks.templates.len()).map(|available| {
1433 CodeActionsItem::CodeAction {
1434 excerpt_id: available.excerpt_id,
1435 action: available.action.clone(),
1436 provider: available.provider.clone(),
1437 }
1438 })
1439 }
1440 }
1441 (Some(tasks), None) => tasks
1442 .templates
1443 .get(index)
1444 .cloned()
1445 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1446 (None, Some(actions)) => {
1447 actions
1448 .get(index)
1449 .map(|available| CodeActionsItem::CodeAction {
1450 excerpt_id: available.excerpt_id,
1451 action: available.action.clone(),
1452 provider: available.provider.clone(),
1453 })
1454 }
1455 (None, None) => None,
1456 }
1457 }
1458}
1459
1460#[allow(clippy::large_enum_variant)]
1461#[derive(Clone)]
1462enum CodeActionsItem {
1463 Task(TaskSourceKind, ResolvedTask),
1464 CodeAction {
1465 excerpt_id: ExcerptId,
1466 action: CodeAction,
1467 provider: Arc<dyn CodeActionProvider>,
1468 },
1469}
1470
1471impl CodeActionsItem {
1472 fn as_task(&self) -> Option<&ResolvedTask> {
1473 let Self::Task(_, task) = self else {
1474 return None;
1475 };
1476 Some(task)
1477 }
1478 fn as_code_action(&self) -> Option<&CodeAction> {
1479 let Self::CodeAction { action, .. } = self else {
1480 return None;
1481 };
1482 Some(action)
1483 }
1484 fn label(&self) -> String {
1485 match self {
1486 Self::CodeAction { action, .. } => action.lsp_action.title.clone(),
1487 Self::Task(_, task) => task.resolved_label.clone(),
1488 }
1489 }
1490}
1491
1492struct CodeActionsMenu {
1493 actions: CodeActionContents,
1494 buffer: Model<Buffer>,
1495 selected_item: usize,
1496 scroll_handle: UniformListScrollHandle,
1497 deployed_from_indicator: Option<DisplayRow>,
1498}
1499
1500impl CodeActionsMenu {
1501 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1502 self.selected_item = 0;
1503 self.scroll_handle.scroll_to_item(self.selected_item);
1504 cx.notify()
1505 }
1506
1507 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1508 if self.selected_item > 0 {
1509 self.selected_item -= 1;
1510 } else {
1511 self.selected_item = self.actions.len() - 1;
1512 }
1513 self.scroll_handle.scroll_to_item(self.selected_item);
1514 cx.notify();
1515 }
1516
1517 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1518 if self.selected_item + 1 < self.actions.len() {
1519 self.selected_item += 1;
1520 } else {
1521 self.selected_item = 0;
1522 }
1523 self.scroll_handle.scroll_to_item(self.selected_item);
1524 cx.notify();
1525 }
1526
1527 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1528 self.selected_item = self.actions.len() - 1;
1529 self.scroll_handle.scroll_to_item(self.selected_item);
1530 cx.notify()
1531 }
1532
1533 fn visible(&self) -> bool {
1534 !self.actions.is_empty()
1535 }
1536
1537 fn render(
1538 &self,
1539 cursor_position: DisplayPoint,
1540 _style: &EditorStyle,
1541 max_height: Pixels,
1542 cx: &mut ViewContext<Editor>,
1543 ) -> (ContextMenuOrigin, AnyElement) {
1544 let actions = self.actions.clone();
1545 let selected_item = self.selected_item;
1546 let element = uniform_list(
1547 cx.view().clone(),
1548 "code_actions_menu",
1549 self.actions.len(),
1550 move |_this, range, cx| {
1551 actions
1552 .iter()
1553 .skip(range.start)
1554 .take(range.end - range.start)
1555 .enumerate()
1556 .map(|(ix, action)| {
1557 let item_ix = range.start + ix;
1558 let selected = selected_item == item_ix;
1559 let colors = cx.theme().colors();
1560 div()
1561 .px_1()
1562 .rounded_md()
1563 .text_color(colors.text)
1564 .when(selected, |style| {
1565 style
1566 .bg(colors.element_active)
1567 .text_color(colors.text_accent)
1568 })
1569 .hover(|style| {
1570 style
1571 .bg(colors.element_hover)
1572 .text_color(colors.text_accent)
1573 })
1574 .whitespace_nowrap()
1575 .when_some(action.as_code_action(), |this, action| {
1576 this.on_mouse_down(
1577 MouseButton::Left,
1578 cx.listener(move |editor, _, cx| {
1579 cx.stop_propagation();
1580 if let Some(task) = editor.confirm_code_action(
1581 &ConfirmCodeAction {
1582 item_ix: Some(item_ix),
1583 },
1584 cx,
1585 ) {
1586 task.detach_and_log_err(cx)
1587 }
1588 }),
1589 )
1590 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1591 .child(SharedString::from(action.lsp_action.title.clone()))
1592 })
1593 .when_some(action.as_task(), |this, task| {
1594 this.on_mouse_down(
1595 MouseButton::Left,
1596 cx.listener(move |editor, _, cx| {
1597 cx.stop_propagation();
1598 if let Some(task) = editor.confirm_code_action(
1599 &ConfirmCodeAction {
1600 item_ix: Some(item_ix),
1601 },
1602 cx,
1603 ) {
1604 task.detach_and_log_err(cx)
1605 }
1606 }),
1607 )
1608 .child(SharedString::from(task.resolved_label.clone()))
1609 })
1610 })
1611 .collect()
1612 },
1613 )
1614 .elevation_1(cx)
1615 .p_1()
1616 .max_h(max_height)
1617 .occlude()
1618 .track_scroll(self.scroll_handle.clone())
1619 .with_width_from_item(
1620 self.actions
1621 .iter()
1622 .enumerate()
1623 .max_by_key(|(_, action)| match action {
1624 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1625 CodeActionsItem::CodeAction { action, .. } => {
1626 action.lsp_action.title.chars().count()
1627 }
1628 })
1629 .map(|(ix, _)| ix),
1630 )
1631 .with_sizing_behavior(ListSizingBehavior::Infer)
1632 .into_any_element();
1633
1634 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1635 ContextMenuOrigin::GutterIndicator(row)
1636 } else {
1637 ContextMenuOrigin::EditorPoint(cursor_position)
1638 };
1639
1640 (cursor_position, element)
1641 }
1642}
1643
1644#[derive(Debug)]
1645struct ActiveDiagnosticGroup {
1646 primary_range: Range<Anchor>,
1647 primary_message: String,
1648 group_id: usize,
1649 blocks: HashMap<CustomBlockId, Diagnostic>,
1650 is_valid: bool,
1651}
1652
1653#[derive(Serialize, Deserialize, Clone, Debug)]
1654pub struct ClipboardSelection {
1655 pub len: usize,
1656 pub is_entire_line: bool,
1657 pub first_line_indent: u32,
1658}
1659
1660#[derive(Debug)]
1661pub(crate) struct NavigationData {
1662 cursor_anchor: Anchor,
1663 cursor_position: Point,
1664 scroll_anchor: ScrollAnchor,
1665 scroll_top_row: u32,
1666}
1667
1668#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1669enum GotoDefinitionKind {
1670 Symbol,
1671 Declaration,
1672 Type,
1673 Implementation,
1674}
1675
1676#[derive(Debug, Clone)]
1677enum InlayHintRefreshReason {
1678 Toggle(bool),
1679 SettingsChange(InlayHintSettings),
1680 NewLinesShown,
1681 BufferEdited(HashSet<Arc<Language>>),
1682 RefreshRequested,
1683 ExcerptsRemoved(Vec<ExcerptId>),
1684}
1685
1686impl InlayHintRefreshReason {
1687 fn description(&self) -> &'static str {
1688 match self {
1689 Self::Toggle(_) => "toggle",
1690 Self::SettingsChange(_) => "settings change",
1691 Self::NewLinesShown => "new lines shown",
1692 Self::BufferEdited(_) => "buffer edited",
1693 Self::RefreshRequested => "refresh requested",
1694 Self::ExcerptsRemoved(_) => "excerpts removed",
1695 }
1696 }
1697}
1698
1699pub(crate) struct FocusedBlock {
1700 id: BlockId,
1701 focus_handle: WeakFocusHandle,
1702}
1703
1704impl Editor {
1705 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1706 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1707 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1708 Self::new(
1709 EditorMode::SingleLine { auto_width: false },
1710 buffer,
1711 None,
1712 false,
1713 cx,
1714 )
1715 }
1716
1717 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1718 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1719 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1720 Self::new(EditorMode::Full, buffer, None, false, cx)
1721 }
1722
1723 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1724 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1725 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1726 Self::new(
1727 EditorMode::SingleLine { auto_width: true },
1728 buffer,
1729 None,
1730 false,
1731 cx,
1732 )
1733 }
1734
1735 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1736 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1737 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1738 Self::new(
1739 EditorMode::AutoHeight { max_lines },
1740 buffer,
1741 None,
1742 false,
1743 cx,
1744 )
1745 }
1746
1747 pub fn for_buffer(
1748 buffer: Model<Buffer>,
1749 project: Option<Model<Project>>,
1750 cx: &mut ViewContext<Self>,
1751 ) -> Self {
1752 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1753 Self::new(EditorMode::Full, buffer, project, false, cx)
1754 }
1755
1756 pub fn for_multibuffer(
1757 buffer: Model<MultiBuffer>,
1758 project: Option<Model<Project>>,
1759 show_excerpt_controls: bool,
1760 cx: &mut ViewContext<Self>,
1761 ) -> Self {
1762 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1763 }
1764
1765 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1766 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1767 let mut clone = Self::new(
1768 self.mode,
1769 self.buffer.clone(),
1770 self.project.clone(),
1771 show_excerpt_controls,
1772 cx,
1773 );
1774 self.display_map.update(cx, |display_map, cx| {
1775 let snapshot = display_map.snapshot(cx);
1776 clone.display_map.update(cx, |display_map, cx| {
1777 display_map.set_state(&snapshot, cx);
1778 });
1779 });
1780 clone.selections.clone_state(&self.selections);
1781 clone.scroll_manager.clone_state(&self.scroll_manager);
1782 clone.searchable = self.searchable;
1783 clone
1784 }
1785
1786 pub fn new(
1787 mode: EditorMode,
1788 buffer: Model<MultiBuffer>,
1789 project: Option<Model<Project>>,
1790 show_excerpt_controls: bool,
1791 cx: &mut ViewContext<Self>,
1792 ) -> Self {
1793 let style = cx.text_style();
1794 let font_size = style.font_size.to_pixels(cx.rem_size());
1795 let editor = cx.view().downgrade();
1796 let fold_placeholder = FoldPlaceholder {
1797 constrain_width: true,
1798 render: Arc::new(move |fold_id, fold_range, cx| {
1799 let editor = editor.clone();
1800 div()
1801 .id(fold_id)
1802 .bg(cx.theme().colors().ghost_element_background)
1803 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1804 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1805 .rounded_sm()
1806 .size_full()
1807 .cursor_pointer()
1808 .child("⋯")
1809 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1810 .on_click(move |_, cx| {
1811 editor
1812 .update(cx, |editor, cx| {
1813 editor.unfold_ranges(
1814 [fold_range.start..fold_range.end],
1815 true,
1816 false,
1817 cx,
1818 );
1819 cx.stop_propagation();
1820 })
1821 .ok();
1822 })
1823 .into_any()
1824 }),
1825 merge_adjacent: true,
1826 };
1827 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1828 let display_map = cx.new_model(|cx| {
1829 DisplayMap::new(
1830 buffer.clone(),
1831 style.font(),
1832 font_size,
1833 None,
1834 show_excerpt_controls,
1835 file_header_size,
1836 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1837 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1838 fold_placeholder,
1839 cx,
1840 )
1841 });
1842
1843 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1844
1845 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1846
1847 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1848 .then(|| language_settings::SoftWrap::None);
1849
1850 let mut project_subscriptions = Vec::new();
1851 if mode == EditorMode::Full {
1852 if let Some(project) = project.as_ref() {
1853 if buffer.read(cx).is_singleton() {
1854 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1855 cx.emit(EditorEvent::TitleChanged);
1856 }));
1857 }
1858 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1859 if let project::Event::RefreshInlayHints = event {
1860 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1861 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1862 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1863 let focus_handle = editor.focus_handle(cx);
1864 if focus_handle.is_focused(cx) {
1865 let snapshot = buffer.read(cx).snapshot();
1866 for (range, snippet) in snippet_edits {
1867 let editor_range =
1868 language::range_from_lsp(*range).to_offset(&snapshot);
1869 editor
1870 .insert_snippet(&[editor_range], snippet.clone(), cx)
1871 .ok();
1872 }
1873 }
1874 }
1875 }
1876 }));
1877 let task_inventory = project.read(cx).task_inventory().clone();
1878 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1879 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1880 }));
1881 }
1882 }
1883
1884 let inlay_hint_settings = inlay_hint_settings(
1885 selections.newest_anchor().head(),
1886 &buffer.read(cx).snapshot(cx),
1887 cx,
1888 );
1889 let focus_handle = cx.focus_handle();
1890 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1891 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1892 .detach();
1893 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1894 .detach();
1895 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1896
1897 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1898 Some(false)
1899 } else {
1900 None
1901 };
1902
1903 let mut code_action_providers = Vec::new();
1904 if let Some(project) = project.clone() {
1905 code_action_providers.push(Arc::new(project) as Arc<_>);
1906 }
1907
1908 let mut this = Self {
1909 focus_handle,
1910 show_cursor_when_unfocused: false,
1911 last_focused_descendant: None,
1912 buffer: buffer.clone(),
1913 display_map: display_map.clone(),
1914 selections,
1915 scroll_manager: ScrollManager::new(cx),
1916 columnar_selection_tail: None,
1917 add_selections_state: None,
1918 select_next_state: None,
1919 select_prev_state: None,
1920 selection_history: Default::default(),
1921 autoclose_regions: Default::default(),
1922 snippet_stack: Default::default(),
1923 select_larger_syntax_node_stack: Vec::new(),
1924 ime_transaction: Default::default(),
1925 active_diagnostics: None,
1926 soft_wrap_mode_override,
1927 completion_provider: project.clone().map(|project| Box::new(project) as _),
1928 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1929 project,
1930 blink_manager: blink_manager.clone(),
1931 show_local_selections: true,
1932 mode,
1933 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1934 show_gutter: mode == EditorMode::Full,
1935 show_line_numbers: None,
1936 use_relative_line_numbers: None,
1937 show_git_diff_gutter: None,
1938 show_code_actions: None,
1939 show_runnables: None,
1940 show_wrap_guides: None,
1941 show_indent_guides,
1942 placeholder_text: None,
1943 highlight_order: 0,
1944 highlighted_rows: HashMap::default(),
1945 background_highlights: Default::default(),
1946 gutter_highlights: TreeMap::default(),
1947 scrollbar_marker_state: ScrollbarMarkerState::default(),
1948 active_indent_guides_state: ActiveIndentGuidesState::default(),
1949 nav_history: None,
1950 context_menu: RwLock::new(None),
1951 mouse_context_menu: None,
1952 hunk_controls_menu_handle: PopoverMenuHandle::default(),
1953 completion_tasks: Default::default(),
1954 signature_help_state: SignatureHelpState::default(),
1955 auto_signature_help: None,
1956 find_all_references_task_sources: Vec::new(),
1957 next_completion_id: 0,
1958 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1959 next_inlay_id: 0,
1960 code_action_providers,
1961 available_code_actions: Default::default(),
1962 code_actions_task: Default::default(),
1963 document_highlights_task: Default::default(),
1964 linked_editing_range_task: Default::default(),
1965 pending_rename: Default::default(),
1966 searchable: true,
1967 cursor_shape: EditorSettings::get_global(cx)
1968 .cursor_shape
1969 .unwrap_or_default(),
1970 current_line_highlight: None,
1971 autoindent_mode: Some(AutoindentMode::EachLine),
1972 collapse_matches: false,
1973 workspace: None,
1974 input_enabled: true,
1975 use_modal_editing: mode == EditorMode::Full,
1976 read_only: false,
1977 use_autoclose: true,
1978 use_auto_surround: true,
1979 auto_replace_emoji_shortcode: false,
1980 leader_peer_id: None,
1981 remote_id: None,
1982 hover_state: Default::default(),
1983 hovered_link_state: Default::default(),
1984 inline_completion_provider: None,
1985 active_inline_completion: None,
1986 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1987 expanded_hunks: ExpandedHunks::default(),
1988 gutter_hovered: false,
1989 pixel_position_of_newest_cursor: None,
1990 last_bounds: None,
1991 expect_bounds_change: None,
1992 gutter_dimensions: GutterDimensions::default(),
1993 style: None,
1994 show_cursor_names: false,
1995 hovered_cursors: Default::default(),
1996 next_editor_action_id: EditorActionId::default(),
1997 editor_actions: Rc::default(),
1998 show_inline_completions_override: None,
1999 enable_inline_completions: true,
2000 custom_context_menu: None,
2001 show_git_blame_gutter: false,
2002 show_git_blame_inline: false,
2003 show_selection_menu: None,
2004 show_git_blame_inline_delay_task: None,
2005 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
2006 serialize_dirty_buffers: ProjectSettings::get_global(cx)
2007 .session
2008 .restore_unsaved_buffers,
2009 blame: None,
2010 blame_subscription: None,
2011 file_header_size,
2012 tasks: Default::default(),
2013 _subscriptions: vec![
2014 cx.observe(&buffer, Self::on_buffer_changed),
2015 cx.subscribe(&buffer, Self::on_buffer_event),
2016 cx.observe(&display_map, Self::on_display_map_changed),
2017 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
2018 cx.observe_global::<SettingsStore>(Self::settings_changed),
2019 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
2020 cx.observe_window_activation(|editor, cx| {
2021 let active = cx.is_window_active();
2022 editor.blink_manager.update(cx, |blink_manager, cx| {
2023 if active {
2024 blink_manager.enable(cx);
2025 } else {
2026 blink_manager.disable(cx);
2027 }
2028 });
2029 }),
2030 ],
2031 tasks_update_task: None,
2032 linked_edit_ranges: Default::default(),
2033 previous_search_ranges: None,
2034 breadcrumb_header: None,
2035 focused_block: None,
2036 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
2037 addons: HashMap::default(),
2038 _scroll_cursor_center_top_bottom_task: Task::ready(()),
2039 };
2040 this.tasks_update_task = Some(this.refresh_runnables(cx));
2041 this._subscriptions.extend(project_subscriptions);
2042
2043 this.end_selection(cx);
2044 this.scroll_manager.show_scrollbar(cx);
2045
2046 if mode == EditorMode::Full {
2047 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2048 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2049
2050 if this.git_blame_inline_enabled {
2051 this.git_blame_inline_enabled = true;
2052 this.start_git_blame_inline(false, cx);
2053 }
2054 }
2055
2056 this.report_editor_event("open", None, cx);
2057 this
2058 }
2059
2060 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2061 self.mouse_context_menu
2062 .as_ref()
2063 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2064 }
2065
2066 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2067 let mut key_context = KeyContext::new_with_defaults();
2068 key_context.add("Editor");
2069 let mode = match self.mode {
2070 EditorMode::SingleLine { .. } => "single_line",
2071 EditorMode::AutoHeight { .. } => "auto_height",
2072 EditorMode::Full => "full",
2073 };
2074
2075 if EditorSettings::jupyter_enabled(cx) {
2076 key_context.add("jupyter");
2077 }
2078
2079 key_context.set("mode", mode);
2080 if self.pending_rename.is_some() {
2081 key_context.add("renaming");
2082 }
2083 if self.context_menu_visible() {
2084 match self.context_menu.read().as_ref() {
2085 Some(ContextMenu::Completions(_)) => {
2086 key_context.add("menu");
2087 key_context.add("showing_completions")
2088 }
2089 Some(ContextMenu::CodeActions(_)) => {
2090 key_context.add("menu");
2091 key_context.add("showing_code_actions")
2092 }
2093 None => {}
2094 }
2095 }
2096
2097 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2098 if !self.focus_handle(cx).contains_focused(cx)
2099 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2100 {
2101 for addon in self.addons.values() {
2102 addon.extend_key_context(&mut key_context, cx)
2103 }
2104 }
2105
2106 if let Some(extension) = self
2107 .buffer
2108 .read(cx)
2109 .as_singleton()
2110 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2111 {
2112 key_context.set("extension", extension.to_string());
2113 }
2114
2115 if self.has_active_inline_completion(cx) {
2116 key_context.add("copilot_suggestion");
2117 key_context.add("inline_completion");
2118 }
2119
2120 key_context
2121 }
2122
2123 pub fn new_file(
2124 workspace: &mut Workspace,
2125 _: &workspace::NewFile,
2126 cx: &mut ViewContext<Workspace>,
2127 ) {
2128 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2129 "Failed to create buffer",
2130 cx,
2131 |e, _| match e.error_code() {
2132 ErrorCode::RemoteUpgradeRequired => Some(format!(
2133 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2134 e.error_tag("required").unwrap_or("the latest version")
2135 )),
2136 _ => None,
2137 },
2138 );
2139 }
2140
2141 pub fn new_in_workspace(
2142 workspace: &mut Workspace,
2143 cx: &mut ViewContext<Workspace>,
2144 ) -> Task<Result<View<Editor>>> {
2145 let project = workspace.project().clone();
2146 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2147
2148 cx.spawn(|workspace, mut cx| async move {
2149 let buffer = create.await?;
2150 workspace.update(&mut cx, |workspace, cx| {
2151 let editor =
2152 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2153 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2154 editor
2155 })
2156 })
2157 }
2158
2159 fn new_file_vertical(
2160 workspace: &mut Workspace,
2161 _: &workspace::NewFileSplitVertical,
2162 cx: &mut ViewContext<Workspace>,
2163 ) {
2164 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2165 }
2166
2167 fn new_file_horizontal(
2168 workspace: &mut Workspace,
2169 _: &workspace::NewFileSplitHorizontal,
2170 cx: &mut ViewContext<Workspace>,
2171 ) {
2172 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2173 }
2174
2175 fn new_file_in_direction(
2176 workspace: &mut Workspace,
2177 direction: SplitDirection,
2178 cx: &mut ViewContext<Workspace>,
2179 ) {
2180 let project = workspace.project().clone();
2181 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2182
2183 cx.spawn(|workspace, mut cx| async move {
2184 let buffer = create.await?;
2185 workspace.update(&mut cx, move |workspace, cx| {
2186 workspace.split_item(
2187 direction,
2188 Box::new(
2189 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2190 ),
2191 cx,
2192 )
2193 })?;
2194 anyhow::Ok(())
2195 })
2196 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2197 ErrorCode::RemoteUpgradeRequired => Some(format!(
2198 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2199 e.error_tag("required").unwrap_or("the latest version")
2200 )),
2201 _ => None,
2202 });
2203 }
2204
2205 pub fn leader_peer_id(&self) -> Option<PeerId> {
2206 self.leader_peer_id
2207 }
2208
2209 pub fn buffer(&self) -> &Model<MultiBuffer> {
2210 &self.buffer
2211 }
2212
2213 pub fn workspace(&self) -> Option<View<Workspace>> {
2214 self.workspace.as_ref()?.0.upgrade()
2215 }
2216
2217 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2218 self.buffer().read(cx).title(cx)
2219 }
2220
2221 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2222 let git_blame_gutter_max_author_length = self
2223 .render_git_blame_gutter(cx)
2224 .then(|| {
2225 if let Some(blame) = self.blame.as_ref() {
2226 let max_author_length =
2227 blame.update(cx, |blame, cx| blame.max_author_length(cx));
2228 Some(max_author_length)
2229 } else {
2230 None
2231 }
2232 })
2233 .flatten();
2234
2235 EditorSnapshot {
2236 mode: self.mode,
2237 show_gutter: self.show_gutter,
2238 show_line_numbers: self.show_line_numbers,
2239 show_git_diff_gutter: self.show_git_diff_gutter,
2240 show_code_actions: self.show_code_actions,
2241 show_runnables: self.show_runnables,
2242 git_blame_gutter_max_author_length,
2243 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2244 scroll_anchor: self.scroll_manager.anchor(),
2245 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2246 placeholder_text: self.placeholder_text.clone(),
2247 is_focused: self.focus_handle.is_focused(cx),
2248 current_line_highlight: self
2249 .current_line_highlight
2250 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2251 gutter_hovered: self.gutter_hovered,
2252 }
2253 }
2254
2255 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2256 self.buffer.read(cx).language_at(point, cx)
2257 }
2258
2259 pub fn file_at<T: ToOffset>(
2260 &self,
2261 point: T,
2262 cx: &AppContext,
2263 ) -> Option<Arc<dyn language::File>> {
2264 self.buffer.read(cx).read(cx).file_at(point).cloned()
2265 }
2266
2267 pub fn active_excerpt(
2268 &self,
2269 cx: &AppContext,
2270 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2271 self.buffer
2272 .read(cx)
2273 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2274 }
2275
2276 pub fn mode(&self) -> EditorMode {
2277 self.mode
2278 }
2279
2280 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2281 self.collaboration_hub.as_deref()
2282 }
2283
2284 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2285 self.collaboration_hub = Some(hub);
2286 }
2287
2288 pub fn set_custom_context_menu(
2289 &mut self,
2290 f: impl 'static
2291 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2292 ) {
2293 self.custom_context_menu = Some(Box::new(f))
2294 }
2295
2296 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2297 self.completion_provider = Some(provider);
2298 }
2299
2300 pub fn set_inline_completion_provider<T>(
2301 &mut self,
2302 provider: Option<Model<T>>,
2303 cx: &mut ViewContext<Self>,
2304 ) where
2305 T: InlineCompletionProvider,
2306 {
2307 self.inline_completion_provider =
2308 provider.map(|provider| RegisteredInlineCompletionProvider {
2309 _subscription: cx.observe(&provider, |this, _, cx| {
2310 if this.focus_handle.is_focused(cx) {
2311 this.update_visible_inline_completion(cx);
2312 }
2313 }),
2314 provider: Arc::new(provider),
2315 });
2316 self.refresh_inline_completion(false, false, cx);
2317 }
2318
2319 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2320 self.placeholder_text.as_deref()
2321 }
2322
2323 pub fn set_placeholder_text(
2324 &mut self,
2325 placeholder_text: impl Into<Arc<str>>,
2326 cx: &mut ViewContext<Self>,
2327 ) {
2328 let placeholder_text = Some(placeholder_text.into());
2329 if self.placeholder_text != placeholder_text {
2330 self.placeholder_text = placeholder_text;
2331 cx.notify();
2332 }
2333 }
2334
2335 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2336 self.cursor_shape = cursor_shape;
2337
2338 // Disrupt blink for immediate user feedback that the cursor shape has changed
2339 self.blink_manager.update(cx, BlinkManager::show_cursor);
2340
2341 cx.notify();
2342 }
2343
2344 pub fn set_current_line_highlight(
2345 &mut self,
2346 current_line_highlight: Option<CurrentLineHighlight>,
2347 ) {
2348 self.current_line_highlight = current_line_highlight;
2349 }
2350
2351 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2352 self.collapse_matches = collapse_matches;
2353 }
2354
2355 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2356 if self.collapse_matches {
2357 return range.start..range.start;
2358 }
2359 range.clone()
2360 }
2361
2362 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2363 if self.display_map.read(cx).clip_at_line_ends != clip {
2364 self.display_map
2365 .update(cx, |map, _| map.clip_at_line_ends = clip);
2366 }
2367 }
2368
2369 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2370 self.input_enabled = input_enabled;
2371 }
2372
2373 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2374 self.enable_inline_completions = enabled;
2375 }
2376
2377 pub fn set_autoindent(&mut self, autoindent: bool) {
2378 if autoindent {
2379 self.autoindent_mode = Some(AutoindentMode::EachLine);
2380 } else {
2381 self.autoindent_mode = None;
2382 }
2383 }
2384
2385 pub fn read_only(&self, cx: &AppContext) -> bool {
2386 self.read_only || self.buffer.read(cx).read_only()
2387 }
2388
2389 pub fn set_read_only(&mut self, read_only: bool) {
2390 self.read_only = read_only;
2391 }
2392
2393 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2394 self.use_autoclose = autoclose;
2395 }
2396
2397 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2398 self.use_auto_surround = auto_surround;
2399 }
2400
2401 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2402 self.auto_replace_emoji_shortcode = auto_replace;
2403 }
2404
2405 pub fn toggle_inline_completions(
2406 &mut self,
2407 _: &ToggleInlineCompletions,
2408 cx: &mut ViewContext<Self>,
2409 ) {
2410 if self.show_inline_completions_override.is_some() {
2411 self.set_show_inline_completions(None, cx);
2412 } else {
2413 let cursor = self.selections.newest_anchor().head();
2414 if let Some((buffer, cursor_buffer_position)) =
2415 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2416 {
2417 let show_inline_completions =
2418 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2419 self.set_show_inline_completions(Some(show_inline_completions), cx);
2420 }
2421 }
2422 }
2423
2424 pub fn set_show_inline_completions(
2425 &mut self,
2426 show_inline_completions: Option<bool>,
2427 cx: &mut ViewContext<Self>,
2428 ) {
2429 self.show_inline_completions_override = show_inline_completions;
2430 self.refresh_inline_completion(false, true, cx);
2431 }
2432
2433 fn should_show_inline_completions(
2434 &self,
2435 buffer: &Model<Buffer>,
2436 buffer_position: language::Anchor,
2437 cx: &AppContext,
2438 ) -> bool {
2439 if let Some(provider) = self.inline_completion_provider() {
2440 if let Some(show_inline_completions) = self.show_inline_completions_override {
2441 show_inline_completions
2442 } else {
2443 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2444 }
2445 } else {
2446 false
2447 }
2448 }
2449
2450 pub fn set_use_modal_editing(&mut self, to: bool) {
2451 self.use_modal_editing = to;
2452 }
2453
2454 pub fn use_modal_editing(&self) -> bool {
2455 self.use_modal_editing
2456 }
2457
2458 fn selections_did_change(
2459 &mut self,
2460 local: bool,
2461 old_cursor_position: &Anchor,
2462 show_completions: bool,
2463 cx: &mut ViewContext<Self>,
2464 ) {
2465 cx.invalidate_character_coordinates();
2466
2467 // Copy selections to primary selection buffer
2468 #[cfg(target_os = "linux")]
2469 if local {
2470 let selections = self.selections.all::<usize>(cx);
2471 let buffer_handle = self.buffer.read(cx).read(cx);
2472
2473 let mut text = String::new();
2474 for (index, selection) in selections.iter().enumerate() {
2475 let text_for_selection = buffer_handle
2476 .text_for_range(selection.start..selection.end)
2477 .collect::<String>();
2478
2479 text.push_str(&text_for_selection);
2480 if index != selections.len() - 1 {
2481 text.push('\n');
2482 }
2483 }
2484
2485 if !text.is_empty() {
2486 cx.write_to_primary(ClipboardItem::new_string(text));
2487 }
2488 }
2489
2490 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2491 self.buffer.update(cx, |buffer, cx| {
2492 buffer.set_active_selections(
2493 &self.selections.disjoint_anchors(),
2494 self.selections.line_mode,
2495 self.cursor_shape,
2496 cx,
2497 )
2498 });
2499 }
2500 let display_map = self
2501 .display_map
2502 .update(cx, |display_map, cx| display_map.snapshot(cx));
2503 let buffer = &display_map.buffer_snapshot;
2504 self.add_selections_state = None;
2505 self.select_next_state = None;
2506 self.select_prev_state = None;
2507 self.select_larger_syntax_node_stack.clear();
2508 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2509 self.snippet_stack
2510 .invalidate(&self.selections.disjoint_anchors(), buffer);
2511 self.take_rename(false, cx);
2512
2513 let new_cursor_position = self.selections.newest_anchor().head();
2514
2515 self.push_to_nav_history(
2516 *old_cursor_position,
2517 Some(new_cursor_position.to_point(buffer)),
2518 cx,
2519 );
2520
2521 if local {
2522 let new_cursor_position = self.selections.newest_anchor().head();
2523 let mut context_menu = self.context_menu.write();
2524 let completion_menu = match context_menu.as_ref() {
2525 Some(ContextMenu::Completions(menu)) => Some(menu),
2526
2527 _ => {
2528 *context_menu = None;
2529 None
2530 }
2531 };
2532
2533 if let Some(completion_menu) = completion_menu {
2534 let cursor_position = new_cursor_position.to_offset(buffer);
2535 let (word_range, kind) =
2536 buffer.surrounding_word(completion_menu.initial_position, true);
2537 if kind == Some(CharKind::Word)
2538 && word_range.to_inclusive().contains(&cursor_position)
2539 {
2540 let mut completion_menu = completion_menu.clone();
2541 drop(context_menu);
2542
2543 let query = Self::completion_query(buffer, cursor_position);
2544 cx.spawn(move |this, mut cx| async move {
2545 completion_menu
2546 .filter(query.as_deref(), cx.background_executor().clone())
2547 .await;
2548
2549 this.update(&mut cx, |this, cx| {
2550 let mut context_menu = this.context_menu.write();
2551 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2552 return;
2553 };
2554
2555 if menu.id > completion_menu.id {
2556 return;
2557 }
2558
2559 *context_menu = Some(ContextMenu::Completions(completion_menu));
2560 drop(context_menu);
2561 cx.notify();
2562 })
2563 })
2564 .detach();
2565
2566 if show_completions {
2567 self.show_completions(&ShowCompletions { trigger: None }, cx);
2568 }
2569 } else {
2570 drop(context_menu);
2571 self.hide_context_menu(cx);
2572 }
2573 } else {
2574 drop(context_menu);
2575 }
2576
2577 hide_hover(self, cx);
2578
2579 if old_cursor_position.to_display_point(&display_map).row()
2580 != new_cursor_position.to_display_point(&display_map).row()
2581 {
2582 self.available_code_actions.take();
2583 }
2584 self.refresh_code_actions(cx);
2585 self.refresh_document_highlights(cx);
2586 refresh_matching_bracket_highlights(self, cx);
2587 self.discard_inline_completion(false, cx);
2588 linked_editing_ranges::refresh_linked_ranges(self, cx);
2589 if self.git_blame_inline_enabled {
2590 self.start_inline_blame_timer(cx);
2591 }
2592 }
2593
2594 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2595 cx.emit(EditorEvent::SelectionsChanged { local });
2596
2597 if self.selections.disjoint_anchors().len() == 1 {
2598 cx.emit(SearchEvent::ActiveMatchChanged)
2599 }
2600 cx.notify();
2601 }
2602
2603 pub fn change_selections<R>(
2604 &mut self,
2605 autoscroll: Option<Autoscroll>,
2606 cx: &mut ViewContext<Self>,
2607 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2608 ) -> R {
2609 self.change_selections_inner(autoscroll, true, cx, change)
2610 }
2611
2612 pub fn change_selections_inner<R>(
2613 &mut self,
2614 autoscroll: Option<Autoscroll>,
2615 request_completions: bool,
2616 cx: &mut ViewContext<Self>,
2617 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2618 ) -> R {
2619 let old_cursor_position = self.selections.newest_anchor().head();
2620 self.push_to_selection_history();
2621
2622 let (changed, result) = self.selections.change_with(cx, change);
2623
2624 if changed {
2625 if let Some(autoscroll) = autoscroll {
2626 self.request_autoscroll(autoscroll, cx);
2627 }
2628 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2629
2630 if self.should_open_signature_help_automatically(
2631 &old_cursor_position,
2632 self.signature_help_state.backspace_pressed(),
2633 cx,
2634 ) {
2635 self.show_signature_help(&ShowSignatureHelp, cx);
2636 }
2637 self.signature_help_state.set_backspace_pressed(false);
2638 }
2639
2640 result
2641 }
2642
2643 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2644 where
2645 I: IntoIterator<Item = (Range<S>, T)>,
2646 S: ToOffset,
2647 T: Into<Arc<str>>,
2648 {
2649 if self.read_only(cx) {
2650 return;
2651 }
2652
2653 self.buffer
2654 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2655 }
2656
2657 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2658 where
2659 I: IntoIterator<Item = (Range<S>, T)>,
2660 S: ToOffset,
2661 T: Into<Arc<str>>,
2662 {
2663 if self.read_only(cx) {
2664 return;
2665 }
2666
2667 self.buffer.update(cx, |buffer, cx| {
2668 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2669 });
2670 }
2671
2672 pub fn edit_with_block_indent<I, S, T>(
2673 &mut self,
2674 edits: I,
2675 original_indent_columns: Vec<u32>,
2676 cx: &mut ViewContext<Self>,
2677 ) where
2678 I: IntoIterator<Item = (Range<S>, T)>,
2679 S: ToOffset,
2680 T: Into<Arc<str>>,
2681 {
2682 if self.read_only(cx) {
2683 return;
2684 }
2685
2686 self.buffer.update(cx, |buffer, cx| {
2687 buffer.edit(
2688 edits,
2689 Some(AutoindentMode::Block {
2690 original_indent_columns,
2691 }),
2692 cx,
2693 )
2694 });
2695 }
2696
2697 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2698 self.hide_context_menu(cx);
2699
2700 match phase {
2701 SelectPhase::Begin {
2702 position,
2703 add,
2704 click_count,
2705 } => self.begin_selection(position, add, click_count, cx),
2706 SelectPhase::BeginColumnar {
2707 position,
2708 goal_column,
2709 reset,
2710 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2711 SelectPhase::Extend {
2712 position,
2713 click_count,
2714 } => self.extend_selection(position, click_count, cx),
2715 SelectPhase::Update {
2716 position,
2717 goal_column,
2718 scroll_delta,
2719 } => self.update_selection(position, goal_column, scroll_delta, cx),
2720 SelectPhase::End => self.end_selection(cx),
2721 }
2722 }
2723
2724 fn extend_selection(
2725 &mut self,
2726 position: DisplayPoint,
2727 click_count: usize,
2728 cx: &mut ViewContext<Self>,
2729 ) {
2730 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2731 let tail = self.selections.newest::<usize>(cx).tail();
2732 self.begin_selection(position, false, click_count, cx);
2733
2734 let position = position.to_offset(&display_map, Bias::Left);
2735 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2736
2737 let mut pending_selection = self
2738 .selections
2739 .pending_anchor()
2740 .expect("extend_selection not called with pending selection");
2741 if position >= tail {
2742 pending_selection.start = tail_anchor;
2743 } else {
2744 pending_selection.end = tail_anchor;
2745 pending_selection.reversed = true;
2746 }
2747
2748 let mut pending_mode = self.selections.pending_mode().unwrap();
2749 match &mut pending_mode {
2750 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2751 _ => {}
2752 }
2753
2754 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2755 s.set_pending(pending_selection, pending_mode)
2756 });
2757 }
2758
2759 fn begin_selection(
2760 &mut self,
2761 position: DisplayPoint,
2762 add: bool,
2763 click_count: usize,
2764 cx: &mut ViewContext<Self>,
2765 ) {
2766 if !self.focus_handle.is_focused(cx) {
2767 self.last_focused_descendant = None;
2768 cx.focus(&self.focus_handle);
2769 }
2770
2771 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2772 let buffer = &display_map.buffer_snapshot;
2773 let newest_selection = self.selections.newest_anchor().clone();
2774 let position = display_map.clip_point(position, Bias::Left);
2775
2776 let start;
2777 let end;
2778 let mode;
2779 let auto_scroll;
2780 match click_count {
2781 1 => {
2782 start = buffer.anchor_before(position.to_point(&display_map));
2783 end = start;
2784 mode = SelectMode::Character;
2785 auto_scroll = true;
2786 }
2787 2 => {
2788 let range = movement::surrounding_word(&display_map, position);
2789 start = buffer.anchor_before(range.start.to_point(&display_map));
2790 end = buffer.anchor_before(range.end.to_point(&display_map));
2791 mode = SelectMode::Word(start..end);
2792 auto_scroll = true;
2793 }
2794 3 => {
2795 let position = display_map
2796 .clip_point(position, Bias::Left)
2797 .to_point(&display_map);
2798 let line_start = display_map.prev_line_boundary(position).0;
2799 let next_line_start = buffer.clip_point(
2800 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2801 Bias::Left,
2802 );
2803 start = buffer.anchor_before(line_start);
2804 end = buffer.anchor_before(next_line_start);
2805 mode = SelectMode::Line(start..end);
2806 auto_scroll = true;
2807 }
2808 _ => {
2809 start = buffer.anchor_before(0);
2810 end = buffer.anchor_before(buffer.len());
2811 mode = SelectMode::All;
2812 auto_scroll = false;
2813 }
2814 }
2815
2816 let point_to_delete: Option<usize> = {
2817 let selected_points: Vec<Selection<Point>> =
2818 self.selections.disjoint_in_range(start..end, cx);
2819
2820 if !add || click_count > 1 {
2821 None
2822 } else if !selected_points.is_empty() {
2823 Some(selected_points[0].id)
2824 } else {
2825 let clicked_point_already_selected =
2826 self.selections.disjoint.iter().find(|selection| {
2827 selection.start.to_point(buffer) == start.to_point(buffer)
2828 || selection.end.to_point(buffer) == end.to_point(buffer)
2829 });
2830
2831 clicked_point_already_selected.map(|selection| selection.id)
2832 }
2833 };
2834
2835 let selections_count = self.selections.count();
2836
2837 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2838 if let Some(point_to_delete) = point_to_delete {
2839 s.delete(point_to_delete);
2840
2841 if selections_count == 1 {
2842 s.set_pending_anchor_range(start..end, mode);
2843 }
2844 } else {
2845 if !add {
2846 s.clear_disjoint();
2847 } else if click_count > 1 {
2848 s.delete(newest_selection.id)
2849 }
2850
2851 s.set_pending_anchor_range(start..end, mode);
2852 }
2853 });
2854 }
2855
2856 fn begin_columnar_selection(
2857 &mut self,
2858 position: DisplayPoint,
2859 goal_column: u32,
2860 reset: bool,
2861 cx: &mut ViewContext<Self>,
2862 ) {
2863 if !self.focus_handle.is_focused(cx) {
2864 self.last_focused_descendant = None;
2865 cx.focus(&self.focus_handle);
2866 }
2867
2868 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2869
2870 if reset {
2871 let pointer_position = display_map
2872 .buffer_snapshot
2873 .anchor_before(position.to_point(&display_map));
2874
2875 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2876 s.clear_disjoint();
2877 s.set_pending_anchor_range(
2878 pointer_position..pointer_position,
2879 SelectMode::Character,
2880 );
2881 });
2882 }
2883
2884 let tail = self.selections.newest::<Point>(cx).tail();
2885 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2886
2887 if !reset {
2888 self.select_columns(
2889 tail.to_display_point(&display_map),
2890 position,
2891 goal_column,
2892 &display_map,
2893 cx,
2894 );
2895 }
2896 }
2897
2898 fn update_selection(
2899 &mut self,
2900 position: DisplayPoint,
2901 goal_column: u32,
2902 scroll_delta: gpui::Point<f32>,
2903 cx: &mut ViewContext<Self>,
2904 ) {
2905 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2906
2907 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2908 let tail = tail.to_display_point(&display_map);
2909 self.select_columns(tail, position, goal_column, &display_map, cx);
2910 } else if let Some(mut pending) = self.selections.pending_anchor() {
2911 let buffer = self.buffer.read(cx).snapshot(cx);
2912 let head;
2913 let tail;
2914 let mode = self.selections.pending_mode().unwrap();
2915 match &mode {
2916 SelectMode::Character => {
2917 head = position.to_point(&display_map);
2918 tail = pending.tail().to_point(&buffer);
2919 }
2920 SelectMode::Word(original_range) => {
2921 let original_display_range = original_range.start.to_display_point(&display_map)
2922 ..original_range.end.to_display_point(&display_map);
2923 let original_buffer_range = original_display_range.start.to_point(&display_map)
2924 ..original_display_range.end.to_point(&display_map);
2925 if movement::is_inside_word(&display_map, position)
2926 || original_display_range.contains(&position)
2927 {
2928 let word_range = movement::surrounding_word(&display_map, position);
2929 if word_range.start < original_display_range.start {
2930 head = word_range.start.to_point(&display_map);
2931 } else {
2932 head = word_range.end.to_point(&display_map);
2933 }
2934 } else {
2935 head = position.to_point(&display_map);
2936 }
2937
2938 if head <= original_buffer_range.start {
2939 tail = original_buffer_range.end;
2940 } else {
2941 tail = original_buffer_range.start;
2942 }
2943 }
2944 SelectMode::Line(original_range) => {
2945 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2946
2947 let position = display_map
2948 .clip_point(position, Bias::Left)
2949 .to_point(&display_map);
2950 let line_start = display_map.prev_line_boundary(position).0;
2951 let next_line_start = buffer.clip_point(
2952 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2953 Bias::Left,
2954 );
2955
2956 if line_start < original_range.start {
2957 head = line_start
2958 } else {
2959 head = next_line_start
2960 }
2961
2962 if head <= original_range.start {
2963 tail = original_range.end;
2964 } else {
2965 tail = original_range.start;
2966 }
2967 }
2968 SelectMode::All => {
2969 return;
2970 }
2971 };
2972
2973 if head < tail {
2974 pending.start = buffer.anchor_before(head);
2975 pending.end = buffer.anchor_before(tail);
2976 pending.reversed = true;
2977 } else {
2978 pending.start = buffer.anchor_before(tail);
2979 pending.end = buffer.anchor_before(head);
2980 pending.reversed = false;
2981 }
2982
2983 self.change_selections(None, cx, |s| {
2984 s.set_pending(pending, mode);
2985 });
2986 } else {
2987 log::error!("update_selection dispatched with no pending selection");
2988 return;
2989 }
2990
2991 self.apply_scroll_delta(scroll_delta, cx);
2992 cx.notify();
2993 }
2994
2995 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2996 self.columnar_selection_tail.take();
2997 if self.selections.pending_anchor().is_some() {
2998 let selections = self.selections.all::<usize>(cx);
2999 self.change_selections(None, cx, |s| {
3000 s.select(selections);
3001 s.clear_pending();
3002 });
3003 }
3004 }
3005
3006 fn select_columns(
3007 &mut self,
3008 tail: DisplayPoint,
3009 head: DisplayPoint,
3010 goal_column: u32,
3011 display_map: &DisplaySnapshot,
3012 cx: &mut ViewContext<Self>,
3013 ) {
3014 let start_row = cmp::min(tail.row(), head.row());
3015 let end_row = cmp::max(tail.row(), head.row());
3016 let start_column = cmp::min(tail.column(), goal_column);
3017 let end_column = cmp::max(tail.column(), goal_column);
3018 let reversed = start_column < tail.column();
3019
3020 let selection_ranges = (start_row.0..=end_row.0)
3021 .map(DisplayRow)
3022 .filter_map(|row| {
3023 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
3024 let start = display_map
3025 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
3026 .to_point(display_map);
3027 let end = display_map
3028 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
3029 .to_point(display_map);
3030 if reversed {
3031 Some(end..start)
3032 } else {
3033 Some(start..end)
3034 }
3035 } else {
3036 None
3037 }
3038 })
3039 .collect::<Vec<_>>();
3040
3041 self.change_selections(None, cx, |s| {
3042 s.select_ranges(selection_ranges);
3043 });
3044 cx.notify();
3045 }
3046
3047 pub fn has_pending_nonempty_selection(&self) -> bool {
3048 let pending_nonempty_selection = match self.selections.pending_anchor() {
3049 Some(Selection { start, end, .. }) => start != end,
3050 None => false,
3051 };
3052
3053 pending_nonempty_selection
3054 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
3055 }
3056
3057 pub fn has_pending_selection(&self) -> bool {
3058 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
3059 }
3060
3061 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3062 if self.clear_clicked_diff_hunks(cx) {
3063 cx.notify();
3064 return;
3065 }
3066 if self.dismiss_menus_and_popups(true, cx) {
3067 return;
3068 }
3069
3070 if self.mode == EditorMode::Full
3071 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3072 {
3073 return;
3074 }
3075
3076 cx.propagate();
3077 }
3078
3079 pub fn dismiss_menus_and_popups(
3080 &mut self,
3081 should_report_inline_completion_event: bool,
3082 cx: &mut ViewContext<Self>,
3083 ) -> bool {
3084 if self.take_rename(false, cx).is_some() {
3085 return true;
3086 }
3087
3088 if hide_hover(self, cx) {
3089 return true;
3090 }
3091
3092 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3093 return true;
3094 }
3095
3096 if self.hide_context_menu(cx).is_some() {
3097 return true;
3098 }
3099
3100 if self.mouse_context_menu.take().is_some() {
3101 return true;
3102 }
3103
3104 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3105 return true;
3106 }
3107
3108 if self.snippet_stack.pop().is_some() {
3109 return true;
3110 }
3111
3112 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3113 self.dismiss_diagnostics(cx);
3114 return true;
3115 }
3116
3117 false
3118 }
3119
3120 fn linked_editing_ranges_for(
3121 &self,
3122 selection: Range<text::Anchor>,
3123 cx: &AppContext,
3124 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3125 if self.linked_edit_ranges.is_empty() {
3126 return None;
3127 }
3128 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3129 selection.end.buffer_id.and_then(|end_buffer_id| {
3130 if selection.start.buffer_id != Some(end_buffer_id) {
3131 return None;
3132 }
3133 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3134 let snapshot = buffer.read(cx).snapshot();
3135 self.linked_edit_ranges
3136 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3137 .map(|ranges| (ranges, snapshot, buffer))
3138 })?;
3139 use text::ToOffset as TO;
3140 // find offset from the start of current range to current cursor position
3141 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3142
3143 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3144 let start_difference = start_offset - start_byte_offset;
3145 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3146 let end_difference = end_offset - start_byte_offset;
3147 // Current range has associated linked ranges.
3148 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3149 for range in linked_ranges.iter() {
3150 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3151 let end_offset = start_offset + end_difference;
3152 let start_offset = start_offset + start_difference;
3153 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3154 continue;
3155 }
3156 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3157 if s.start.buffer_id != selection.start.buffer_id
3158 || s.end.buffer_id != selection.end.buffer_id
3159 {
3160 return false;
3161 }
3162 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3163 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3164 }) {
3165 continue;
3166 }
3167 let start = buffer_snapshot.anchor_after(start_offset);
3168 let end = buffer_snapshot.anchor_after(end_offset);
3169 linked_edits
3170 .entry(buffer.clone())
3171 .or_default()
3172 .push(start..end);
3173 }
3174 Some(linked_edits)
3175 }
3176
3177 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3178 let text: Arc<str> = text.into();
3179
3180 if self.read_only(cx) {
3181 return;
3182 }
3183
3184 let selections = self.selections.all_adjusted(cx);
3185 let mut bracket_inserted = false;
3186 let mut edits = Vec::new();
3187 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3188 let mut new_selections = Vec::with_capacity(selections.len());
3189 let mut new_autoclose_regions = Vec::new();
3190 let snapshot = self.buffer.read(cx).read(cx);
3191
3192 for (selection, autoclose_region) in
3193 self.selections_with_autoclose_regions(selections, &snapshot)
3194 {
3195 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3196 // Determine if the inserted text matches the opening or closing
3197 // bracket of any of this language's bracket pairs.
3198 let mut bracket_pair = None;
3199 let mut is_bracket_pair_start = false;
3200 let mut is_bracket_pair_end = false;
3201 if !text.is_empty() {
3202 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3203 // and they are removing the character that triggered IME popup.
3204 for (pair, enabled) in scope.brackets() {
3205 if !pair.close && !pair.surround {
3206 continue;
3207 }
3208
3209 if enabled && pair.start.ends_with(text.as_ref()) {
3210 bracket_pair = Some(pair.clone());
3211 is_bracket_pair_start = true;
3212 break;
3213 }
3214 if pair.end.as_str() == text.as_ref() {
3215 bracket_pair = Some(pair.clone());
3216 is_bracket_pair_end = true;
3217 break;
3218 }
3219 }
3220 }
3221
3222 if let Some(bracket_pair) = bracket_pair {
3223 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3224 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3225 let auto_surround =
3226 self.use_auto_surround && snapshot_settings.use_auto_surround;
3227 if selection.is_empty() {
3228 if is_bracket_pair_start {
3229 let prefix_len = bracket_pair.start.len() - text.len();
3230
3231 // If the inserted text is a suffix of an opening bracket and the
3232 // selection is preceded by the rest of the opening bracket, then
3233 // insert the closing bracket.
3234 let following_text_allows_autoclose = snapshot
3235 .chars_at(selection.start)
3236 .next()
3237 .map_or(true, |c| scope.should_autoclose_before(c));
3238 let preceding_text_matches_prefix = prefix_len == 0
3239 || (selection.start.column >= (prefix_len as u32)
3240 && snapshot.contains_str_at(
3241 Point::new(
3242 selection.start.row,
3243 selection.start.column - (prefix_len as u32),
3244 ),
3245 &bracket_pair.start[..prefix_len],
3246 ));
3247
3248 if autoclose
3249 && bracket_pair.close
3250 && following_text_allows_autoclose
3251 && preceding_text_matches_prefix
3252 {
3253 let anchor = snapshot.anchor_before(selection.end);
3254 new_selections.push((selection.map(|_| anchor), text.len()));
3255 new_autoclose_regions.push((
3256 anchor,
3257 text.len(),
3258 selection.id,
3259 bracket_pair.clone(),
3260 ));
3261 edits.push((
3262 selection.range(),
3263 format!("{}{}", text, bracket_pair.end).into(),
3264 ));
3265 bracket_inserted = true;
3266 continue;
3267 }
3268 }
3269
3270 if let Some(region) = autoclose_region {
3271 // If the selection is followed by an auto-inserted closing bracket,
3272 // then don't insert that closing bracket again; just move the selection
3273 // past the closing bracket.
3274 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3275 && text.as_ref() == region.pair.end.as_str();
3276 if should_skip {
3277 let anchor = snapshot.anchor_after(selection.end);
3278 new_selections
3279 .push((selection.map(|_| anchor), region.pair.end.len()));
3280 continue;
3281 }
3282 }
3283
3284 let always_treat_brackets_as_autoclosed = snapshot
3285 .settings_at(selection.start, cx)
3286 .always_treat_brackets_as_autoclosed;
3287 if always_treat_brackets_as_autoclosed
3288 && is_bracket_pair_end
3289 && snapshot.contains_str_at(selection.end, text.as_ref())
3290 {
3291 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3292 // and the inserted text is a closing bracket and the selection is followed
3293 // by the closing bracket then move the selection past the closing bracket.
3294 let anchor = snapshot.anchor_after(selection.end);
3295 new_selections.push((selection.map(|_| anchor), text.len()));
3296 continue;
3297 }
3298 }
3299 // If an opening bracket is 1 character long and is typed while
3300 // text is selected, then surround that text with the bracket pair.
3301 else if auto_surround
3302 && bracket_pair.surround
3303 && is_bracket_pair_start
3304 && bracket_pair.start.chars().count() == 1
3305 {
3306 edits.push((selection.start..selection.start, text.clone()));
3307 edits.push((
3308 selection.end..selection.end,
3309 bracket_pair.end.as_str().into(),
3310 ));
3311 bracket_inserted = true;
3312 new_selections.push((
3313 Selection {
3314 id: selection.id,
3315 start: snapshot.anchor_after(selection.start),
3316 end: snapshot.anchor_before(selection.end),
3317 reversed: selection.reversed,
3318 goal: selection.goal,
3319 },
3320 0,
3321 ));
3322 continue;
3323 }
3324 }
3325 }
3326
3327 if self.auto_replace_emoji_shortcode
3328 && selection.is_empty()
3329 && text.as_ref().ends_with(':')
3330 {
3331 if let Some(possible_emoji_short_code) =
3332 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3333 {
3334 if !possible_emoji_short_code.is_empty() {
3335 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3336 let emoji_shortcode_start = Point::new(
3337 selection.start.row,
3338 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3339 );
3340
3341 // Remove shortcode from buffer
3342 edits.push((
3343 emoji_shortcode_start..selection.start,
3344 "".to_string().into(),
3345 ));
3346 new_selections.push((
3347 Selection {
3348 id: selection.id,
3349 start: snapshot.anchor_after(emoji_shortcode_start),
3350 end: snapshot.anchor_before(selection.start),
3351 reversed: selection.reversed,
3352 goal: selection.goal,
3353 },
3354 0,
3355 ));
3356
3357 // Insert emoji
3358 let selection_start_anchor = snapshot.anchor_after(selection.start);
3359 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3360 edits.push((selection.start..selection.end, emoji.to_string().into()));
3361
3362 continue;
3363 }
3364 }
3365 }
3366 }
3367
3368 // If not handling any auto-close operation, then just replace the selected
3369 // text with the given input and move the selection to the end of the
3370 // newly inserted text.
3371 let anchor = snapshot.anchor_after(selection.end);
3372 if !self.linked_edit_ranges.is_empty() {
3373 let start_anchor = snapshot.anchor_before(selection.start);
3374
3375 let is_word_char = text.chars().next().map_or(true, |char| {
3376 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3377 classifier.is_word(char)
3378 });
3379
3380 if is_word_char {
3381 if let Some(ranges) = self
3382 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3383 {
3384 for (buffer, edits) in ranges {
3385 linked_edits
3386 .entry(buffer.clone())
3387 .or_default()
3388 .extend(edits.into_iter().map(|range| (range, text.clone())));
3389 }
3390 }
3391 }
3392 }
3393
3394 new_selections.push((selection.map(|_| anchor), 0));
3395 edits.push((selection.start..selection.end, text.clone()));
3396 }
3397
3398 drop(snapshot);
3399
3400 self.transact(cx, |this, cx| {
3401 this.buffer.update(cx, |buffer, cx| {
3402 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3403 });
3404 for (buffer, edits) in linked_edits {
3405 buffer.update(cx, |buffer, cx| {
3406 let snapshot = buffer.snapshot();
3407 let edits = edits
3408 .into_iter()
3409 .map(|(range, text)| {
3410 use text::ToPoint as TP;
3411 let end_point = TP::to_point(&range.end, &snapshot);
3412 let start_point = TP::to_point(&range.start, &snapshot);
3413 (start_point..end_point, text)
3414 })
3415 .sorted_by_key(|(range, _)| range.start)
3416 .collect::<Vec<_>>();
3417 buffer.edit(edits, None, cx);
3418 })
3419 }
3420 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3421 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3422 let snapshot = this.buffer.read(cx).read(cx);
3423 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3424 .zip(new_selection_deltas)
3425 .map(|(selection, delta)| Selection {
3426 id: selection.id,
3427 start: selection.start + delta,
3428 end: selection.end + delta,
3429 reversed: selection.reversed,
3430 goal: SelectionGoal::None,
3431 })
3432 .collect::<Vec<_>>();
3433
3434 let mut i = 0;
3435 for (position, delta, selection_id, pair) in new_autoclose_regions {
3436 let position = position.to_offset(&snapshot) + delta;
3437 let start = snapshot.anchor_before(position);
3438 let end = snapshot.anchor_after(position);
3439 while let Some(existing_state) = this.autoclose_regions.get(i) {
3440 match existing_state.range.start.cmp(&start, &snapshot) {
3441 Ordering::Less => i += 1,
3442 Ordering::Greater => break,
3443 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3444 Ordering::Less => i += 1,
3445 Ordering::Equal => break,
3446 Ordering::Greater => break,
3447 },
3448 }
3449 }
3450 this.autoclose_regions.insert(
3451 i,
3452 AutocloseRegion {
3453 selection_id,
3454 range: start..end,
3455 pair,
3456 },
3457 );
3458 }
3459
3460 drop(snapshot);
3461 let had_active_inline_completion = this.has_active_inline_completion(cx);
3462 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3463 s.select(new_selections)
3464 });
3465
3466 if !bracket_inserted {
3467 if let Some(on_type_format_task) =
3468 this.trigger_on_type_formatting(text.to_string(), cx)
3469 {
3470 on_type_format_task.detach_and_log_err(cx);
3471 }
3472 }
3473
3474 let editor_settings = EditorSettings::get_global(cx);
3475 if bracket_inserted
3476 && (editor_settings.auto_signature_help
3477 || editor_settings.show_signature_help_after_edits)
3478 {
3479 this.show_signature_help(&ShowSignatureHelp, cx);
3480 }
3481
3482 let trigger_in_words = !had_active_inline_completion;
3483 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3484 linked_editing_ranges::refresh_linked_ranges(this, cx);
3485 this.refresh_inline_completion(true, false, cx);
3486 });
3487 }
3488
3489 fn find_possible_emoji_shortcode_at_position(
3490 snapshot: &MultiBufferSnapshot,
3491 position: Point,
3492 ) -> Option<String> {
3493 let mut chars = Vec::new();
3494 let mut found_colon = false;
3495 for char in snapshot.reversed_chars_at(position).take(100) {
3496 // Found a possible emoji shortcode in the middle of the buffer
3497 if found_colon {
3498 if char.is_whitespace() {
3499 chars.reverse();
3500 return Some(chars.iter().collect());
3501 }
3502 // If the previous character is not a whitespace, we are in the middle of a word
3503 // and we only want to complete the shortcode if the word is made up of other emojis
3504 let mut containing_word = String::new();
3505 for ch in snapshot
3506 .reversed_chars_at(position)
3507 .skip(chars.len() + 1)
3508 .take(100)
3509 {
3510 if ch.is_whitespace() {
3511 break;
3512 }
3513 containing_word.push(ch);
3514 }
3515 let containing_word = containing_word.chars().rev().collect::<String>();
3516 if util::word_consists_of_emojis(containing_word.as_str()) {
3517 chars.reverse();
3518 return Some(chars.iter().collect());
3519 }
3520 }
3521
3522 if char.is_whitespace() || !char.is_ascii() {
3523 return None;
3524 }
3525 if char == ':' {
3526 found_colon = true;
3527 } else {
3528 chars.push(char);
3529 }
3530 }
3531 // Found a possible emoji shortcode at the beginning of the buffer
3532 chars.reverse();
3533 Some(chars.iter().collect())
3534 }
3535
3536 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3537 self.transact(cx, |this, cx| {
3538 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3539 let selections = this.selections.all::<usize>(cx);
3540 let multi_buffer = this.buffer.read(cx);
3541 let buffer = multi_buffer.snapshot(cx);
3542 selections
3543 .iter()
3544 .map(|selection| {
3545 let start_point = selection.start.to_point(&buffer);
3546 let mut indent =
3547 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3548 indent.len = cmp::min(indent.len, start_point.column);
3549 let start = selection.start;
3550 let end = selection.end;
3551 let selection_is_empty = start == end;
3552 let language_scope = buffer.language_scope_at(start);
3553 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3554 &language_scope
3555 {
3556 let leading_whitespace_len = buffer
3557 .reversed_chars_at(start)
3558 .take_while(|c| c.is_whitespace() && *c != '\n')
3559 .map(|c| c.len_utf8())
3560 .sum::<usize>();
3561
3562 let trailing_whitespace_len = buffer
3563 .chars_at(end)
3564 .take_while(|c| c.is_whitespace() && *c != '\n')
3565 .map(|c| c.len_utf8())
3566 .sum::<usize>();
3567
3568 let insert_extra_newline =
3569 language.brackets().any(|(pair, enabled)| {
3570 let pair_start = pair.start.trim_end();
3571 let pair_end = pair.end.trim_start();
3572
3573 enabled
3574 && pair.newline
3575 && buffer.contains_str_at(
3576 end + trailing_whitespace_len,
3577 pair_end,
3578 )
3579 && buffer.contains_str_at(
3580 (start - leading_whitespace_len)
3581 .saturating_sub(pair_start.len()),
3582 pair_start,
3583 )
3584 });
3585
3586 // Comment extension on newline is allowed only for cursor selections
3587 let comment_delimiter = maybe!({
3588 if !selection_is_empty {
3589 return None;
3590 }
3591
3592 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3593 return None;
3594 }
3595
3596 let delimiters = language.line_comment_prefixes();
3597 let max_len_of_delimiter =
3598 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3599 let (snapshot, range) =
3600 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3601
3602 let mut index_of_first_non_whitespace = 0;
3603 let comment_candidate = snapshot
3604 .chars_for_range(range)
3605 .skip_while(|c| {
3606 let should_skip = c.is_whitespace();
3607 if should_skip {
3608 index_of_first_non_whitespace += 1;
3609 }
3610 should_skip
3611 })
3612 .take(max_len_of_delimiter)
3613 .collect::<String>();
3614 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3615 comment_candidate.starts_with(comment_prefix.as_ref())
3616 })?;
3617 let cursor_is_placed_after_comment_marker =
3618 index_of_first_non_whitespace + comment_prefix.len()
3619 <= start_point.column as usize;
3620 if cursor_is_placed_after_comment_marker {
3621 Some(comment_prefix.clone())
3622 } else {
3623 None
3624 }
3625 });
3626 (comment_delimiter, insert_extra_newline)
3627 } else {
3628 (None, false)
3629 };
3630
3631 let capacity_for_delimiter = comment_delimiter
3632 .as_deref()
3633 .map(str::len)
3634 .unwrap_or_default();
3635 let mut new_text =
3636 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3637 new_text.push('\n');
3638 new_text.extend(indent.chars());
3639 if let Some(delimiter) = &comment_delimiter {
3640 new_text.push_str(delimiter);
3641 }
3642 if insert_extra_newline {
3643 new_text = new_text.repeat(2);
3644 }
3645
3646 let anchor = buffer.anchor_after(end);
3647 let new_selection = selection.map(|_| anchor);
3648 (
3649 (start..end, new_text),
3650 (insert_extra_newline, new_selection),
3651 )
3652 })
3653 .unzip()
3654 };
3655
3656 this.edit_with_autoindent(edits, cx);
3657 let buffer = this.buffer.read(cx).snapshot(cx);
3658 let new_selections = selection_fixup_info
3659 .into_iter()
3660 .map(|(extra_newline_inserted, new_selection)| {
3661 let mut cursor = new_selection.end.to_point(&buffer);
3662 if extra_newline_inserted {
3663 cursor.row -= 1;
3664 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3665 }
3666 new_selection.map(|_| cursor)
3667 })
3668 .collect();
3669
3670 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3671 this.refresh_inline_completion(true, false, cx);
3672 });
3673 }
3674
3675 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3676 let buffer = self.buffer.read(cx);
3677 let snapshot = buffer.snapshot(cx);
3678
3679 let mut edits = Vec::new();
3680 let mut rows = Vec::new();
3681
3682 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3683 let cursor = selection.head();
3684 let row = cursor.row;
3685
3686 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3687
3688 let newline = "\n".to_string();
3689 edits.push((start_of_line..start_of_line, newline));
3690
3691 rows.push(row + rows_inserted as u32);
3692 }
3693
3694 self.transact(cx, |editor, cx| {
3695 editor.edit(edits, cx);
3696
3697 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3698 let mut index = 0;
3699 s.move_cursors_with(|map, _, _| {
3700 let row = rows[index];
3701 index += 1;
3702
3703 let point = Point::new(row, 0);
3704 let boundary = map.next_line_boundary(point).1;
3705 let clipped = map.clip_point(boundary, Bias::Left);
3706
3707 (clipped, SelectionGoal::None)
3708 });
3709 });
3710
3711 let mut indent_edits = Vec::new();
3712 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3713 for row in rows {
3714 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3715 for (row, indent) in indents {
3716 if indent.len == 0 {
3717 continue;
3718 }
3719
3720 let text = match indent.kind {
3721 IndentKind::Space => " ".repeat(indent.len as usize),
3722 IndentKind::Tab => "\t".repeat(indent.len as usize),
3723 };
3724 let point = Point::new(row.0, 0);
3725 indent_edits.push((point..point, text));
3726 }
3727 }
3728 editor.edit(indent_edits, cx);
3729 });
3730 }
3731
3732 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3733 let buffer = self.buffer.read(cx);
3734 let snapshot = buffer.snapshot(cx);
3735
3736 let mut edits = Vec::new();
3737 let mut rows = Vec::new();
3738 let mut rows_inserted = 0;
3739
3740 for selection in self.selections.all_adjusted(cx) {
3741 let cursor = selection.head();
3742 let row = cursor.row;
3743
3744 let point = Point::new(row + 1, 0);
3745 let start_of_line = snapshot.clip_point(point, Bias::Left);
3746
3747 let newline = "\n".to_string();
3748 edits.push((start_of_line..start_of_line, newline));
3749
3750 rows_inserted += 1;
3751 rows.push(row + rows_inserted);
3752 }
3753
3754 self.transact(cx, |editor, cx| {
3755 editor.edit(edits, cx);
3756
3757 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3758 let mut index = 0;
3759 s.move_cursors_with(|map, _, _| {
3760 let row = rows[index];
3761 index += 1;
3762
3763 let point = Point::new(row, 0);
3764 let boundary = map.next_line_boundary(point).1;
3765 let clipped = map.clip_point(boundary, Bias::Left);
3766
3767 (clipped, SelectionGoal::None)
3768 });
3769 });
3770
3771 let mut indent_edits = Vec::new();
3772 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3773 for row in rows {
3774 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3775 for (row, indent) in indents {
3776 if indent.len == 0 {
3777 continue;
3778 }
3779
3780 let text = match indent.kind {
3781 IndentKind::Space => " ".repeat(indent.len as usize),
3782 IndentKind::Tab => "\t".repeat(indent.len as usize),
3783 };
3784 let point = Point::new(row.0, 0);
3785 indent_edits.push((point..point, text));
3786 }
3787 }
3788 editor.edit(indent_edits, cx);
3789 });
3790 }
3791
3792 pub fn insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3793 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3794 original_indent_columns: Vec::new(),
3795 });
3796 self.insert_with_autoindent_mode(text, autoindent, cx);
3797 }
3798
3799 fn insert_with_autoindent_mode(
3800 &mut self,
3801 text: &str,
3802 autoindent_mode: Option<AutoindentMode>,
3803 cx: &mut ViewContext<Self>,
3804 ) {
3805 if self.read_only(cx) {
3806 return;
3807 }
3808
3809 let text: Arc<str> = text.into();
3810 self.transact(cx, |this, cx| {
3811 let old_selections = this.selections.all_adjusted(cx);
3812 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3813 let anchors = {
3814 let snapshot = buffer.read(cx);
3815 old_selections
3816 .iter()
3817 .map(|s| {
3818 let anchor = snapshot.anchor_after(s.head());
3819 s.map(|_| anchor)
3820 })
3821 .collect::<Vec<_>>()
3822 };
3823 buffer.edit(
3824 old_selections
3825 .iter()
3826 .map(|s| (s.start..s.end, text.clone())),
3827 autoindent_mode,
3828 cx,
3829 );
3830 anchors
3831 });
3832
3833 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3834 s.select_anchors(selection_anchors);
3835 })
3836 });
3837 }
3838
3839 fn trigger_completion_on_input(
3840 &mut self,
3841 text: &str,
3842 trigger_in_words: bool,
3843 cx: &mut ViewContext<Self>,
3844 ) {
3845 if self.is_completion_trigger(text, trigger_in_words, cx) {
3846 self.show_completions(
3847 &ShowCompletions {
3848 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3849 },
3850 cx,
3851 );
3852 } else {
3853 self.hide_context_menu(cx);
3854 }
3855 }
3856
3857 fn is_completion_trigger(
3858 &self,
3859 text: &str,
3860 trigger_in_words: bool,
3861 cx: &mut ViewContext<Self>,
3862 ) -> bool {
3863 let position = self.selections.newest_anchor().head();
3864 let multibuffer = self.buffer.read(cx);
3865 let Some(buffer) = position
3866 .buffer_id
3867 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3868 else {
3869 return false;
3870 };
3871
3872 if let Some(completion_provider) = &self.completion_provider {
3873 completion_provider.is_completion_trigger(
3874 &buffer,
3875 position.text_anchor,
3876 text,
3877 trigger_in_words,
3878 cx,
3879 )
3880 } else {
3881 false
3882 }
3883 }
3884
3885 /// If any empty selections is touching the start of its innermost containing autoclose
3886 /// region, expand it to select the brackets.
3887 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3888 let selections = self.selections.all::<usize>(cx);
3889 let buffer = self.buffer.read(cx).read(cx);
3890 let new_selections = self
3891 .selections_with_autoclose_regions(selections, &buffer)
3892 .map(|(mut selection, region)| {
3893 if !selection.is_empty() {
3894 return selection;
3895 }
3896
3897 if let Some(region) = region {
3898 let mut range = region.range.to_offset(&buffer);
3899 if selection.start == range.start && range.start >= region.pair.start.len() {
3900 range.start -= region.pair.start.len();
3901 if buffer.contains_str_at(range.start, ®ion.pair.start)
3902 && buffer.contains_str_at(range.end, ®ion.pair.end)
3903 {
3904 range.end += region.pair.end.len();
3905 selection.start = range.start;
3906 selection.end = range.end;
3907
3908 return selection;
3909 }
3910 }
3911 }
3912
3913 let always_treat_brackets_as_autoclosed = buffer
3914 .settings_at(selection.start, cx)
3915 .always_treat_brackets_as_autoclosed;
3916
3917 if !always_treat_brackets_as_autoclosed {
3918 return selection;
3919 }
3920
3921 if let Some(scope) = buffer.language_scope_at(selection.start) {
3922 for (pair, enabled) in scope.brackets() {
3923 if !enabled || !pair.close {
3924 continue;
3925 }
3926
3927 if buffer.contains_str_at(selection.start, &pair.end) {
3928 let pair_start_len = pair.start.len();
3929 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3930 {
3931 selection.start -= pair_start_len;
3932 selection.end += pair.end.len();
3933
3934 return selection;
3935 }
3936 }
3937 }
3938 }
3939
3940 selection
3941 })
3942 .collect();
3943
3944 drop(buffer);
3945 self.change_selections(None, cx, |selections| selections.select(new_selections));
3946 }
3947
3948 /// Iterate the given selections, and for each one, find the smallest surrounding
3949 /// autoclose region. This uses the ordering of the selections and the autoclose
3950 /// regions to avoid repeated comparisons.
3951 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3952 &'a self,
3953 selections: impl IntoIterator<Item = Selection<D>>,
3954 buffer: &'a MultiBufferSnapshot,
3955 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3956 let mut i = 0;
3957 let mut regions = self.autoclose_regions.as_slice();
3958 selections.into_iter().map(move |selection| {
3959 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3960
3961 let mut enclosing = None;
3962 while let Some(pair_state) = regions.get(i) {
3963 if pair_state.range.end.to_offset(buffer) < range.start {
3964 regions = ®ions[i + 1..];
3965 i = 0;
3966 } else if pair_state.range.start.to_offset(buffer) > range.end {
3967 break;
3968 } else {
3969 if pair_state.selection_id == selection.id {
3970 enclosing = Some(pair_state);
3971 }
3972 i += 1;
3973 }
3974 }
3975
3976 (selection.clone(), enclosing)
3977 })
3978 }
3979
3980 /// Remove any autoclose regions that no longer contain their selection.
3981 fn invalidate_autoclose_regions(
3982 &mut self,
3983 mut selections: &[Selection<Anchor>],
3984 buffer: &MultiBufferSnapshot,
3985 ) {
3986 self.autoclose_regions.retain(|state| {
3987 let mut i = 0;
3988 while let Some(selection) = selections.get(i) {
3989 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3990 selections = &selections[1..];
3991 continue;
3992 }
3993 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3994 break;
3995 }
3996 if selection.id == state.selection_id {
3997 return true;
3998 } else {
3999 i += 1;
4000 }
4001 }
4002 false
4003 });
4004 }
4005
4006 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
4007 let offset = position.to_offset(buffer);
4008 let (word_range, kind) = buffer.surrounding_word(offset, true);
4009 if offset > word_range.start && kind == Some(CharKind::Word) {
4010 Some(
4011 buffer
4012 .text_for_range(word_range.start..offset)
4013 .collect::<String>(),
4014 )
4015 } else {
4016 None
4017 }
4018 }
4019
4020 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
4021 self.refresh_inlay_hints(
4022 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
4023 cx,
4024 );
4025 }
4026
4027 pub fn inlay_hints_enabled(&self) -> bool {
4028 self.inlay_hint_cache.enabled
4029 }
4030
4031 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
4032 if self.project.is_none() || self.mode != EditorMode::Full {
4033 return;
4034 }
4035
4036 let reason_description = reason.description();
4037 let ignore_debounce = matches!(
4038 reason,
4039 InlayHintRefreshReason::SettingsChange(_)
4040 | InlayHintRefreshReason::Toggle(_)
4041 | InlayHintRefreshReason::ExcerptsRemoved(_)
4042 );
4043 let (invalidate_cache, required_languages) = match reason {
4044 InlayHintRefreshReason::Toggle(enabled) => {
4045 self.inlay_hint_cache.enabled = enabled;
4046 if enabled {
4047 (InvalidationStrategy::RefreshRequested, None)
4048 } else {
4049 self.inlay_hint_cache.clear();
4050 self.splice_inlays(
4051 self.visible_inlay_hints(cx)
4052 .iter()
4053 .map(|inlay| inlay.id)
4054 .collect(),
4055 Vec::new(),
4056 cx,
4057 );
4058 return;
4059 }
4060 }
4061 InlayHintRefreshReason::SettingsChange(new_settings) => {
4062 match self.inlay_hint_cache.update_settings(
4063 &self.buffer,
4064 new_settings,
4065 self.visible_inlay_hints(cx),
4066 cx,
4067 ) {
4068 ControlFlow::Break(Some(InlaySplice {
4069 to_remove,
4070 to_insert,
4071 })) => {
4072 self.splice_inlays(to_remove, to_insert, cx);
4073 return;
4074 }
4075 ControlFlow::Break(None) => return,
4076 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4077 }
4078 }
4079 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4080 if let Some(InlaySplice {
4081 to_remove,
4082 to_insert,
4083 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4084 {
4085 self.splice_inlays(to_remove, to_insert, cx);
4086 }
4087 return;
4088 }
4089 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4090 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4091 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4092 }
4093 InlayHintRefreshReason::RefreshRequested => {
4094 (InvalidationStrategy::RefreshRequested, None)
4095 }
4096 };
4097
4098 if let Some(InlaySplice {
4099 to_remove,
4100 to_insert,
4101 }) = self.inlay_hint_cache.spawn_hint_refresh(
4102 reason_description,
4103 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4104 invalidate_cache,
4105 ignore_debounce,
4106 cx,
4107 ) {
4108 self.splice_inlays(to_remove, to_insert, cx);
4109 }
4110 }
4111
4112 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4113 self.display_map
4114 .read(cx)
4115 .current_inlays()
4116 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4117 .cloned()
4118 .collect()
4119 }
4120
4121 pub fn excerpts_for_inlay_hints_query(
4122 &self,
4123 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4124 cx: &mut ViewContext<Editor>,
4125 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4126 let Some(project) = self.project.as_ref() else {
4127 return HashMap::default();
4128 };
4129 let project = project.read(cx);
4130 let multi_buffer = self.buffer().read(cx);
4131 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4132 let multi_buffer_visible_start = self
4133 .scroll_manager
4134 .anchor()
4135 .anchor
4136 .to_point(&multi_buffer_snapshot);
4137 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4138 multi_buffer_visible_start
4139 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4140 Bias::Left,
4141 );
4142 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4143 multi_buffer
4144 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4145 .into_iter()
4146 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4147 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4148 let buffer = buffer_handle.read(cx);
4149 let buffer_file = project::File::from_dyn(buffer.file())?;
4150 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4151 let worktree_entry = buffer_worktree
4152 .read(cx)
4153 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4154 if worktree_entry.is_ignored {
4155 return None;
4156 }
4157
4158 let language = buffer.language()?;
4159 if let Some(restrict_to_languages) = restrict_to_languages {
4160 if !restrict_to_languages.contains(language) {
4161 return None;
4162 }
4163 }
4164 Some((
4165 excerpt_id,
4166 (
4167 buffer_handle,
4168 buffer.version().clone(),
4169 excerpt_visible_range,
4170 ),
4171 ))
4172 })
4173 .collect()
4174 }
4175
4176 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4177 TextLayoutDetails {
4178 text_system: cx.text_system().clone(),
4179 editor_style: self.style.clone().unwrap(),
4180 rem_size: cx.rem_size(),
4181 scroll_anchor: self.scroll_manager.anchor(),
4182 visible_rows: self.visible_line_count(),
4183 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4184 }
4185 }
4186
4187 fn splice_inlays(
4188 &self,
4189 to_remove: Vec<InlayId>,
4190 to_insert: Vec<Inlay>,
4191 cx: &mut ViewContext<Self>,
4192 ) {
4193 self.display_map.update(cx, |display_map, cx| {
4194 display_map.splice_inlays(to_remove, to_insert, cx);
4195 });
4196 cx.notify();
4197 }
4198
4199 fn trigger_on_type_formatting(
4200 &self,
4201 input: String,
4202 cx: &mut ViewContext<Self>,
4203 ) -> Option<Task<Result<()>>> {
4204 if input.len() != 1 {
4205 return None;
4206 }
4207
4208 let project = self.project.as_ref()?;
4209 let position = self.selections.newest_anchor().head();
4210 let (buffer, buffer_position) = self
4211 .buffer
4212 .read(cx)
4213 .text_anchor_for_position(position, cx)?;
4214
4215 let settings = language_settings::language_settings(
4216 buffer.read(cx).language_at(buffer_position).as_ref(),
4217 buffer.read(cx).file(),
4218 cx,
4219 );
4220 if !settings.use_on_type_format {
4221 return None;
4222 }
4223
4224 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4225 // hence we do LSP request & edit on host side only — add formats to host's history.
4226 let push_to_lsp_host_history = true;
4227 // If this is not the host, append its history with new edits.
4228 let push_to_client_history = project.read(cx).is_via_collab();
4229
4230 let on_type_formatting = project.update(cx, |project, cx| {
4231 project.on_type_format(
4232 buffer.clone(),
4233 buffer_position,
4234 input,
4235 push_to_lsp_host_history,
4236 cx,
4237 )
4238 });
4239 Some(cx.spawn(|editor, mut cx| async move {
4240 if let Some(transaction) = on_type_formatting.await? {
4241 if push_to_client_history {
4242 buffer
4243 .update(&mut cx, |buffer, _| {
4244 buffer.push_transaction(transaction, Instant::now());
4245 })
4246 .ok();
4247 }
4248 editor.update(&mut cx, |editor, cx| {
4249 editor.refresh_document_highlights(cx);
4250 })?;
4251 }
4252 Ok(())
4253 }))
4254 }
4255
4256 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4257 if self.pending_rename.is_some() {
4258 return;
4259 }
4260
4261 let Some(provider) = self.completion_provider.as_ref() else {
4262 return;
4263 };
4264
4265 let position = self.selections.newest_anchor().head();
4266 let (buffer, buffer_position) =
4267 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4268 output
4269 } else {
4270 return;
4271 };
4272
4273 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4274 let is_followup_invoke = {
4275 let context_menu_state = self.context_menu.read();
4276 matches!(
4277 context_menu_state.deref(),
4278 Some(ContextMenu::Completions(_))
4279 )
4280 };
4281 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4282 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4283 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4284 CompletionTriggerKind::TRIGGER_CHARACTER
4285 }
4286
4287 _ => CompletionTriggerKind::INVOKED,
4288 };
4289 let completion_context = CompletionContext {
4290 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4291 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4292 Some(String::from(trigger))
4293 } else {
4294 None
4295 }
4296 }),
4297 trigger_kind,
4298 };
4299 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4300 let sort_completions = provider.sort_completions();
4301
4302 let id = post_inc(&mut self.next_completion_id);
4303 let task = cx.spawn(|this, mut cx| {
4304 async move {
4305 this.update(&mut cx, |this, _| {
4306 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4307 })?;
4308 let completions = completions.await.log_err();
4309 let menu = if let Some(completions) = completions {
4310 let mut menu = CompletionsMenu {
4311 id,
4312 sort_completions,
4313 initial_position: position,
4314 match_candidates: completions
4315 .iter()
4316 .enumerate()
4317 .map(|(id, completion)| {
4318 StringMatchCandidate::new(
4319 id,
4320 completion.label.text[completion.label.filter_range.clone()]
4321 .into(),
4322 )
4323 })
4324 .collect(),
4325 buffer: buffer.clone(),
4326 completions: Arc::new(RwLock::new(completions.into())),
4327 matches: Vec::new().into(),
4328 selected_item: 0,
4329 scroll_handle: UniformListScrollHandle::new(),
4330 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4331 DebouncedDelay::new(),
4332 )),
4333 };
4334 menu.filter(query.as_deref(), cx.background_executor().clone())
4335 .await;
4336
4337 if menu.matches.is_empty() {
4338 None
4339 } else {
4340 this.update(&mut cx, |editor, cx| {
4341 let completions = menu.completions.clone();
4342 let matches = menu.matches.clone();
4343
4344 let delay_ms = EditorSettings::get_global(cx)
4345 .completion_documentation_secondary_query_debounce;
4346 let delay = Duration::from_millis(delay_ms);
4347 editor
4348 .completion_documentation_pre_resolve_debounce
4349 .fire_new(delay, cx, |editor, cx| {
4350 CompletionsMenu::pre_resolve_completion_documentation(
4351 buffer,
4352 completions,
4353 matches,
4354 editor,
4355 cx,
4356 )
4357 });
4358 })
4359 .ok();
4360 Some(menu)
4361 }
4362 } else {
4363 None
4364 };
4365
4366 this.update(&mut cx, |this, cx| {
4367 let mut context_menu = this.context_menu.write();
4368 match context_menu.as_ref() {
4369 None => {}
4370
4371 Some(ContextMenu::Completions(prev_menu)) => {
4372 if prev_menu.id > id {
4373 return;
4374 }
4375 }
4376
4377 _ => return,
4378 }
4379
4380 if this.focus_handle.is_focused(cx) && menu.is_some() {
4381 let menu = menu.unwrap();
4382 *context_menu = Some(ContextMenu::Completions(menu));
4383 drop(context_menu);
4384 this.discard_inline_completion(false, cx);
4385 cx.notify();
4386 } else if this.completion_tasks.len() <= 1 {
4387 // If there are no more completion tasks and the last menu was
4388 // empty, we should hide it. If it was already hidden, we should
4389 // also show the copilot completion when available.
4390 drop(context_menu);
4391 if this.hide_context_menu(cx).is_none() {
4392 this.update_visible_inline_completion(cx);
4393 }
4394 }
4395 })?;
4396
4397 Ok::<_, anyhow::Error>(())
4398 }
4399 .log_err()
4400 });
4401
4402 self.completion_tasks.push((id, task));
4403 }
4404
4405 pub fn confirm_completion(
4406 &mut self,
4407 action: &ConfirmCompletion,
4408 cx: &mut ViewContext<Self>,
4409 ) -> Option<Task<Result<()>>> {
4410 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4411 }
4412
4413 pub fn compose_completion(
4414 &mut self,
4415 action: &ComposeCompletion,
4416 cx: &mut ViewContext<Self>,
4417 ) -> Option<Task<Result<()>>> {
4418 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4419 }
4420
4421 fn do_completion(
4422 &mut self,
4423 item_ix: Option<usize>,
4424 intent: CompletionIntent,
4425 cx: &mut ViewContext<Editor>,
4426 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4427 use language::ToOffset as _;
4428
4429 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4430 menu
4431 } else {
4432 return None;
4433 };
4434
4435 let mat = completions_menu
4436 .matches
4437 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4438 let buffer_handle = completions_menu.buffer;
4439 let completions = completions_menu.completions.read();
4440 let completion = completions.get(mat.candidate_id)?;
4441 cx.stop_propagation();
4442
4443 let snippet;
4444 let text;
4445
4446 if completion.is_snippet() {
4447 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4448 text = snippet.as_ref().unwrap().text.clone();
4449 } else {
4450 snippet = None;
4451 text = completion.new_text.clone();
4452 };
4453 let selections = self.selections.all::<usize>(cx);
4454 let buffer = buffer_handle.read(cx);
4455 let old_range = completion.old_range.to_offset(buffer);
4456 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4457
4458 let newest_selection = self.selections.newest_anchor();
4459 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4460 return None;
4461 }
4462
4463 let lookbehind = newest_selection
4464 .start
4465 .text_anchor
4466 .to_offset(buffer)
4467 .saturating_sub(old_range.start);
4468 let lookahead = old_range
4469 .end
4470 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4471 let mut common_prefix_len = old_text
4472 .bytes()
4473 .zip(text.bytes())
4474 .take_while(|(a, b)| a == b)
4475 .count();
4476
4477 let snapshot = self.buffer.read(cx).snapshot(cx);
4478 let mut range_to_replace: Option<Range<isize>> = None;
4479 let mut ranges = Vec::new();
4480 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4481 for selection in &selections {
4482 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4483 let start = selection.start.saturating_sub(lookbehind);
4484 let end = selection.end + lookahead;
4485 if selection.id == newest_selection.id {
4486 range_to_replace = Some(
4487 ((start + common_prefix_len) as isize - selection.start as isize)
4488 ..(end as isize - selection.start as isize),
4489 );
4490 }
4491 ranges.push(start + common_prefix_len..end);
4492 } else {
4493 common_prefix_len = 0;
4494 ranges.clear();
4495 ranges.extend(selections.iter().map(|s| {
4496 if s.id == newest_selection.id {
4497 range_to_replace = Some(
4498 old_range.start.to_offset_utf16(&snapshot).0 as isize
4499 - selection.start as isize
4500 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4501 - selection.start as isize,
4502 );
4503 old_range.clone()
4504 } else {
4505 s.start..s.end
4506 }
4507 }));
4508 break;
4509 }
4510 if !self.linked_edit_ranges.is_empty() {
4511 let start_anchor = snapshot.anchor_before(selection.head());
4512 let end_anchor = snapshot.anchor_after(selection.tail());
4513 if let Some(ranges) = self
4514 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4515 {
4516 for (buffer, edits) in ranges {
4517 linked_edits.entry(buffer.clone()).or_default().extend(
4518 edits
4519 .into_iter()
4520 .map(|range| (range, text[common_prefix_len..].to_owned())),
4521 );
4522 }
4523 }
4524 }
4525 }
4526 let text = &text[common_prefix_len..];
4527
4528 cx.emit(EditorEvent::InputHandled {
4529 utf16_range_to_replace: range_to_replace,
4530 text: text.into(),
4531 });
4532
4533 self.transact(cx, |this, cx| {
4534 if let Some(mut snippet) = snippet {
4535 snippet.text = text.to_string();
4536 for tabstop in snippet.tabstops.iter_mut().flatten() {
4537 tabstop.start -= common_prefix_len as isize;
4538 tabstop.end -= common_prefix_len as isize;
4539 }
4540
4541 this.insert_snippet(&ranges, snippet, cx).log_err();
4542 } else {
4543 this.buffer.update(cx, |buffer, cx| {
4544 buffer.edit(
4545 ranges.iter().map(|range| (range.clone(), text)),
4546 this.autoindent_mode.clone(),
4547 cx,
4548 );
4549 });
4550 }
4551 for (buffer, edits) in linked_edits {
4552 buffer.update(cx, |buffer, cx| {
4553 let snapshot = buffer.snapshot();
4554 let edits = edits
4555 .into_iter()
4556 .map(|(range, text)| {
4557 use text::ToPoint as TP;
4558 let end_point = TP::to_point(&range.end, &snapshot);
4559 let start_point = TP::to_point(&range.start, &snapshot);
4560 (start_point..end_point, text)
4561 })
4562 .sorted_by_key(|(range, _)| range.start)
4563 .collect::<Vec<_>>();
4564 buffer.edit(edits, None, cx);
4565 })
4566 }
4567
4568 this.refresh_inline_completion(true, false, cx);
4569 });
4570
4571 let show_new_completions_on_confirm = completion
4572 .confirm
4573 .as_ref()
4574 .map_or(false, |confirm| confirm(intent, cx));
4575 if show_new_completions_on_confirm {
4576 self.show_completions(&ShowCompletions { trigger: None }, cx);
4577 }
4578
4579 let provider = self.completion_provider.as_ref()?;
4580 let apply_edits = provider.apply_additional_edits_for_completion(
4581 buffer_handle,
4582 completion.clone(),
4583 true,
4584 cx,
4585 );
4586
4587 let editor_settings = EditorSettings::get_global(cx);
4588 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4589 // After the code completion is finished, users often want to know what signatures are needed.
4590 // so we should automatically call signature_help
4591 self.show_signature_help(&ShowSignatureHelp, cx);
4592 }
4593
4594 Some(cx.foreground_executor().spawn(async move {
4595 apply_edits.await?;
4596 Ok(())
4597 }))
4598 }
4599
4600 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4601 let mut context_menu = self.context_menu.write();
4602 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4603 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4604 // Toggle if we're selecting the same one
4605 *context_menu = None;
4606 cx.notify();
4607 return;
4608 } else {
4609 // Otherwise, clear it and start a new one
4610 *context_menu = None;
4611 cx.notify();
4612 }
4613 }
4614 drop(context_menu);
4615 let snapshot = self.snapshot(cx);
4616 let deployed_from_indicator = action.deployed_from_indicator;
4617 let mut task = self.code_actions_task.take();
4618 let action = action.clone();
4619 cx.spawn(|editor, mut cx| async move {
4620 while let Some(prev_task) = task {
4621 prev_task.await.log_err();
4622 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4623 }
4624
4625 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4626 if editor.focus_handle.is_focused(cx) {
4627 let multibuffer_point = action
4628 .deployed_from_indicator
4629 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4630 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4631 let (buffer, buffer_row) = snapshot
4632 .buffer_snapshot
4633 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4634 .and_then(|(buffer_snapshot, range)| {
4635 editor
4636 .buffer
4637 .read(cx)
4638 .buffer(buffer_snapshot.remote_id())
4639 .map(|buffer| (buffer, range.start.row))
4640 })?;
4641 let (_, code_actions) = editor
4642 .available_code_actions
4643 .clone()
4644 .and_then(|(location, code_actions)| {
4645 let snapshot = location.buffer.read(cx).snapshot();
4646 let point_range = location.range.to_point(&snapshot);
4647 let point_range = point_range.start.row..=point_range.end.row;
4648 if point_range.contains(&buffer_row) {
4649 Some((location, code_actions))
4650 } else {
4651 None
4652 }
4653 })
4654 .unzip();
4655 let buffer_id = buffer.read(cx).remote_id();
4656 let tasks = editor
4657 .tasks
4658 .get(&(buffer_id, buffer_row))
4659 .map(|t| Arc::new(t.to_owned()));
4660 if tasks.is_none() && code_actions.is_none() {
4661 return None;
4662 }
4663
4664 editor.completion_tasks.clear();
4665 editor.discard_inline_completion(false, cx);
4666 let task_context =
4667 tasks
4668 .as_ref()
4669 .zip(editor.project.clone())
4670 .map(|(tasks, project)| {
4671 let position = Point::new(buffer_row, tasks.column);
4672 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4673 let location = Location {
4674 buffer: buffer.clone(),
4675 range: range_start..range_start,
4676 };
4677 // Fill in the environmental variables from the tree-sitter captures
4678 let mut captured_task_variables = TaskVariables::default();
4679 for (capture_name, value) in tasks.extra_variables.clone() {
4680 captured_task_variables.insert(
4681 task::VariableName::Custom(capture_name.into()),
4682 value.clone(),
4683 );
4684 }
4685 project.update(cx, |project, cx| {
4686 project.task_context_for_location(
4687 captured_task_variables,
4688 location,
4689 cx,
4690 )
4691 })
4692 });
4693
4694 Some(cx.spawn(|editor, mut cx| async move {
4695 let task_context = match task_context {
4696 Some(task_context) => task_context.await,
4697 None => None,
4698 };
4699 let resolved_tasks =
4700 tasks.zip(task_context).map(|(tasks, task_context)| {
4701 Arc::new(ResolvedTasks {
4702 templates: tasks
4703 .templates
4704 .iter()
4705 .filter_map(|(kind, template)| {
4706 template
4707 .resolve_task(&kind.to_id_base(), &task_context)
4708 .map(|task| (kind.clone(), task))
4709 })
4710 .collect(),
4711 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4712 multibuffer_point.row,
4713 tasks.column,
4714 )),
4715 })
4716 });
4717 let spawn_straight_away = resolved_tasks
4718 .as_ref()
4719 .map_or(false, |tasks| tasks.templates.len() == 1)
4720 && code_actions
4721 .as_ref()
4722 .map_or(true, |actions| actions.is_empty());
4723 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4724 *editor.context_menu.write() =
4725 Some(ContextMenu::CodeActions(CodeActionsMenu {
4726 buffer,
4727 actions: CodeActionContents {
4728 tasks: resolved_tasks,
4729 actions: code_actions,
4730 },
4731 selected_item: Default::default(),
4732 scroll_handle: UniformListScrollHandle::default(),
4733 deployed_from_indicator,
4734 }));
4735 if spawn_straight_away {
4736 if let Some(task) = editor.confirm_code_action(
4737 &ConfirmCodeAction { item_ix: Some(0) },
4738 cx,
4739 ) {
4740 cx.notify();
4741 return task;
4742 }
4743 }
4744 cx.notify();
4745 Task::ready(Ok(()))
4746 }) {
4747 task.await
4748 } else {
4749 Ok(())
4750 }
4751 }))
4752 } else {
4753 Some(Task::ready(Ok(())))
4754 }
4755 })?;
4756 if let Some(task) = spawned_test_task {
4757 task.await?;
4758 }
4759
4760 Ok::<_, anyhow::Error>(())
4761 })
4762 .detach_and_log_err(cx);
4763 }
4764
4765 pub fn confirm_code_action(
4766 &mut self,
4767 action: &ConfirmCodeAction,
4768 cx: &mut ViewContext<Self>,
4769 ) -> Option<Task<Result<()>>> {
4770 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4771 menu
4772 } else {
4773 return None;
4774 };
4775 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4776 let action = actions_menu.actions.get(action_ix)?;
4777 let title = action.label();
4778 let buffer = actions_menu.buffer;
4779 let workspace = self.workspace()?;
4780
4781 match action {
4782 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4783 workspace.update(cx, |workspace, cx| {
4784 workspace::tasks::schedule_resolved_task(
4785 workspace,
4786 task_source_kind,
4787 resolved_task,
4788 false,
4789 cx,
4790 );
4791
4792 Some(Task::ready(Ok(())))
4793 })
4794 }
4795 CodeActionsItem::CodeAction {
4796 excerpt_id,
4797 action,
4798 provider,
4799 } => {
4800 let apply_code_action =
4801 provider.apply_code_action(buffer, action, excerpt_id, true, cx);
4802 let workspace = workspace.downgrade();
4803 Some(cx.spawn(|editor, cx| async move {
4804 let project_transaction = apply_code_action.await?;
4805 Self::open_project_transaction(
4806 &editor,
4807 workspace,
4808 project_transaction,
4809 title,
4810 cx,
4811 )
4812 .await
4813 }))
4814 }
4815 }
4816 }
4817
4818 pub async fn open_project_transaction(
4819 this: &WeakView<Editor>,
4820 workspace: WeakView<Workspace>,
4821 transaction: ProjectTransaction,
4822 title: String,
4823 mut cx: AsyncWindowContext,
4824 ) -> Result<()> {
4825 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4826 cx.update(|cx| {
4827 entries.sort_unstable_by_key(|(buffer, _)| {
4828 buffer.read(cx).file().map(|f| f.path().clone())
4829 });
4830 })?;
4831
4832 // If the project transaction's edits are all contained within this editor, then
4833 // avoid opening a new editor to display them.
4834
4835 if let Some((buffer, transaction)) = entries.first() {
4836 if entries.len() == 1 {
4837 let excerpt = this.update(&mut cx, |editor, cx| {
4838 editor
4839 .buffer()
4840 .read(cx)
4841 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4842 })?;
4843 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4844 if excerpted_buffer == *buffer {
4845 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4846 let excerpt_range = excerpt_range.to_offset(buffer);
4847 buffer
4848 .edited_ranges_for_transaction::<usize>(transaction)
4849 .all(|range| {
4850 excerpt_range.start <= range.start
4851 && excerpt_range.end >= range.end
4852 })
4853 })?;
4854
4855 if all_edits_within_excerpt {
4856 return Ok(());
4857 }
4858 }
4859 }
4860 }
4861 } else {
4862 return Ok(());
4863 }
4864
4865 let mut ranges_to_highlight = Vec::new();
4866 let excerpt_buffer = cx.new_model(|cx| {
4867 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4868 for (buffer_handle, transaction) in &entries {
4869 let buffer = buffer_handle.read(cx);
4870 ranges_to_highlight.extend(
4871 multibuffer.push_excerpts_with_context_lines(
4872 buffer_handle.clone(),
4873 buffer
4874 .edited_ranges_for_transaction::<usize>(transaction)
4875 .collect(),
4876 DEFAULT_MULTIBUFFER_CONTEXT,
4877 cx,
4878 ),
4879 );
4880 }
4881 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4882 multibuffer
4883 })?;
4884
4885 workspace.update(&mut cx, |workspace, cx| {
4886 let project = workspace.project().clone();
4887 let editor =
4888 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4889 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4890 editor.update(cx, |editor, cx| {
4891 editor.highlight_background::<Self>(
4892 &ranges_to_highlight,
4893 |theme| theme.editor_highlighted_line_background,
4894 cx,
4895 );
4896 });
4897 })?;
4898
4899 Ok(())
4900 }
4901
4902 pub fn push_code_action_provider(
4903 &mut self,
4904 provider: Arc<dyn CodeActionProvider>,
4905 cx: &mut ViewContext<Self>,
4906 ) {
4907 self.code_action_providers.push(provider);
4908 self.refresh_code_actions(cx);
4909 }
4910
4911 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4912 let buffer = self.buffer.read(cx);
4913 let newest_selection = self.selections.newest_anchor().clone();
4914 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4915 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4916 if start_buffer != end_buffer {
4917 return None;
4918 }
4919
4920 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4921 cx.background_executor()
4922 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4923 .await;
4924
4925 let (providers, tasks) = this.update(&mut cx, |this, cx| {
4926 let providers = this.code_action_providers.clone();
4927 let tasks = this
4928 .code_action_providers
4929 .iter()
4930 .map(|provider| provider.code_actions(&start_buffer, start..end, cx))
4931 .collect::<Vec<_>>();
4932 (providers, tasks)
4933 })?;
4934
4935 let mut actions = Vec::new();
4936 for (provider, provider_actions) in
4937 providers.into_iter().zip(future::join_all(tasks).await)
4938 {
4939 if let Some(provider_actions) = provider_actions.log_err() {
4940 actions.extend(provider_actions.into_iter().map(|action| {
4941 AvailableCodeAction {
4942 excerpt_id: newest_selection.start.excerpt_id,
4943 action,
4944 provider: provider.clone(),
4945 }
4946 }));
4947 }
4948 }
4949
4950 this.update(&mut cx, |this, cx| {
4951 this.available_code_actions = if actions.is_empty() {
4952 None
4953 } else {
4954 Some((
4955 Location {
4956 buffer: start_buffer,
4957 range: start..end,
4958 },
4959 actions.into(),
4960 ))
4961 };
4962 cx.notify();
4963 })
4964 }));
4965 None
4966 }
4967
4968 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4969 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4970 self.show_git_blame_inline = false;
4971
4972 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4973 cx.background_executor().timer(delay).await;
4974
4975 this.update(&mut cx, |this, cx| {
4976 this.show_git_blame_inline = true;
4977 cx.notify();
4978 })
4979 .log_err();
4980 }));
4981 }
4982 }
4983
4984 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4985 if self.pending_rename.is_some() {
4986 return None;
4987 }
4988
4989 let project = self.project.clone()?;
4990 let buffer = self.buffer.read(cx);
4991 let newest_selection = self.selections.newest_anchor().clone();
4992 let cursor_position = newest_selection.head();
4993 let (cursor_buffer, cursor_buffer_position) =
4994 buffer.text_anchor_for_position(cursor_position, cx)?;
4995 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4996 if cursor_buffer != tail_buffer {
4997 return None;
4998 }
4999
5000 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
5001 cx.background_executor()
5002 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
5003 .await;
5004
5005 let highlights = if let Some(highlights) = project
5006 .update(&mut cx, |project, cx| {
5007 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
5008 })
5009 .log_err()
5010 {
5011 highlights.await.log_err()
5012 } else {
5013 None
5014 };
5015
5016 if let Some(highlights) = highlights {
5017 this.update(&mut cx, |this, cx| {
5018 if this.pending_rename.is_some() {
5019 return;
5020 }
5021
5022 let buffer_id = cursor_position.buffer_id;
5023 let buffer = this.buffer.read(cx);
5024 if !buffer
5025 .text_anchor_for_position(cursor_position, cx)
5026 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
5027 {
5028 return;
5029 }
5030
5031 let cursor_buffer_snapshot = cursor_buffer.read(cx);
5032 let mut write_ranges = Vec::new();
5033 let mut read_ranges = Vec::new();
5034 for highlight in highlights {
5035 for (excerpt_id, excerpt_range) in
5036 buffer.excerpts_for_buffer(&cursor_buffer, cx)
5037 {
5038 let start = highlight
5039 .range
5040 .start
5041 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
5042 let end = highlight
5043 .range
5044 .end
5045 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
5046 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
5047 continue;
5048 }
5049
5050 let range = Anchor {
5051 buffer_id,
5052 excerpt_id,
5053 text_anchor: start,
5054 }..Anchor {
5055 buffer_id,
5056 excerpt_id,
5057 text_anchor: end,
5058 };
5059 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
5060 write_ranges.push(range);
5061 } else {
5062 read_ranges.push(range);
5063 }
5064 }
5065 }
5066
5067 this.highlight_background::<DocumentHighlightRead>(
5068 &read_ranges,
5069 |theme| theme.editor_document_highlight_read_background,
5070 cx,
5071 );
5072 this.highlight_background::<DocumentHighlightWrite>(
5073 &write_ranges,
5074 |theme| theme.editor_document_highlight_write_background,
5075 cx,
5076 );
5077 cx.notify();
5078 })
5079 .log_err();
5080 }
5081 }));
5082 None
5083 }
5084
5085 pub fn refresh_inline_completion(
5086 &mut self,
5087 debounce: bool,
5088 user_requested: bool,
5089 cx: &mut ViewContext<Self>,
5090 ) -> Option<()> {
5091 let provider = self.inline_completion_provider()?;
5092 let cursor = self.selections.newest_anchor().head();
5093 let (buffer, cursor_buffer_position) =
5094 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5095
5096 if !user_requested
5097 && (!self.enable_inline_completions
5098 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5099 {
5100 self.discard_inline_completion(false, cx);
5101 return None;
5102 }
5103
5104 self.update_visible_inline_completion(cx);
5105 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5106 Some(())
5107 }
5108
5109 fn cycle_inline_completion(
5110 &mut self,
5111 direction: Direction,
5112 cx: &mut ViewContext<Self>,
5113 ) -> Option<()> {
5114 let provider = self.inline_completion_provider()?;
5115 let cursor = self.selections.newest_anchor().head();
5116 let (buffer, cursor_buffer_position) =
5117 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5118 if !self.enable_inline_completions
5119 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5120 {
5121 return None;
5122 }
5123
5124 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5125 self.update_visible_inline_completion(cx);
5126
5127 Some(())
5128 }
5129
5130 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5131 if !self.has_active_inline_completion(cx) {
5132 self.refresh_inline_completion(false, true, cx);
5133 return;
5134 }
5135
5136 self.update_visible_inline_completion(cx);
5137 }
5138
5139 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5140 self.show_cursor_names(cx);
5141 }
5142
5143 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5144 self.show_cursor_names = true;
5145 cx.notify();
5146 cx.spawn(|this, mut cx| async move {
5147 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5148 this.update(&mut cx, |this, cx| {
5149 this.show_cursor_names = false;
5150 cx.notify()
5151 })
5152 .ok()
5153 })
5154 .detach();
5155 }
5156
5157 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5158 if self.has_active_inline_completion(cx) {
5159 self.cycle_inline_completion(Direction::Next, cx);
5160 } else {
5161 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5162 if is_copilot_disabled {
5163 cx.propagate();
5164 }
5165 }
5166 }
5167
5168 pub fn previous_inline_completion(
5169 &mut self,
5170 _: &PreviousInlineCompletion,
5171 cx: &mut ViewContext<Self>,
5172 ) {
5173 if self.has_active_inline_completion(cx) {
5174 self.cycle_inline_completion(Direction::Prev, cx);
5175 } else {
5176 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5177 if is_copilot_disabled {
5178 cx.propagate();
5179 }
5180 }
5181 }
5182
5183 pub fn accept_inline_completion(
5184 &mut self,
5185 _: &AcceptInlineCompletion,
5186 cx: &mut ViewContext<Self>,
5187 ) {
5188 let Some(completion) = self.take_active_inline_completion(cx) else {
5189 return;
5190 };
5191 if let Some(provider) = self.inline_completion_provider() {
5192 provider.accept(cx);
5193 }
5194
5195 cx.emit(EditorEvent::InputHandled {
5196 utf16_range_to_replace: None,
5197 text: completion.text.to_string().into(),
5198 });
5199
5200 if let Some(range) = completion.delete_range {
5201 self.change_selections(None, cx, |s| s.select_ranges([range]))
5202 }
5203 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5204 self.refresh_inline_completion(true, true, cx);
5205 cx.notify();
5206 }
5207
5208 pub fn accept_partial_inline_completion(
5209 &mut self,
5210 _: &AcceptPartialInlineCompletion,
5211 cx: &mut ViewContext<Self>,
5212 ) {
5213 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5214 if let Some(completion) = self.take_active_inline_completion(cx) {
5215 let mut partial_completion = completion
5216 .text
5217 .chars()
5218 .by_ref()
5219 .take_while(|c| c.is_alphabetic())
5220 .collect::<String>();
5221 if partial_completion.is_empty() {
5222 partial_completion = completion
5223 .text
5224 .chars()
5225 .by_ref()
5226 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5227 .collect::<String>();
5228 }
5229
5230 cx.emit(EditorEvent::InputHandled {
5231 utf16_range_to_replace: None,
5232 text: partial_completion.clone().into(),
5233 });
5234
5235 if let Some(range) = completion.delete_range {
5236 self.change_selections(None, cx, |s| s.select_ranges([range]))
5237 }
5238 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5239
5240 self.refresh_inline_completion(true, true, cx);
5241 cx.notify();
5242 }
5243 }
5244 }
5245
5246 fn discard_inline_completion(
5247 &mut self,
5248 should_report_inline_completion_event: bool,
5249 cx: &mut ViewContext<Self>,
5250 ) -> bool {
5251 if let Some(provider) = self.inline_completion_provider() {
5252 provider.discard(should_report_inline_completion_event, cx);
5253 }
5254
5255 self.take_active_inline_completion(cx).is_some()
5256 }
5257
5258 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5259 if let Some(completion) = self.active_inline_completion.as_ref() {
5260 let buffer = self.buffer.read(cx).read(cx);
5261 completion.position.is_valid(&buffer)
5262 } else {
5263 false
5264 }
5265 }
5266
5267 fn take_active_inline_completion(
5268 &mut self,
5269 cx: &mut ViewContext<Self>,
5270 ) -> Option<CompletionState> {
5271 let completion = self.active_inline_completion.take()?;
5272 let render_inlay_ids = completion.render_inlay_ids.clone();
5273 self.display_map.update(cx, |map, cx| {
5274 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5275 });
5276 let buffer = self.buffer.read(cx).read(cx);
5277
5278 if completion.position.is_valid(&buffer) {
5279 Some(completion)
5280 } else {
5281 None
5282 }
5283 }
5284
5285 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5286 let selection = self.selections.newest_anchor();
5287 let cursor = selection.head();
5288
5289 let excerpt_id = cursor.excerpt_id;
5290
5291 if self.context_menu.read().is_none()
5292 && self.completion_tasks.is_empty()
5293 && selection.start == selection.end
5294 {
5295 if let Some(provider) = self.inline_completion_provider() {
5296 if let Some((buffer, cursor_buffer_position)) =
5297 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5298 {
5299 if let Some(proposal) =
5300 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5301 {
5302 let mut to_remove = Vec::new();
5303 if let Some(completion) = self.active_inline_completion.take() {
5304 to_remove.extend(completion.render_inlay_ids.iter());
5305 }
5306
5307 let to_add = proposal
5308 .inlays
5309 .iter()
5310 .filter_map(|inlay| {
5311 let snapshot = self.buffer.read(cx).snapshot(cx);
5312 let id = post_inc(&mut self.next_inlay_id);
5313 match inlay {
5314 InlayProposal::Hint(position, hint) => {
5315 let position =
5316 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5317 Some(Inlay::hint(id, position, hint))
5318 }
5319 InlayProposal::Suggestion(position, text) => {
5320 let position =
5321 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5322 Some(Inlay::suggestion(id, position, text.clone()))
5323 }
5324 }
5325 })
5326 .collect_vec();
5327
5328 self.active_inline_completion = Some(CompletionState {
5329 position: cursor,
5330 text: proposal.text,
5331 delete_range: proposal.delete_range.and_then(|range| {
5332 let snapshot = self.buffer.read(cx).snapshot(cx);
5333 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5334 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5335 Some(start?..end?)
5336 }),
5337 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5338 });
5339
5340 self.display_map
5341 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5342
5343 cx.notify();
5344 return;
5345 }
5346 }
5347 }
5348 }
5349
5350 self.discard_inline_completion(false, cx);
5351 }
5352
5353 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5354 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5355 }
5356
5357 fn render_code_actions_indicator(
5358 &self,
5359 _style: &EditorStyle,
5360 row: DisplayRow,
5361 is_active: bool,
5362 cx: &mut ViewContext<Self>,
5363 ) -> Option<IconButton> {
5364 if self.available_code_actions.is_some() {
5365 Some(
5366 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5367 .shape(ui::IconButtonShape::Square)
5368 .icon_size(IconSize::XSmall)
5369 .icon_color(Color::Muted)
5370 .selected(is_active)
5371 .tooltip({
5372 let focus_handle = self.focus_handle.clone();
5373 move |cx| {
5374 Tooltip::for_action_in(
5375 "Toggle Code Actions",
5376 &ToggleCodeActions {
5377 deployed_from_indicator: None,
5378 },
5379 &focus_handle,
5380 cx,
5381 )
5382 }
5383 })
5384 .on_click(cx.listener(move |editor, _e, cx| {
5385 editor.focus(cx);
5386 editor.toggle_code_actions(
5387 &ToggleCodeActions {
5388 deployed_from_indicator: Some(row),
5389 },
5390 cx,
5391 );
5392 })),
5393 )
5394 } else {
5395 None
5396 }
5397 }
5398
5399 fn clear_tasks(&mut self) {
5400 self.tasks.clear()
5401 }
5402
5403 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5404 if self.tasks.insert(key, value).is_some() {
5405 // This case should hopefully be rare, but just in case...
5406 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5407 }
5408 }
5409
5410 fn render_run_indicator(
5411 &self,
5412 _style: &EditorStyle,
5413 is_active: bool,
5414 row: DisplayRow,
5415 cx: &mut ViewContext<Self>,
5416 ) -> IconButton {
5417 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5418 .shape(ui::IconButtonShape::Square)
5419 .icon_size(IconSize::XSmall)
5420 .icon_color(Color::Muted)
5421 .selected(is_active)
5422 .on_click(cx.listener(move |editor, _e, cx| {
5423 editor.focus(cx);
5424 editor.toggle_code_actions(
5425 &ToggleCodeActions {
5426 deployed_from_indicator: Some(row),
5427 },
5428 cx,
5429 );
5430 }))
5431 }
5432
5433 pub fn context_menu_visible(&self) -> bool {
5434 self.context_menu
5435 .read()
5436 .as_ref()
5437 .map_or(false, |menu| menu.visible())
5438 }
5439
5440 fn render_context_menu(
5441 &self,
5442 cursor_position: DisplayPoint,
5443 style: &EditorStyle,
5444 max_height: Pixels,
5445 cx: &mut ViewContext<Editor>,
5446 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5447 self.context_menu.read().as_ref().map(|menu| {
5448 menu.render(
5449 cursor_position,
5450 style,
5451 max_height,
5452 self.workspace.as_ref().map(|(w, _)| w.clone()),
5453 cx,
5454 )
5455 })
5456 }
5457
5458 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5459 cx.notify();
5460 self.completion_tasks.clear();
5461 let context_menu = self.context_menu.write().take();
5462 if context_menu.is_some() {
5463 self.update_visible_inline_completion(cx);
5464 }
5465 context_menu
5466 }
5467
5468 pub fn insert_snippet(
5469 &mut self,
5470 insertion_ranges: &[Range<usize>],
5471 snippet: Snippet,
5472 cx: &mut ViewContext<Self>,
5473 ) -> Result<()> {
5474 struct Tabstop<T> {
5475 is_end_tabstop: bool,
5476 ranges: Vec<Range<T>>,
5477 }
5478
5479 let tabstops = self.buffer.update(cx, |buffer, cx| {
5480 let snippet_text: Arc<str> = snippet.text.clone().into();
5481 buffer.edit(
5482 insertion_ranges
5483 .iter()
5484 .cloned()
5485 .map(|range| (range, snippet_text.clone())),
5486 Some(AutoindentMode::EachLine),
5487 cx,
5488 );
5489
5490 let snapshot = &*buffer.read(cx);
5491 let snippet = &snippet;
5492 snippet
5493 .tabstops
5494 .iter()
5495 .map(|tabstop| {
5496 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5497 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5498 });
5499 let mut tabstop_ranges = tabstop
5500 .iter()
5501 .flat_map(|tabstop_range| {
5502 let mut delta = 0_isize;
5503 insertion_ranges.iter().map(move |insertion_range| {
5504 let insertion_start = insertion_range.start as isize + delta;
5505 delta +=
5506 snippet.text.len() as isize - insertion_range.len() as isize;
5507
5508 let start = ((insertion_start + tabstop_range.start) as usize)
5509 .min(snapshot.len());
5510 let end = ((insertion_start + tabstop_range.end) as usize)
5511 .min(snapshot.len());
5512 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5513 })
5514 })
5515 .collect::<Vec<_>>();
5516 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5517
5518 Tabstop {
5519 is_end_tabstop,
5520 ranges: tabstop_ranges,
5521 }
5522 })
5523 .collect::<Vec<_>>()
5524 });
5525 if let Some(tabstop) = tabstops.first() {
5526 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5527 s.select_ranges(tabstop.ranges.iter().cloned());
5528 });
5529
5530 // If we're already at the last tabstop and it's at the end of the snippet,
5531 // we're done, we don't need to keep the state around.
5532 if !tabstop.is_end_tabstop {
5533 let ranges = tabstops
5534 .into_iter()
5535 .map(|tabstop| tabstop.ranges)
5536 .collect::<Vec<_>>();
5537 self.snippet_stack.push(SnippetState {
5538 active_index: 0,
5539 ranges,
5540 });
5541 }
5542
5543 // Check whether the just-entered snippet ends with an auto-closable bracket.
5544 if self.autoclose_regions.is_empty() {
5545 let snapshot = self.buffer.read(cx).snapshot(cx);
5546 for selection in &mut self.selections.all::<Point>(cx) {
5547 let selection_head = selection.head();
5548 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5549 continue;
5550 };
5551
5552 let mut bracket_pair = None;
5553 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5554 let prev_chars = snapshot
5555 .reversed_chars_at(selection_head)
5556 .collect::<String>();
5557 for (pair, enabled) in scope.brackets() {
5558 if enabled
5559 && pair.close
5560 && prev_chars.starts_with(pair.start.as_str())
5561 && next_chars.starts_with(pair.end.as_str())
5562 {
5563 bracket_pair = Some(pair.clone());
5564 break;
5565 }
5566 }
5567 if let Some(pair) = bracket_pair {
5568 let start = snapshot.anchor_after(selection_head);
5569 let end = snapshot.anchor_after(selection_head);
5570 self.autoclose_regions.push(AutocloseRegion {
5571 selection_id: selection.id,
5572 range: start..end,
5573 pair,
5574 });
5575 }
5576 }
5577 }
5578 }
5579 Ok(())
5580 }
5581
5582 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5583 self.move_to_snippet_tabstop(Bias::Right, cx)
5584 }
5585
5586 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5587 self.move_to_snippet_tabstop(Bias::Left, cx)
5588 }
5589
5590 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5591 if let Some(mut snippet) = self.snippet_stack.pop() {
5592 match bias {
5593 Bias::Left => {
5594 if snippet.active_index > 0 {
5595 snippet.active_index -= 1;
5596 } else {
5597 self.snippet_stack.push(snippet);
5598 return false;
5599 }
5600 }
5601 Bias::Right => {
5602 if snippet.active_index + 1 < snippet.ranges.len() {
5603 snippet.active_index += 1;
5604 } else {
5605 self.snippet_stack.push(snippet);
5606 return false;
5607 }
5608 }
5609 }
5610 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5611 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5612 s.select_anchor_ranges(current_ranges.iter().cloned())
5613 });
5614 // If snippet state is not at the last tabstop, push it back on the stack
5615 if snippet.active_index + 1 < snippet.ranges.len() {
5616 self.snippet_stack.push(snippet);
5617 }
5618 return true;
5619 }
5620 }
5621
5622 false
5623 }
5624
5625 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5626 self.transact(cx, |this, cx| {
5627 this.select_all(&SelectAll, cx);
5628 this.insert("", cx);
5629 });
5630 }
5631
5632 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5633 self.transact(cx, |this, cx| {
5634 this.select_autoclose_pair(cx);
5635 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5636 if !this.linked_edit_ranges.is_empty() {
5637 let selections = this.selections.all::<MultiBufferPoint>(cx);
5638 let snapshot = this.buffer.read(cx).snapshot(cx);
5639
5640 for selection in selections.iter() {
5641 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5642 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5643 if selection_start.buffer_id != selection_end.buffer_id {
5644 continue;
5645 }
5646 if let Some(ranges) =
5647 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5648 {
5649 for (buffer, entries) in ranges {
5650 linked_ranges.entry(buffer).or_default().extend(entries);
5651 }
5652 }
5653 }
5654 }
5655
5656 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5657 if !this.selections.line_mode {
5658 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5659 for selection in &mut selections {
5660 if selection.is_empty() {
5661 let old_head = selection.head();
5662 let mut new_head =
5663 movement::left(&display_map, old_head.to_display_point(&display_map))
5664 .to_point(&display_map);
5665 if let Some((buffer, line_buffer_range)) = display_map
5666 .buffer_snapshot
5667 .buffer_line_for_row(MultiBufferRow(old_head.row))
5668 {
5669 let indent_size =
5670 buffer.indent_size_for_line(line_buffer_range.start.row);
5671 let indent_len = match indent_size.kind {
5672 IndentKind::Space => {
5673 buffer.settings_at(line_buffer_range.start, cx).tab_size
5674 }
5675 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5676 };
5677 if old_head.column <= indent_size.len && old_head.column > 0 {
5678 let indent_len = indent_len.get();
5679 new_head = cmp::min(
5680 new_head,
5681 MultiBufferPoint::new(
5682 old_head.row,
5683 ((old_head.column - 1) / indent_len) * indent_len,
5684 ),
5685 );
5686 }
5687 }
5688
5689 selection.set_head(new_head, SelectionGoal::None);
5690 }
5691 }
5692 }
5693
5694 this.signature_help_state.set_backspace_pressed(true);
5695 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5696 this.insert("", cx);
5697 let empty_str: Arc<str> = Arc::from("");
5698 for (buffer, edits) in linked_ranges {
5699 let snapshot = buffer.read(cx).snapshot();
5700 use text::ToPoint as TP;
5701
5702 let edits = edits
5703 .into_iter()
5704 .map(|range| {
5705 let end_point = TP::to_point(&range.end, &snapshot);
5706 let mut start_point = TP::to_point(&range.start, &snapshot);
5707
5708 if end_point == start_point {
5709 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5710 .saturating_sub(1);
5711 start_point = TP::to_point(&offset, &snapshot);
5712 };
5713
5714 (start_point..end_point, empty_str.clone())
5715 })
5716 .sorted_by_key(|(range, _)| range.start)
5717 .collect::<Vec<_>>();
5718 buffer.update(cx, |this, cx| {
5719 this.edit(edits, None, cx);
5720 })
5721 }
5722 this.refresh_inline_completion(true, false, cx);
5723 linked_editing_ranges::refresh_linked_ranges(this, cx);
5724 });
5725 }
5726
5727 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5728 self.transact(cx, |this, cx| {
5729 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5730 let line_mode = s.line_mode;
5731 s.move_with(|map, selection| {
5732 if selection.is_empty() && !line_mode {
5733 let cursor = movement::right(map, selection.head());
5734 selection.end = cursor;
5735 selection.reversed = true;
5736 selection.goal = SelectionGoal::None;
5737 }
5738 })
5739 });
5740 this.insert("", cx);
5741 this.refresh_inline_completion(true, false, cx);
5742 });
5743 }
5744
5745 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5746 if self.move_to_prev_snippet_tabstop(cx) {
5747 return;
5748 }
5749
5750 self.outdent(&Outdent, cx);
5751 }
5752
5753 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5754 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5755 return;
5756 }
5757
5758 let mut selections = self.selections.all_adjusted(cx);
5759 let buffer = self.buffer.read(cx);
5760 let snapshot = buffer.snapshot(cx);
5761 let rows_iter = selections.iter().map(|s| s.head().row);
5762 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5763
5764 let mut edits = Vec::new();
5765 let mut prev_edited_row = 0;
5766 let mut row_delta = 0;
5767 for selection in &mut selections {
5768 if selection.start.row != prev_edited_row {
5769 row_delta = 0;
5770 }
5771 prev_edited_row = selection.end.row;
5772
5773 // If the selection is non-empty, then increase the indentation of the selected lines.
5774 if !selection.is_empty() {
5775 row_delta =
5776 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5777 continue;
5778 }
5779
5780 // If the selection is empty and the cursor is in the leading whitespace before the
5781 // suggested indentation, then auto-indent the line.
5782 let cursor = selection.head();
5783 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5784 if let Some(suggested_indent) =
5785 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5786 {
5787 if cursor.column < suggested_indent.len
5788 && cursor.column <= current_indent.len
5789 && current_indent.len <= suggested_indent.len
5790 {
5791 selection.start = Point::new(cursor.row, suggested_indent.len);
5792 selection.end = selection.start;
5793 if row_delta == 0 {
5794 edits.extend(Buffer::edit_for_indent_size_adjustment(
5795 cursor.row,
5796 current_indent,
5797 suggested_indent,
5798 ));
5799 row_delta = suggested_indent.len - current_indent.len;
5800 }
5801 continue;
5802 }
5803 }
5804
5805 // Otherwise, insert a hard or soft tab.
5806 let settings = buffer.settings_at(cursor, cx);
5807 let tab_size = if settings.hard_tabs {
5808 IndentSize::tab()
5809 } else {
5810 let tab_size = settings.tab_size.get();
5811 let char_column = snapshot
5812 .text_for_range(Point::new(cursor.row, 0)..cursor)
5813 .flat_map(str::chars)
5814 .count()
5815 + row_delta as usize;
5816 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5817 IndentSize::spaces(chars_to_next_tab_stop)
5818 };
5819 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5820 selection.end = selection.start;
5821 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5822 row_delta += tab_size.len;
5823 }
5824
5825 self.transact(cx, |this, cx| {
5826 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5827 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5828 this.refresh_inline_completion(true, false, cx);
5829 });
5830 }
5831
5832 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5833 if self.read_only(cx) {
5834 return;
5835 }
5836 let mut selections = self.selections.all::<Point>(cx);
5837 let mut prev_edited_row = 0;
5838 let mut row_delta = 0;
5839 let mut edits = Vec::new();
5840 let buffer = self.buffer.read(cx);
5841 let snapshot = buffer.snapshot(cx);
5842 for selection in &mut selections {
5843 if selection.start.row != prev_edited_row {
5844 row_delta = 0;
5845 }
5846 prev_edited_row = selection.end.row;
5847
5848 row_delta =
5849 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5850 }
5851
5852 self.transact(cx, |this, cx| {
5853 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5854 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5855 });
5856 }
5857
5858 fn indent_selection(
5859 buffer: &MultiBuffer,
5860 snapshot: &MultiBufferSnapshot,
5861 selection: &mut Selection<Point>,
5862 edits: &mut Vec<(Range<Point>, String)>,
5863 delta_for_start_row: u32,
5864 cx: &AppContext,
5865 ) -> u32 {
5866 let settings = buffer.settings_at(selection.start, cx);
5867 let tab_size = settings.tab_size.get();
5868 let indent_kind = if settings.hard_tabs {
5869 IndentKind::Tab
5870 } else {
5871 IndentKind::Space
5872 };
5873 let mut start_row = selection.start.row;
5874 let mut end_row = selection.end.row + 1;
5875
5876 // If a selection ends at the beginning of a line, don't indent
5877 // that last line.
5878 if selection.end.column == 0 && selection.end.row > selection.start.row {
5879 end_row -= 1;
5880 }
5881
5882 // Avoid re-indenting a row that has already been indented by a
5883 // previous selection, but still update this selection's column
5884 // to reflect that indentation.
5885 if delta_for_start_row > 0 {
5886 start_row += 1;
5887 selection.start.column += delta_for_start_row;
5888 if selection.end.row == selection.start.row {
5889 selection.end.column += delta_for_start_row;
5890 }
5891 }
5892
5893 let mut delta_for_end_row = 0;
5894 let has_multiple_rows = start_row + 1 != end_row;
5895 for row in start_row..end_row {
5896 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5897 let indent_delta = match (current_indent.kind, indent_kind) {
5898 (IndentKind::Space, IndentKind::Space) => {
5899 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5900 IndentSize::spaces(columns_to_next_tab_stop)
5901 }
5902 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5903 (_, IndentKind::Tab) => IndentSize::tab(),
5904 };
5905
5906 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5907 0
5908 } else {
5909 selection.start.column
5910 };
5911 let row_start = Point::new(row, start);
5912 edits.push((
5913 row_start..row_start,
5914 indent_delta.chars().collect::<String>(),
5915 ));
5916
5917 // Update this selection's endpoints to reflect the indentation.
5918 if row == selection.start.row {
5919 selection.start.column += indent_delta.len;
5920 }
5921 if row == selection.end.row {
5922 selection.end.column += indent_delta.len;
5923 delta_for_end_row = indent_delta.len;
5924 }
5925 }
5926
5927 if selection.start.row == selection.end.row {
5928 delta_for_start_row + delta_for_end_row
5929 } else {
5930 delta_for_end_row
5931 }
5932 }
5933
5934 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5935 if self.read_only(cx) {
5936 return;
5937 }
5938 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5939 let selections = self.selections.all::<Point>(cx);
5940 let mut deletion_ranges = Vec::new();
5941 let mut last_outdent = None;
5942 {
5943 let buffer = self.buffer.read(cx);
5944 let snapshot = buffer.snapshot(cx);
5945 for selection in &selections {
5946 let settings = buffer.settings_at(selection.start, cx);
5947 let tab_size = settings.tab_size.get();
5948 let mut rows = selection.spanned_rows(false, &display_map);
5949
5950 // Avoid re-outdenting a row that has already been outdented by a
5951 // previous selection.
5952 if let Some(last_row) = last_outdent {
5953 if last_row == rows.start {
5954 rows.start = rows.start.next_row();
5955 }
5956 }
5957 let has_multiple_rows = rows.len() > 1;
5958 for row in rows.iter_rows() {
5959 let indent_size = snapshot.indent_size_for_line(row);
5960 if indent_size.len > 0 {
5961 let deletion_len = match indent_size.kind {
5962 IndentKind::Space => {
5963 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5964 if columns_to_prev_tab_stop == 0 {
5965 tab_size
5966 } else {
5967 columns_to_prev_tab_stop
5968 }
5969 }
5970 IndentKind::Tab => 1,
5971 };
5972 let start = if has_multiple_rows
5973 || deletion_len > selection.start.column
5974 || indent_size.len < selection.start.column
5975 {
5976 0
5977 } else {
5978 selection.start.column - deletion_len
5979 };
5980 deletion_ranges.push(
5981 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5982 );
5983 last_outdent = Some(row);
5984 }
5985 }
5986 }
5987 }
5988
5989 self.transact(cx, |this, cx| {
5990 this.buffer.update(cx, |buffer, cx| {
5991 let empty_str: Arc<str> = Arc::default();
5992 buffer.edit(
5993 deletion_ranges
5994 .into_iter()
5995 .map(|range| (range, empty_str.clone())),
5996 None,
5997 cx,
5998 );
5999 });
6000 let selections = this.selections.all::<usize>(cx);
6001 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
6002 });
6003 }
6004
6005 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
6006 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6007 let selections = self.selections.all::<Point>(cx);
6008
6009 let mut new_cursors = Vec::new();
6010 let mut edit_ranges = Vec::new();
6011 let mut selections = selections.iter().peekable();
6012 while let Some(selection) = selections.next() {
6013 let mut rows = selection.spanned_rows(false, &display_map);
6014 let goal_display_column = selection.head().to_display_point(&display_map).column();
6015
6016 // Accumulate contiguous regions of rows that we want to delete.
6017 while let Some(next_selection) = selections.peek() {
6018 let next_rows = next_selection.spanned_rows(false, &display_map);
6019 if next_rows.start <= rows.end {
6020 rows.end = next_rows.end;
6021 selections.next().unwrap();
6022 } else {
6023 break;
6024 }
6025 }
6026
6027 let buffer = &display_map.buffer_snapshot;
6028 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
6029 let edit_end;
6030 let cursor_buffer_row;
6031 if buffer.max_point().row >= rows.end.0 {
6032 // If there's a line after the range, delete the \n from the end of the row range
6033 // and position the cursor on the next line.
6034 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
6035 cursor_buffer_row = rows.end;
6036 } else {
6037 // If there isn't a line after the range, delete the \n from the line before the
6038 // start of the row range and position the cursor there.
6039 edit_start = edit_start.saturating_sub(1);
6040 edit_end = buffer.len();
6041 cursor_buffer_row = rows.start.previous_row();
6042 }
6043
6044 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
6045 *cursor.column_mut() =
6046 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
6047
6048 new_cursors.push((
6049 selection.id,
6050 buffer.anchor_after(cursor.to_point(&display_map)),
6051 ));
6052 edit_ranges.push(edit_start..edit_end);
6053 }
6054
6055 self.transact(cx, |this, cx| {
6056 let buffer = this.buffer.update(cx, |buffer, cx| {
6057 let empty_str: Arc<str> = Arc::default();
6058 buffer.edit(
6059 edit_ranges
6060 .into_iter()
6061 .map(|range| (range, empty_str.clone())),
6062 None,
6063 cx,
6064 );
6065 buffer.snapshot(cx)
6066 });
6067 let new_selections = new_cursors
6068 .into_iter()
6069 .map(|(id, cursor)| {
6070 let cursor = cursor.to_point(&buffer);
6071 Selection {
6072 id,
6073 start: cursor,
6074 end: cursor,
6075 reversed: false,
6076 goal: SelectionGoal::None,
6077 }
6078 })
6079 .collect();
6080
6081 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6082 s.select(new_selections);
6083 });
6084 });
6085 }
6086
6087 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6088 if self.read_only(cx) {
6089 return;
6090 }
6091 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6092 for selection in self.selections.all::<Point>(cx) {
6093 let start = MultiBufferRow(selection.start.row);
6094 let end = if selection.start.row == selection.end.row {
6095 MultiBufferRow(selection.start.row + 1)
6096 } else {
6097 MultiBufferRow(selection.end.row)
6098 };
6099
6100 if let Some(last_row_range) = row_ranges.last_mut() {
6101 if start <= last_row_range.end {
6102 last_row_range.end = end;
6103 continue;
6104 }
6105 }
6106 row_ranges.push(start..end);
6107 }
6108
6109 let snapshot = self.buffer.read(cx).snapshot(cx);
6110 let mut cursor_positions = Vec::new();
6111 for row_range in &row_ranges {
6112 let anchor = snapshot.anchor_before(Point::new(
6113 row_range.end.previous_row().0,
6114 snapshot.line_len(row_range.end.previous_row()),
6115 ));
6116 cursor_positions.push(anchor..anchor);
6117 }
6118
6119 self.transact(cx, |this, cx| {
6120 for row_range in row_ranges.into_iter().rev() {
6121 for row in row_range.iter_rows().rev() {
6122 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6123 let next_line_row = row.next_row();
6124 let indent = snapshot.indent_size_for_line(next_line_row);
6125 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6126
6127 let replace = if snapshot.line_len(next_line_row) > indent.len {
6128 " "
6129 } else {
6130 ""
6131 };
6132
6133 this.buffer.update(cx, |buffer, cx| {
6134 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6135 });
6136 }
6137 }
6138
6139 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6140 s.select_anchor_ranges(cursor_positions)
6141 });
6142 });
6143 }
6144
6145 pub fn sort_lines_case_sensitive(
6146 &mut self,
6147 _: &SortLinesCaseSensitive,
6148 cx: &mut ViewContext<Self>,
6149 ) {
6150 self.manipulate_lines(cx, |lines| lines.sort())
6151 }
6152
6153 pub fn sort_lines_case_insensitive(
6154 &mut self,
6155 _: &SortLinesCaseInsensitive,
6156 cx: &mut ViewContext<Self>,
6157 ) {
6158 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6159 }
6160
6161 pub fn unique_lines_case_insensitive(
6162 &mut self,
6163 _: &UniqueLinesCaseInsensitive,
6164 cx: &mut ViewContext<Self>,
6165 ) {
6166 self.manipulate_lines(cx, |lines| {
6167 let mut seen = HashSet::default();
6168 lines.retain(|line| seen.insert(line.to_lowercase()));
6169 })
6170 }
6171
6172 pub fn unique_lines_case_sensitive(
6173 &mut self,
6174 _: &UniqueLinesCaseSensitive,
6175 cx: &mut ViewContext<Self>,
6176 ) {
6177 self.manipulate_lines(cx, |lines| {
6178 let mut seen = HashSet::default();
6179 lines.retain(|line| seen.insert(*line));
6180 })
6181 }
6182
6183 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6184 let mut revert_changes = HashMap::default();
6185 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6186 for hunk in hunks_for_rows(
6187 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6188 &multi_buffer_snapshot,
6189 ) {
6190 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6191 }
6192 if !revert_changes.is_empty() {
6193 self.transact(cx, |editor, cx| {
6194 editor.revert(revert_changes, cx);
6195 });
6196 }
6197 }
6198
6199 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6200 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6201 if !revert_changes.is_empty() {
6202 self.transact(cx, |editor, cx| {
6203 editor.revert(revert_changes, cx);
6204 });
6205 }
6206 }
6207
6208 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6209 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6210 let project_path = buffer.read(cx).project_path(cx)?;
6211 let project = self.project.as_ref()?.read(cx);
6212 let entry = project.entry_for_path(&project_path, cx)?;
6213 let abs_path = project.absolute_path(&project_path, cx)?;
6214 let parent = if entry.is_symlink {
6215 abs_path.canonicalize().ok()?
6216 } else {
6217 abs_path
6218 }
6219 .parent()?
6220 .to_path_buf();
6221 Some(parent)
6222 }) {
6223 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6224 }
6225 }
6226
6227 fn gather_revert_changes(
6228 &mut self,
6229 selections: &[Selection<Anchor>],
6230 cx: &mut ViewContext<'_, Editor>,
6231 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6232 let mut revert_changes = HashMap::default();
6233 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6234 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6235 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6236 }
6237 revert_changes
6238 }
6239
6240 pub fn prepare_revert_change(
6241 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6242 multi_buffer: &Model<MultiBuffer>,
6243 hunk: &MultiBufferDiffHunk,
6244 cx: &AppContext,
6245 ) -> Option<()> {
6246 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6247 let buffer = buffer.read(cx);
6248 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6249 let buffer_snapshot = buffer.snapshot();
6250 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6251 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6252 probe
6253 .0
6254 .start
6255 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6256 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6257 }) {
6258 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6259 Some(())
6260 } else {
6261 None
6262 }
6263 }
6264
6265 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6266 self.manipulate_lines(cx, |lines| lines.reverse())
6267 }
6268
6269 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6270 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6271 }
6272
6273 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6274 where
6275 Fn: FnMut(&mut Vec<&str>),
6276 {
6277 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6278 let buffer = self.buffer.read(cx).snapshot(cx);
6279
6280 let mut edits = Vec::new();
6281
6282 let selections = self.selections.all::<Point>(cx);
6283 let mut selections = selections.iter().peekable();
6284 let mut contiguous_row_selections = Vec::new();
6285 let mut new_selections = Vec::new();
6286 let mut added_lines = 0;
6287 let mut removed_lines = 0;
6288
6289 while let Some(selection) = selections.next() {
6290 let (start_row, end_row) = consume_contiguous_rows(
6291 &mut contiguous_row_selections,
6292 selection,
6293 &display_map,
6294 &mut selections,
6295 );
6296
6297 let start_point = Point::new(start_row.0, 0);
6298 let end_point = Point::new(
6299 end_row.previous_row().0,
6300 buffer.line_len(end_row.previous_row()),
6301 );
6302 let text = buffer
6303 .text_for_range(start_point..end_point)
6304 .collect::<String>();
6305
6306 let mut lines = text.split('\n').collect_vec();
6307
6308 let lines_before = lines.len();
6309 callback(&mut lines);
6310 let lines_after = lines.len();
6311
6312 edits.push((start_point..end_point, lines.join("\n")));
6313
6314 // Selections must change based on added and removed line count
6315 let start_row =
6316 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6317 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6318 new_selections.push(Selection {
6319 id: selection.id,
6320 start: start_row,
6321 end: end_row,
6322 goal: SelectionGoal::None,
6323 reversed: selection.reversed,
6324 });
6325
6326 if lines_after > lines_before {
6327 added_lines += lines_after - lines_before;
6328 } else if lines_before > lines_after {
6329 removed_lines += lines_before - lines_after;
6330 }
6331 }
6332
6333 self.transact(cx, |this, cx| {
6334 let buffer = this.buffer.update(cx, |buffer, cx| {
6335 buffer.edit(edits, None, cx);
6336 buffer.snapshot(cx)
6337 });
6338
6339 // Recalculate offsets on newly edited buffer
6340 let new_selections = new_selections
6341 .iter()
6342 .map(|s| {
6343 let start_point = Point::new(s.start.0, 0);
6344 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6345 Selection {
6346 id: s.id,
6347 start: buffer.point_to_offset(start_point),
6348 end: buffer.point_to_offset(end_point),
6349 goal: s.goal,
6350 reversed: s.reversed,
6351 }
6352 })
6353 .collect();
6354
6355 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6356 s.select(new_selections);
6357 });
6358
6359 this.request_autoscroll(Autoscroll::fit(), cx);
6360 });
6361 }
6362
6363 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6364 self.manipulate_text(cx, |text| text.to_uppercase())
6365 }
6366
6367 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6368 self.manipulate_text(cx, |text| text.to_lowercase())
6369 }
6370
6371 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6372 self.manipulate_text(cx, |text| {
6373 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6374 // https://github.com/rutrum/convert-case/issues/16
6375 text.split('\n')
6376 .map(|line| line.to_case(Case::Title))
6377 .join("\n")
6378 })
6379 }
6380
6381 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6382 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6383 }
6384
6385 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6386 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6387 }
6388
6389 pub fn convert_to_upper_camel_case(
6390 &mut self,
6391 _: &ConvertToUpperCamelCase,
6392 cx: &mut ViewContext<Self>,
6393 ) {
6394 self.manipulate_text(cx, |text| {
6395 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6396 // https://github.com/rutrum/convert-case/issues/16
6397 text.split('\n')
6398 .map(|line| line.to_case(Case::UpperCamel))
6399 .join("\n")
6400 })
6401 }
6402
6403 pub fn convert_to_lower_camel_case(
6404 &mut self,
6405 _: &ConvertToLowerCamelCase,
6406 cx: &mut ViewContext<Self>,
6407 ) {
6408 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6409 }
6410
6411 pub fn convert_to_opposite_case(
6412 &mut self,
6413 _: &ConvertToOppositeCase,
6414 cx: &mut ViewContext<Self>,
6415 ) {
6416 self.manipulate_text(cx, |text| {
6417 text.chars()
6418 .fold(String::with_capacity(text.len()), |mut t, c| {
6419 if c.is_uppercase() {
6420 t.extend(c.to_lowercase());
6421 } else {
6422 t.extend(c.to_uppercase());
6423 }
6424 t
6425 })
6426 })
6427 }
6428
6429 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6430 where
6431 Fn: FnMut(&str) -> String,
6432 {
6433 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6434 let buffer = self.buffer.read(cx).snapshot(cx);
6435
6436 let mut new_selections = Vec::new();
6437 let mut edits = Vec::new();
6438 let mut selection_adjustment = 0i32;
6439
6440 for selection in self.selections.all::<usize>(cx) {
6441 let selection_is_empty = selection.is_empty();
6442
6443 let (start, end) = if selection_is_empty {
6444 let word_range = movement::surrounding_word(
6445 &display_map,
6446 selection.start.to_display_point(&display_map),
6447 );
6448 let start = word_range.start.to_offset(&display_map, Bias::Left);
6449 let end = word_range.end.to_offset(&display_map, Bias::Left);
6450 (start, end)
6451 } else {
6452 (selection.start, selection.end)
6453 };
6454
6455 let text = buffer.text_for_range(start..end).collect::<String>();
6456 let old_length = text.len() as i32;
6457 let text = callback(&text);
6458
6459 new_selections.push(Selection {
6460 start: (start as i32 - selection_adjustment) as usize,
6461 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6462 goal: SelectionGoal::None,
6463 ..selection
6464 });
6465
6466 selection_adjustment += old_length - text.len() as i32;
6467
6468 edits.push((start..end, text));
6469 }
6470
6471 self.transact(cx, |this, cx| {
6472 this.buffer.update(cx, |buffer, cx| {
6473 buffer.edit(edits, None, cx);
6474 });
6475
6476 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6477 s.select(new_selections);
6478 });
6479
6480 this.request_autoscroll(Autoscroll::fit(), cx);
6481 });
6482 }
6483
6484 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6485 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6486 let buffer = &display_map.buffer_snapshot;
6487 let selections = self.selections.all::<Point>(cx);
6488
6489 let mut edits = Vec::new();
6490 let mut selections_iter = selections.iter().peekable();
6491 while let Some(selection) = selections_iter.next() {
6492 // Avoid duplicating the same lines twice.
6493 let mut rows = selection.spanned_rows(false, &display_map);
6494
6495 while let Some(next_selection) = selections_iter.peek() {
6496 let next_rows = next_selection.spanned_rows(false, &display_map);
6497 if next_rows.start < rows.end {
6498 rows.end = next_rows.end;
6499 selections_iter.next().unwrap();
6500 } else {
6501 break;
6502 }
6503 }
6504
6505 // Copy the text from the selected row region and splice it either at the start
6506 // or end of the region.
6507 let start = Point::new(rows.start.0, 0);
6508 let end = Point::new(
6509 rows.end.previous_row().0,
6510 buffer.line_len(rows.end.previous_row()),
6511 );
6512 let text = buffer
6513 .text_for_range(start..end)
6514 .chain(Some("\n"))
6515 .collect::<String>();
6516 let insert_location = if upwards {
6517 Point::new(rows.end.0, 0)
6518 } else {
6519 start
6520 };
6521 edits.push((insert_location..insert_location, text));
6522 }
6523
6524 self.transact(cx, |this, cx| {
6525 this.buffer.update(cx, |buffer, cx| {
6526 buffer.edit(edits, None, cx);
6527 });
6528
6529 this.request_autoscroll(Autoscroll::fit(), cx);
6530 });
6531 }
6532
6533 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6534 self.duplicate_line(true, cx);
6535 }
6536
6537 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6538 self.duplicate_line(false, cx);
6539 }
6540
6541 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6542 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6543 let buffer = self.buffer.read(cx).snapshot(cx);
6544
6545 let mut edits = Vec::new();
6546 let mut unfold_ranges = Vec::new();
6547 let mut refold_ranges = Vec::new();
6548
6549 let selections = self.selections.all::<Point>(cx);
6550 let mut selections = selections.iter().peekable();
6551 let mut contiguous_row_selections = Vec::new();
6552 let mut new_selections = Vec::new();
6553
6554 while let Some(selection) = selections.next() {
6555 // Find all the selections that span a contiguous row range
6556 let (start_row, end_row) = consume_contiguous_rows(
6557 &mut contiguous_row_selections,
6558 selection,
6559 &display_map,
6560 &mut selections,
6561 );
6562
6563 // Move the text spanned by the row range to be before the line preceding the row range
6564 if start_row.0 > 0 {
6565 let range_to_move = Point::new(
6566 start_row.previous_row().0,
6567 buffer.line_len(start_row.previous_row()),
6568 )
6569 ..Point::new(
6570 end_row.previous_row().0,
6571 buffer.line_len(end_row.previous_row()),
6572 );
6573 let insertion_point = display_map
6574 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6575 .0;
6576
6577 // Don't move lines across excerpts
6578 if buffer
6579 .excerpt_boundaries_in_range((
6580 Bound::Excluded(insertion_point),
6581 Bound::Included(range_to_move.end),
6582 ))
6583 .next()
6584 .is_none()
6585 {
6586 let text = buffer
6587 .text_for_range(range_to_move.clone())
6588 .flat_map(|s| s.chars())
6589 .skip(1)
6590 .chain(['\n'])
6591 .collect::<String>();
6592
6593 edits.push((
6594 buffer.anchor_after(range_to_move.start)
6595 ..buffer.anchor_before(range_to_move.end),
6596 String::new(),
6597 ));
6598 let insertion_anchor = buffer.anchor_after(insertion_point);
6599 edits.push((insertion_anchor..insertion_anchor, text));
6600
6601 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6602
6603 // Move selections up
6604 new_selections.extend(contiguous_row_selections.drain(..).map(
6605 |mut selection| {
6606 selection.start.row -= row_delta;
6607 selection.end.row -= row_delta;
6608 selection
6609 },
6610 ));
6611
6612 // Move folds up
6613 unfold_ranges.push(range_to_move.clone());
6614 for fold in display_map.folds_in_range(
6615 buffer.anchor_before(range_to_move.start)
6616 ..buffer.anchor_after(range_to_move.end),
6617 ) {
6618 let mut start = fold.range.start.to_point(&buffer);
6619 let mut end = fold.range.end.to_point(&buffer);
6620 start.row -= row_delta;
6621 end.row -= row_delta;
6622 refold_ranges.push((start..end, fold.placeholder.clone()));
6623 }
6624 }
6625 }
6626
6627 // If we didn't move line(s), preserve the existing selections
6628 new_selections.append(&mut contiguous_row_selections);
6629 }
6630
6631 self.transact(cx, |this, cx| {
6632 this.unfold_ranges(unfold_ranges, true, true, cx);
6633 this.buffer.update(cx, |buffer, cx| {
6634 for (range, text) in edits {
6635 buffer.edit([(range, text)], None, cx);
6636 }
6637 });
6638 this.fold_ranges(refold_ranges, true, cx);
6639 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6640 s.select(new_selections);
6641 })
6642 });
6643 }
6644
6645 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6646 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6647 let buffer = self.buffer.read(cx).snapshot(cx);
6648
6649 let mut edits = Vec::new();
6650 let mut unfold_ranges = Vec::new();
6651 let mut refold_ranges = Vec::new();
6652
6653 let selections = self.selections.all::<Point>(cx);
6654 let mut selections = selections.iter().peekable();
6655 let mut contiguous_row_selections = Vec::new();
6656 let mut new_selections = Vec::new();
6657
6658 while let Some(selection) = selections.next() {
6659 // Find all the selections that span a contiguous row range
6660 let (start_row, end_row) = consume_contiguous_rows(
6661 &mut contiguous_row_selections,
6662 selection,
6663 &display_map,
6664 &mut selections,
6665 );
6666
6667 // Move the text spanned by the row range to be after the last line of the row range
6668 if end_row.0 <= buffer.max_point().row {
6669 let range_to_move =
6670 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6671 let insertion_point = display_map
6672 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6673 .0;
6674
6675 // Don't move lines across excerpt boundaries
6676 if buffer
6677 .excerpt_boundaries_in_range((
6678 Bound::Excluded(range_to_move.start),
6679 Bound::Included(insertion_point),
6680 ))
6681 .next()
6682 .is_none()
6683 {
6684 let mut text = String::from("\n");
6685 text.extend(buffer.text_for_range(range_to_move.clone()));
6686 text.pop(); // Drop trailing newline
6687 edits.push((
6688 buffer.anchor_after(range_to_move.start)
6689 ..buffer.anchor_before(range_to_move.end),
6690 String::new(),
6691 ));
6692 let insertion_anchor = buffer.anchor_after(insertion_point);
6693 edits.push((insertion_anchor..insertion_anchor, text));
6694
6695 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6696
6697 // Move selections down
6698 new_selections.extend(contiguous_row_selections.drain(..).map(
6699 |mut selection| {
6700 selection.start.row += row_delta;
6701 selection.end.row += row_delta;
6702 selection
6703 },
6704 ));
6705
6706 // Move folds down
6707 unfold_ranges.push(range_to_move.clone());
6708 for fold in display_map.folds_in_range(
6709 buffer.anchor_before(range_to_move.start)
6710 ..buffer.anchor_after(range_to_move.end),
6711 ) {
6712 let mut start = fold.range.start.to_point(&buffer);
6713 let mut end = fold.range.end.to_point(&buffer);
6714 start.row += row_delta;
6715 end.row += row_delta;
6716 refold_ranges.push((start..end, fold.placeholder.clone()));
6717 }
6718 }
6719 }
6720
6721 // If we didn't move line(s), preserve the existing selections
6722 new_selections.append(&mut contiguous_row_selections);
6723 }
6724
6725 self.transact(cx, |this, cx| {
6726 this.unfold_ranges(unfold_ranges, true, true, cx);
6727 this.buffer.update(cx, |buffer, cx| {
6728 for (range, text) in edits {
6729 buffer.edit([(range, text)], None, cx);
6730 }
6731 });
6732 this.fold_ranges(refold_ranges, true, cx);
6733 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6734 });
6735 }
6736
6737 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6738 let text_layout_details = &self.text_layout_details(cx);
6739 self.transact(cx, |this, cx| {
6740 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6741 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6742 let line_mode = s.line_mode;
6743 s.move_with(|display_map, selection| {
6744 if !selection.is_empty() || line_mode {
6745 return;
6746 }
6747
6748 let mut head = selection.head();
6749 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6750 if head.column() == display_map.line_len(head.row()) {
6751 transpose_offset = display_map
6752 .buffer_snapshot
6753 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6754 }
6755
6756 if transpose_offset == 0 {
6757 return;
6758 }
6759
6760 *head.column_mut() += 1;
6761 head = display_map.clip_point(head, Bias::Right);
6762 let goal = SelectionGoal::HorizontalPosition(
6763 display_map
6764 .x_for_display_point(head, text_layout_details)
6765 .into(),
6766 );
6767 selection.collapse_to(head, goal);
6768
6769 let transpose_start = display_map
6770 .buffer_snapshot
6771 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6772 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6773 let transpose_end = display_map
6774 .buffer_snapshot
6775 .clip_offset(transpose_offset + 1, Bias::Right);
6776 if let Some(ch) =
6777 display_map.buffer_snapshot.chars_at(transpose_start).next()
6778 {
6779 edits.push((transpose_start..transpose_offset, String::new()));
6780 edits.push((transpose_end..transpose_end, ch.to_string()));
6781 }
6782 }
6783 });
6784 edits
6785 });
6786 this.buffer
6787 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6788 let selections = this.selections.all::<usize>(cx);
6789 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6790 s.select(selections);
6791 });
6792 });
6793 }
6794
6795 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6796 self.rewrap_impl(true, cx)
6797 }
6798
6799 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6800 let buffer = self.buffer.read(cx).snapshot(cx);
6801 let selections = self.selections.all::<Point>(cx);
6802 let mut selections = selections.iter().peekable();
6803
6804 let mut edits = Vec::new();
6805 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6806
6807 while let Some(selection) = selections.next() {
6808 let mut start_row = selection.start.row;
6809 let mut end_row = selection.end.row;
6810
6811 // Skip selections that overlap with a range that has already been rewrapped.
6812 let selection_range = start_row..end_row;
6813 if rewrapped_row_ranges
6814 .iter()
6815 .any(|range| range.overlaps(&selection_range))
6816 {
6817 continue;
6818 }
6819
6820 let mut should_rewrap = !only_text;
6821
6822 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6823 match language_scope.language_name().0.as_ref() {
6824 "Markdown" | "Plain Text" => {
6825 should_rewrap = true;
6826 }
6827 _ => {}
6828 }
6829 }
6830
6831 // Since not all lines in the selection may be at the same indent
6832 // level, choose the indent size that is the most common between all
6833 // of the lines.
6834 //
6835 // If there is a tie, we use the deepest indent.
6836 let (indent_size, indent_end) = {
6837 let mut indent_size_occurrences = HashMap::default();
6838 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6839
6840 for row in start_row..=end_row {
6841 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6842 rows_by_indent_size.entry(indent).or_default().push(row);
6843 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6844 }
6845
6846 let indent_size = indent_size_occurrences
6847 .into_iter()
6848 .max_by_key(|(indent, count)| (*count, indent.len))
6849 .map(|(indent, _)| indent)
6850 .unwrap_or_default();
6851 let row = rows_by_indent_size[&indent_size][0];
6852 let indent_end = Point::new(row, indent_size.len);
6853
6854 (indent_size, indent_end)
6855 };
6856
6857 let mut line_prefix = indent_size.chars().collect::<String>();
6858
6859 if let Some(comment_prefix) =
6860 buffer
6861 .language_scope_at(selection.head())
6862 .and_then(|language| {
6863 language
6864 .line_comment_prefixes()
6865 .iter()
6866 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6867 .cloned()
6868 })
6869 {
6870 line_prefix.push_str(&comment_prefix);
6871 should_rewrap = true;
6872 }
6873
6874 if selection.is_empty() {
6875 'expand_upwards: while start_row > 0 {
6876 let prev_row = start_row - 1;
6877 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6878 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6879 {
6880 start_row = prev_row;
6881 } else {
6882 break 'expand_upwards;
6883 }
6884 }
6885
6886 'expand_downwards: while end_row < buffer.max_point().row {
6887 let next_row = end_row + 1;
6888 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6889 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6890 {
6891 end_row = next_row;
6892 } else {
6893 break 'expand_downwards;
6894 }
6895 }
6896 }
6897
6898 if !should_rewrap {
6899 continue;
6900 }
6901
6902 let start = Point::new(start_row, 0);
6903 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6904 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6905 let Some(lines_without_prefixes) = selection_text
6906 .lines()
6907 .map(|line| {
6908 line.strip_prefix(&line_prefix)
6909 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6910 .ok_or_else(|| {
6911 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6912 })
6913 })
6914 .collect::<Result<Vec<_>, _>>()
6915 .log_err()
6916 else {
6917 continue;
6918 };
6919
6920 let unwrapped_text = lines_without_prefixes.join(" ");
6921 let wrap_column = buffer
6922 .settings_at(Point::new(start_row, 0), cx)
6923 .preferred_line_length as usize;
6924 let mut wrapped_text = String::new();
6925 let mut current_line = line_prefix.clone();
6926 for word in unwrapped_text.split_whitespace() {
6927 if current_line.len() + word.len() >= wrap_column {
6928 wrapped_text.push_str(¤t_line);
6929 wrapped_text.push('\n');
6930 current_line.truncate(line_prefix.len());
6931 }
6932
6933 if current_line.len() > line_prefix.len() {
6934 current_line.push(' ');
6935 }
6936
6937 current_line.push_str(word);
6938 }
6939
6940 if !current_line.is_empty() {
6941 wrapped_text.push_str(¤t_line);
6942 }
6943
6944 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
6945 let mut offset = start.to_offset(&buffer);
6946 let mut moved_since_edit = true;
6947
6948 for change in diff.iter_all_changes() {
6949 let value = change.value();
6950 match change.tag() {
6951 ChangeTag::Equal => {
6952 offset += value.len();
6953 moved_since_edit = true;
6954 }
6955 ChangeTag::Delete => {
6956 let start = buffer.anchor_after(offset);
6957 let end = buffer.anchor_before(offset + value.len());
6958
6959 if moved_since_edit {
6960 edits.push((start..end, String::new()));
6961 } else {
6962 edits.last_mut().unwrap().0.end = end;
6963 }
6964
6965 offset += value.len();
6966 moved_since_edit = false;
6967 }
6968 ChangeTag::Insert => {
6969 if moved_since_edit {
6970 let anchor = buffer.anchor_after(offset);
6971 edits.push((anchor..anchor, value.to_string()));
6972 } else {
6973 edits.last_mut().unwrap().1.push_str(value);
6974 }
6975
6976 moved_since_edit = false;
6977 }
6978 }
6979 }
6980
6981 rewrapped_row_ranges.push(start_row..=end_row);
6982 }
6983
6984 self.buffer
6985 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6986 }
6987
6988 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6989 let mut text = String::new();
6990 let buffer = self.buffer.read(cx).snapshot(cx);
6991 let mut selections = self.selections.all::<Point>(cx);
6992 let mut clipboard_selections = Vec::with_capacity(selections.len());
6993 {
6994 let max_point = buffer.max_point();
6995 let mut is_first = true;
6996 for selection in &mut selections {
6997 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6998 if is_entire_line {
6999 selection.start = Point::new(selection.start.row, 0);
7000 if !selection.is_empty() && selection.end.column == 0 {
7001 selection.end = cmp::min(max_point, selection.end);
7002 } else {
7003 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7004 }
7005 selection.goal = SelectionGoal::None;
7006 }
7007 if is_first {
7008 is_first = false;
7009 } else {
7010 text += "\n";
7011 }
7012 let mut len = 0;
7013 for chunk in buffer.text_for_range(selection.start..selection.end) {
7014 text.push_str(chunk);
7015 len += chunk.len();
7016 }
7017 clipboard_selections.push(ClipboardSelection {
7018 len,
7019 is_entire_line,
7020 first_line_indent: buffer
7021 .indent_size_for_line(MultiBufferRow(selection.start.row))
7022 .len,
7023 });
7024 }
7025 }
7026
7027 self.transact(cx, |this, cx| {
7028 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7029 s.select(selections);
7030 });
7031 this.insert("", cx);
7032 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7033 text,
7034 clipboard_selections,
7035 ));
7036 });
7037 }
7038
7039 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7040 let selections = self.selections.all::<Point>(cx);
7041 let buffer = self.buffer.read(cx).read(cx);
7042 let mut text = String::new();
7043
7044 let mut clipboard_selections = Vec::with_capacity(selections.len());
7045 {
7046 let max_point = buffer.max_point();
7047 let mut is_first = true;
7048 for selection in selections.iter() {
7049 let mut start = selection.start;
7050 let mut end = selection.end;
7051 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7052 if is_entire_line {
7053 start = Point::new(start.row, 0);
7054 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7055 }
7056 if is_first {
7057 is_first = false;
7058 } else {
7059 text += "\n";
7060 }
7061 let mut len = 0;
7062 for chunk in buffer.text_for_range(start..end) {
7063 text.push_str(chunk);
7064 len += chunk.len();
7065 }
7066 clipboard_selections.push(ClipboardSelection {
7067 len,
7068 is_entire_line,
7069 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7070 });
7071 }
7072 }
7073
7074 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7075 text,
7076 clipboard_selections,
7077 ));
7078 }
7079
7080 pub fn do_paste(
7081 &mut self,
7082 text: &String,
7083 clipboard_selections: Option<Vec<ClipboardSelection>>,
7084 handle_entire_lines: bool,
7085 cx: &mut ViewContext<Self>,
7086 ) {
7087 if self.read_only(cx) {
7088 return;
7089 }
7090
7091 let clipboard_text = Cow::Borrowed(text);
7092
7093 self.transact(cx, |this, cx| {
7094 if let Some(mut clipboard_selections) = clipboard_selections {
7095 let old_selections = this.selections.all::<usize>(cx);
7096 let all_selections_were_entire_line =
7097 clipboard_selections.iter().all(|s| s.is_entire_line);
7098 let first_selection_indent_column =
7099 clipboard_selections.first().map(|s| s.first_line_indent);
7100 if clipboard_selections.len() != old_selections.len() {
7101 clipboard_selections.drain(..);
7102 }
7103
7104 this.buffer.update(cx, |buffer, cx| {
7105 let snapshot = buffer.read(cx);
7106 let mut start_offset = 0;
7107 let mut edits = Vec::new();
7108 let mut original_indent_columns = Vec::new();
7109 for (ix, selection) in old_selections.iter().enumerate() {
7110 let to_insert;
7111 let entire_line;
7112 let original_indent_column;
7113 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7114 let end_offset = start_offset + clipboard_selection.len;
7115 to_insert = &clipboard_text[start_offset..end_offset];
7116 entire_line = clipboard_selection.is_entire_line;
7117 start_offset = end_offset + 1;
7118 original_indent_column = Some(clipboard_selection.first_line_indent);
7119 } else {
7120 to_insert = clipboard_text.as_str();
7121 entire_line = all_selections_were_entire_line;
7122 original_indent_column = first_selection_indent_column
7123 }
7124
7125 // If the corresponding selection was empty when this slice of the
7126 // clipboard text was written, then the entire line containing the
7127 // selection was copied. If this selection is also currently empty,
7128 // then paste the line before the current line of the buffer.
7129 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7130 let column = selection.start.to_point(&snapshot).column as usize;
7131 let line_start = selection.start - column;
7132 line_start..line_start
7133 } else {
7134 selection.range()
7135 };
7136
7137 edits.push((range, to_insert));
7138 original_indent_columns.extend(original_indent_column);
7139 }
7140 drop(snapshot);
7141
7142 buffer.edit(
7143 edits,
7144 Some(AutoindentMode::Block {
7145 original_indent_columns,
7146 }),
7147 cx,
7148 );
7149 });
7150
7151 let selections = this.selections.all::<usize>(cx);
7152 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7153 } else {
7154 this.insert(&clipboard_text, cx);
7155 }
7156 });
7157 }
7158
7159 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7160 if let Some(item) = cx.read_from_clipboard() {
7161 let entries = item.entries();
7162
7163 match entries.first() {
7164 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7165 // of all the pasted entries.
7166 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7167 .do_paste(
7168 clipboard_string.text(),
7169 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7170 true,
7171 cx,
7172 ),
7173 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7174 }
7175 }
7176 }
7177
7178 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7179 if self.read_only(cx) {
7180 return;
7181 }
7182
7183 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7184 if let Some((selections, _)) =
7185 self.selection_history.transaction(transaction_id).cloned()
7186 {
7187 self.change_selections(None, cx, |s| {
7188 s.select_anchors(selections.to_vec());
7189 });
7190 }
7191 self.request_autoscroll(Autoscroll::fit(), cx);
7192 self.unmark_text(cx);
7193 self.refresh_inline_completion(true, false, cx);
7194 cx.emit(EditorEvent::Edited { transaction_id });
7195 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7196 }
7197 }
7198
7199 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7200 if self.read_only(cx) {
7201 return;
7202 }
7203
7204 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7205 if let Some((_, Some(selections))) =
7206 self.selection_history.transaction(transaction_id).cloned()
7207 {
7208 self.change_selections(None, cx, |s| {
7209 s.select_anchors(selections.to_vec());
7210 });
7211 }
7212 self.request_autoscroll(Autoscroll::fit(), cx);
7213 self.unmark_text(cx);
7214 self.refresh_inline_completion(true, false, cx);
7215 cx.emit(EditorEvent::Edited { transaction_id });
7216 }
7217 }
7218
7219 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7220 self.buffer
7221 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7222 }
7223
7224 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7225 self.buffer
7226 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7227 }
7228
7229 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7230 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7231 let line_mode = s.line_mode;
7232 s.move_with(|map, selection| {
7233 let cursor = if selection.is_empty() && !line_mode {
7234 movement::left(map, selection.start)
7235 } else {
7236 selection.start
7237 };
7238 selection.collapse_to(cursor, SelectionGoal::None);
7239 });
7240 })
7241 }
7242
7243 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7244 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7245 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7246 })
7247 }
7248
7249 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7250 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7251 let line_mode = s.line_mode;
7252 s.move_with(|map, selection| {
7253 let cursor = if selection.is_empty() && !line_mode {
7254 movement::right(map, selection.end)
7255 } else {
7256 selection.end
7257 };
7258 selection.collapse_to(cursor, SelectionGoal::None)
7259 });
7260 })
7261 }
7262
7263 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7264 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7265 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7266 })
7267 }
7268
7269 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7270 if self.take_rename(true, cx).is_some() {
7271 return;
7272 }
7273
7274 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7275 cx.propagate();
7276 return;
7277 }
7278
7279 let text_layout_details = &self.text_layout_details(cx);
7280 let selection_count = self.selections.count();
7281 let first_selection = self.selections.first_anchor();
7282
7283 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7284 let line_mode = s.line_mode;
7285 s.move_with(|map, selection| {
7286 if !selection.is_empty() && !line_mode {
7287 selection.goal = SelectionGoal::None;
7288 }
7289 let (cursor, goal) = movement::up(
7290 map,
7291 selection.start,
7292 selection.goal,
7293 false,
7294 text_layout_details,
7295 );
7296 selection.collapse_to(cursor, goal);
7297 });
7298 });
7299
7300 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7301 {
7302 cx.propagate();
7303 }
7304 }
7305
7306 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7307 if self.take_rename(true, cx).is_some() {
7308 return;
7309 }
7310
7311 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7312 cx.propagate();
7313 return;
7314 }
7315
7316 let text_layout_details = &self.text_layout_details(cx);
7317
7318 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7319 let line_mode = s.line_mode;
7320 s.move_with(|map, selection| {
7321 if !selection.is_empty() && !line_mode {
7322 selection.goal = SelectionGoal::None;
7323 }
7324 let (cursor, goal) = movement::up_by_rows(
7325 map,
7326 selection.start,
7327 action.lines,
7328 selection.goal,
7329 false,
7330 text_layout_details,
7331 );
7332 selection.collapse_to(cursor, goal);
7333 });
7334 })
7335 }
7336
7337 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7338 if self.take_rename(true, cx).is_some() {
7339 return;
7340 }
7341
7342 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7343 cx.propagate();
7344 return;
7345 }
7346
7347 let text_layout_details = &self.text_layout_details(cx);
7348
7349 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7350 let line_mode = s.line_mode;
7351 s.move_with(|map, selection| {
7352 if !selection.is_empty() && !line_mode {
7353 selection.goal = SelectionGoal::None;
7354 }
7355 let (cursor, goal) = movement::down_by_rows(
7356 map,
7357 selection.start,
7358 action.lines,
7359 selection.goal,
7360 false,
7361 text_layout_details,
7362 );
7363 selection.collapse_to(cursor, goal);
7364 });
7365 })
7366 }
7367
7368 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7369 let text_layout_details = &self.text_layout_details(cx);
7370 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7371 s.move_heads_with(|map, head, goal| {
7372 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7373 })
7374 })
7375 }
7376
7377 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7378 let text_layout_details = &self.text_layout_details(cx);
7379 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7380 s.move_heads_with(|map, head, goal| {
7381 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7382 })
7383 })
7384 }
7385
7386 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7387 let Some(row_count) = self.visible_row_count() else {
7388 return;
7389 };
7390
7391 let text_layout_details = &self.text_layout_details(cx);
7392
7393 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7394 s.move_heads_with(|map, head, goal| {
7395 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7396 })
7397 })
7398 }
7399
7400 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7401 if self.take_rename(true, cx).is_some() {
7402 return;
7403 }
7404
7405 if self
7406 .context_menu
7407 .write()
7408 .as_mut()
7409 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7410 .unwrap_or(false)
7411 {
7412 return;
7413 }
7414
7415 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7416 cx.propagate();
7417 return;
7418 }
7419
7420 let Some(row_count) = self.visible_row_count() else {
7421 return;
7422 };
7423
7424 let autoscroll = if action.center_cursor {
7425 Autoscroll::center()
7426 } else {
7427 Autoscroll::fit()
7428 };
7429
7430 let text_layout_details = &self.text_layout_details(cx);
7431
7432 self.change_selections(Some(autoscroll), cx, |s| {
7433 let line_mode = s.line_mode;
7434 s.move_with(|map, selection| {
7435 if !selection.is_empty() && !line_mode {
7436 selection.goal = SelectionGoal::None;
7437 }
7438 let (cursor, goal) = movement::up_by_rows(
7439 map,
7440 selection.end,
7441 row_count,
7442 selection.goal,
7443 false,
7444 text_layout_details,
7445 );
7446 selection.collapse_to(cursor, goal);
7447 });
7448 });
7449 }
7450
7451 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7452 let text_layout_details = &self.text_layout_details(cx);
7453 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7454 s.move_heads_with(|map, head, goal| {
7455 movement::up(map, head, goal, false, text_layout_details)
7456 })
7457 })
7458 }
7459
7460 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7461 self.take_rename(true, cx);
7462
7463 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7464 cx.propagate();
7465 return;
7466 }
7467
7468 let text_layout_details = &self.text_layout_details(cx);
7469 let selection_count = self.selections.count();
7470 let first_selection = self.selections.first_anchor();
7471
7472 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7473 let line_mode = s.line_mode;
7474 s.move_with(|map, selection| {
7475 if !selection.is_empty() && !line_mode {
7476 selection.goal = SelectionGoal::None;
7477 }
7478 let (cursor, goal) = movement::down(
7479 map,
7480 selection.end,
7481 selection.goal,
7482 false,
7483 text_layout_details,
7484 );
7485 selection.collapse_to(cursor, goal);
7486 });
7487 });
7488
7489 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7490 {
7491 cx.propagate();
7492 }
7493 }
7494
7495 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7496 let Some(row_count) = self.visible_row_count() else {
7497 return;
7498 };
7499
7500 let text_layout_details = &self.text_layout_details(cx);
7501
7502 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7503 s.move_heads_with(|map, head, goal| {
7504 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7505 })
7506 })
7507 }
7508
7509 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7510 if self.take_rename(true, cx).is_some() {
7511 return;
7512 }
7513
7514 if self
7515 .context_menu
7516 .write()
7517 .as_mut()
7518 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7519 .unwrap_or(false)
7520 {
7521 return;
7522 }
7523
7524 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7525 cx.propagate();
7526 return;
7527 }
7528
7529 let Some(row_count) = self.visible_row_count() else {
7530 return;
7531 };
7532
7533 let autoscroll = if action.center_cursor {
7534 Autoscroll::center()
7535 } else {
7536 Autoscroll::fit()
7537 };
7538
7539 let text_layout_details = &self.text_layout_details(cx);
7540 self.change_selections(Some(autoscroll), cx, |s| {
7541 let line_mode = s.line_mode;
7542 s.move_with(|map, selection| {
7543 if !selection.is_empty() && !line_mode {
7544 selection.goal = SelectionGoal::None;
7545 }
7546 let (cursor, goal) = movement::down_by_rows(
7547 map,
7548 selection.end,
7549 row_count,
7550 selection.goal,
7551 false,
7552 text_layout_details,
7553 );
7554 selection.collapse_to(cursor, goal);
7555 });
7556 });
7557 }
7558
7559 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7560 let text_layout_details = &self.text_layout_details(cx);
7561 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7562 s.move_heads_with(|map, head, goal| {
7563 movement::down(map, head, goal, false, text_layout_details)
7564 })
7565 });
7566 }
7567
7568 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7569 if let Some(context_menu) = self.context_menu.write().as_mut() {
7570 context_menu.select_first(self.project.as_ref(), cx);
7571 }
7572 }
7573
7574 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7575 if let Some(context_menu) = self.context_menu.write().as_mut() {
7576 context_menu.select_prev(self.project.as_ref(), cx);
7577 }
7578 }
7579
7580 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7581 if let Some(context_menu) = self.context_menu.write().as_mut() {
7582 context_menu.select_next(self.project.as_ref(), cx);
7583 }
7584 }
7585
7586 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7587 if let Some(context_menu) = self.context_menu.write().as_mut() {
7588 context_menu.select_last(self.project.as_ref(), cx);
7589 }
7590 }
7591
7592 pub fn move_to_previous_word_start(
7593 &mut self,
7594 _: &MoveToPreviousWordStart,
7595 cx: &mut ViewContext<Self>,
7596 ) {
7597 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7598 s.move_cursors_with(|map, head, _| {
7599 (
7600 movement::previous_word_start(map, head),
7601 SelectionGoal::None,
7602 )
7603 });
7604 })
7605 }
7606
7607 pub fn move_to_previous_subword_start(
7608 &mut self,
7609 _: &MoveToPreviousSubwordStart,
7610 cx: &mut ViewContext<Self>,
7611 ) {
7612 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7613 s.move_cursors_with(|map, head, _| {
7614 (
7615 movement::previous_subword_start(map, head),
7616 SelectionGoal::None,
7617 )
7618 });
7619 })
7620 }
7621
7622 pub fn select_to_previous_word_start(
7623 &mut self,
7624 _: &SelectToPreviousWordStart,
7625 cx: &mut ViewContext<Self>,
7626 ) {
7627 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7628 s.move_heads_with(|map, head, _| {
7629 (
7630 movement::previous_word_start(map, head),
7631 SelectionGoal::None,
7632 )
7633 });
7634 })
7635 }
7636
7637 pub fn select_to_previous_subword_start(
7638 &mut self,
7639 _: &SelectToPreviousSubwordStart,
7640 cx: &mut ViewContext<Self>,
7641 ) {
7642 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7643 s.move_heads_with(|map, head, _| {
7644 (
7645 movement::previous_subword_start(map, head),
7646 SelectionGoal::None,
7647 )
7648 });
7649 })
7650 }
7651
7652 pub fn delete_to_previous_word_start(
7653 &mut self,
7654 action: &DeleteToPreviousWordStart,
7655 cx: &mut ViewContext<Self>,
7656 ) {
7657 self.transact(cx, |this, cx| {
7658 this.select_autoclose_pair(cx);
7659 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7660 let line_mode = s.line_mode;
7661 s.move_with(|map, selection| {
7662 if selection.is_empty() && !line_mode {
7663 let cursor = if action.ignore_newlines {
7664 movement::previous_word_start(map, selection.head())
7665 } else {
7666 movement::previous_word_start_or_newline(map, selection.head())
7667 };
7668 selection.set_head(cursor, SelectionGoal::None);
7669 }
7670 });
7671 });
7672 this.insert("", cx);
7673 });
7674 }
7675
7676 pub fn delete_to_previous_subword_start(
7677 &mut self,
7678 _: &DeleteToPreviousSubwordStart,
7679 cx: &mut ViewContext<Self>,
7680 ) {
7681 self.transact(cx, |this, cx| {
7682 this.select_autoclose_pair(cx);
7683 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7684 let line_mode = s.line_mode;
7685 s.move_with(|map, selection| {
7686 if selection.is_empty() && !line_mode {
7687 let cursor = movement::previous_subword_start(map, selection.head());
7688 selection.set_head(cursor, SelectionGoal::None);
7689 }
7690 });
7691 });
7692 this.insert("", cx);
7693 });
7694 }
7695
7696 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7697 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7698 s.move_cursors_with(|map, head, _| {
7699 (movement::next_word_end(map, head), SelectionGoal::None)
7700 });
7701 })
7702 }
7703
7704 pub fn move_to_next_subword_end(
7705 &mut self,
7706 _: &MoveToNextSubwordEnd,
7707 cx: &mut ViewContext<Self>,
7708 ) {
7709 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7710 s.move_cursors_with(|map, head, _| {
7711 (movement::next_subword_end(map, head), SelectionGoal::None)
7712 });
7713 })
7714 }
7715
7716 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7717 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7718 s.move_heads_with(|map, head, _| {
7719 (movement::next_word_end(map, head), SelectionGoal::None)
7720 });
7721 })
7722 }
7723
7724 pub fn select_to_next_subword_end(
7725 &mut self,
7726 _: &SelectToNextSubwordEnd,
7727 cx: &mut ViewContext<Self>,
7728 ) {
7729 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7730 s.move_heads_with(|map, head, _| {
7731 (movement::next_subword_end(map, head), SelectionGoal::None)
7732 });
7733 })
7734 }
7735
7736 pub fn delete_to_next_word_end(
7737 &mut self,
7738 action: &DeleteToNextWordEnd,
7739 cx: &mut ViewContext<Self>,
7740 ) {
7741 self.transact(cx, |this, cx| {
7742 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7743 let line_mode = s.line_mode;
7744 s.move_with(|map, selection| {
7745 if selection.is_empty() && !line_mode {
7746 let cursor = if action.ignore_newlines {
7747 movement::next_word_end(map, selection.head())
7748 } else {
7749 movement::next_word_end_or_newline(map, selection.head())
7750 };
7751 selection.set_head(cursor, SelectionGoal::None);
7752 }
7753 });
7754 });
7755 this.insert("", cx);
7756 });
7757 }
7758
7759 pub fn delete_to_next_subword_end(
7760 &mut self,
7761 _: &DeleteToNextSubwordEnd,
7762 cx: &mut ViewContext<Self>,
7763 ) {
7764 self.transact(cx, |this, cx| {
7765 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7766 s.move_with(|map, selection| {
7767 if selection.is_empty() {
7768 let cursor = movement::next_subword_end(map, selection.head());
7769 selection.set_head(cursor, SelectionGoal::None);
7770 }
7771 });
7772 });
7773 this.insert("", cx);
7774 });
7775 }
7776
7777 pub fn move_to_beginning_of_line(
7778 &mut self,
7779 action: &MoveToBeginningOfLine,
7780 cx: &mut ViewContext<Self>,
7781 ) {
7782 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7783 s.move_cursors_with(|map, head, _| {
7784 (
7785 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7786 SelectionGoal::None,
7787 )
7788 });
7789 })
7790 }
7791
7792 pub fn select_to_beginning_of_line(
7793 &mut self,
7794 action: &SelectToBeginningOfLine,
7795 cx: &mut ViewContext<Self>,
7796 ) {
7797 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7798 s.move_heads_with(|map, head, _| {
7799 (
7800 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7801 SelectionGoal::None,
7802 )
7803 });
7804 });
7805 }
7806
7807 pub fn delete_to_beginning_of_line(
7808 &mut self,
7809 _: &DeleteToBeginningOfLine,
7810 cx: &mut ViewContext<Self>,
7811 ) {
7812 self.transact(cx, |this, cx| {
7813 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7814 s.move_with(|_, selection| {
7815 selection.reversed = true;
7816 });
7817 });
7818
7819 this.select_to_beginning_of_line(
7820 &SelectToBeginningOfLine {
7821 stop_at_soft_wraps: false,
7822 },
7823 cx,
7824 );
7825 this.backspace(&Backspace, cx);
7826 });
7827 }
7828
7829 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7830 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7831 s.move_cursors_with(|map, head, _| {
7832 (
7833 movement::line_end(map, head, action.stop_at_soft_wraps),
7834 SelectionGoal::None,
7835 )
7836 });
7837 })
7838 }
7839
7840 pub fn select_to_end_of_line(
7841 &mut self,
7842 action: &SelectToEndOfLine,
7843 cx: &mut ViewContext<Self>,
7844 ) {
7845 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7846 s.move_heads_with(|map, head, _| {
7847 (
7848 movement::line_end(map, head, action.stop_at_soft_wraps),
7849 SelectionGoal::None,
7850 )
7851 });
7852 })
7853 }
7854
7855 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7856 self.transact(cx, |this, cx| {
7857 this.select_to_end_of_line(
7858 &SelectToEndOfLine {
7859 stop_at_soft_wraps: false,
7860 },
7861 cx,
7862 );
7863 this.delete(&Delete, cx);
7864 });
7865 }
7866
7867 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7868 self.transact(cx, |this, cx| {
7869 this.select_to_end_of_line(
7870 &SelectToEndOfLine {
7871 stop_at_soft_wraps: false,
7872 },
7873 cx,
7874 );
7875 this.cut(&Cut, cx);
7876 });
7877 }
7878
7879 pub fn move_to_start_of_paragraph(
7880 &mut self,
7881 _: &MoveToStartOfParagraph,
7882 cx: &mut ViewContext<Self>,
7883 ) {
7884 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7885 cx.propagate();
7886 return;
7887 }
7888
7889 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7890 s.move_with(|map, selection| {
7891 selection.collapse_to(
7892 movement::start_of_paragraph(map, selection.head(), 1),
7893 SelectionGoal::None,
7894 )
7895 });
7896 })
7897 }
7898
7899 pub fn move_to_end_of_paragraph(
7900 &mut self,
7901 _: &MoveToEndOfParagraph,
7902 cx: &mut ViewContext<Self>,
7903 ) {
7904 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7905 cx.propagate();
7906 return;
7907 }
7908
7909 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7910 s.move_with(|map, selection| {
7911 selection.collapse_to(
7912 movement::end_of_paragraph(map, selection.head(), 1),
7913 SelectionGoal::None,
7914 )
7915 });
7916 })
7917 }
7918
7919 pub fn select_to_start_of_paragraph(
7920 &mut self,
7921 _: &SelectToStartOfParagraph,
7922 cx: &mut ViewContext<Self>,
7923 ) {
7924 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7925 cx.propagate();
7926 return;
7927 }
7928
7929 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7930 s.move_heads_with(|map, head, _| {
7931 (
7932 movement::start_of_paragraph(map, head, 1),
7933 SelectionGoal::None,
7934 )
7935 });
7936 })
7937 }
7938
7939 pub fn select_to_end_of_paragraph(
7940 &mut self,
7941 _: &SelectToEndOfParagraph,
7942 cx: &mut ViewContext<Self>,
7943 ) {
7944 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7945 cx.propagate();
7946 return;
7947 }
7948
7949 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7950 s.move_heads_with(|map, head, _| {
7951 (
7952 movement::end_of_paragraph(map, head, 1),
7953 SelectionGoal::None,
7954 )
7955 });
7956 })
7957 }
7958
7959 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
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.select_ranges(vec![0..0]);
7967 });
7968 }
7969
7970 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7971 let mut selection = self.selections.last::<Point>(cx);
7972 selection.set_head(Point::zero(), SelectionGoal::None);
7973
7974 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7975 s.select(vec![selection]);
7976 });
7977 }
7978
7979 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7980 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7981 cx.propagate();
7982 return;
7983 }
7984
7985 let cursor = self.buffer.read(cx).read(cx).len();
7986 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7987 s.select_ranges(vec![cursor..cursor])
7988 });
7989 }
7990
7991 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7992 self.nav_history = nav_history;
7993 }
7994
7995 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7996 self.nav_history.as_ref()
7997 }
7998
7999 fn push_to_nav_history(
8000 &mut self,
8001 cursor_anchor: Anchor,
8002 new_position: Option<Point>,
8003 cx: &mut ViewContext<Self>,
8004 ) {
8005 if let Some(nav_history) = self.nav_history.as_mut() {
8006 let buffer = self.buffer.read(cx).read(cx);
8007 let cursor_position = cursor_anchor.to_point(&buffer);
8008 let scroll_state = self.scroll_manager.anchor();
8009 let scroll_top_row = scroll_state.top_row(&buffer);
8010 drop(buffer);
8011
8012 if let Some(new_position) = new_position {
8013 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8014 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8015 return;
8016 }
8017 }
8018
8019 nav_history.push(
8020 Some(NavigationData {
8021 cursor_anchor,
8022 cursor_position,
8023 scroll_anchor: scroll_state,
8024 scroll_top_row,
8025 }),
8026 cx,
8027 );
8028 }
8029 }
8030
8031 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8032 let buffer = self.buffer.read(cx).snapshot(cx);
8033 let mut selection = self.selections.first::<usize>(cx);
8034 selection.set_head(buffer.len(), SelectionGoal::None);
8035 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8036 s.select(vec![selection]);
8037 });
8038 }
8039
8040 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8041 let end = self.buffer.read(cx).read(cx).len();
8042 self.change_selections(None, cx, |s| {
8043 s.select_ranges(vec![0..end]);
8044 });
8045 }
8046
8047 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8048 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8049 let mut selections = self.selections.all::<Point>(cx);
8050 let max_point = display_map.buffer_snapshot.max_point();
8051 for selection in &mut selections {
8052 let rows = selection.spanned_rows(true, &display_map);
8053 selection.start = Point::new(rows.start.0, 0);
8054 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8055 selection.reversed = false;
8056 }
8057 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8058 s.select(selections);
8059 });
8060 }
8061
8062 pub fn split_selection_into_lines(
8063 &mut self,
8064 _: &SplitSelectionIntoLines,
8065 cx: &mut ViewContext<Self>,
8066 ) {
8067 let mut to_unfold = Vec::new();
8068 let mut new_selection_ranges = Vec::new();
8069 {
8070 let selections = self.selections.all::<Point>(cx);
8071 let buffer = self.buffer.read(cx).read(cx);
8072 for selection in selections {
8073 for row in selection.start.row..selection.end.row {
8074 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8075 new_selection_ranges.push(cursor..cursor);
8076 }
8077 new_selection_ranges.push(selection.end..selection.end);
8078 to_unfold.push(selection.start..selection.end);
8079 }
8080 }
8081 self.unfold_ranges(to_unfold, true, true, cx);
8082 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8083 s.select_ranges(new_selection_ranges);
8084 });
8085 }
8086
8087 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8088 self.add_selection(true, cx);
8089 }
8090
8091 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8092 self.add_selection(false, cx);
8093 }
8094
8095 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8096 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8097 let mut selections = self.selections.all::<Point>(cx);
8098 let text_layout_details = self.text_layout_details(cx);
8099 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8100 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8101 let range = oldest_selection.display_range(&display_map).sorted();
8102
8103 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8104 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8105 let positions = start_x.min(end_x)..start_x.max(end_x);
8106
8107 selections.clear();
8108 let mut stack = Vec::new();
8109 for row in range.start.row().0..=range.end.row().0 {
8110 if let Some(selection) = self.selections.build_columnar_selection(
8111 &display_map,
8112 DisplayRow(row),
8113 &positions,
8114 oldest_selection.reversed,
8115 &text_layout_details,
8116 ) {
8117 stack.push(selection.id);
8118 selections.push(selection);
8119 }
8120 }
8121
8122 if above {
8123 stack.reverse();
8124 }
8125
8126 AddSelectionsState { above, stack }
8127 });
8128
8129 let last_added_selection = *state.stack.last().unwrap();
8130 let mut new_selections = Vec::new();
8131 if above == state.above {
8132 let end_row = if above {
8133 DisplayRow(0)
8134 } else {
8135 display_map.max_point().row()
8136 };
8137
8138 'outer: for selection in selections {
8139 if selection.id == last_added_selection {
8140 let range = selection.display_range(&display_map).sorted();
8141 debug_assert_eq!(range.start.row(), range.end.row());
8142 let mut row = range.start.row();
8143 let positions =
8144 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8145 px(start)..px(end)
8146 } else {
8147 let start_x =
8148 display_map.x_for_display_point(range.start, &text_layout_details);
8149 let end_x =
8150 display_map.x_for_display_point(range.end, &text_layout_details);
8151 start_x.min(end_x)..start_x.max(end_x)
8152 };
8153
8154 while row != end_row {
8155 if above {
8156 row.0 -= 1;
8157 } else {
8158 row.0 += 1;
8159 }
8160
8161 if let Some(new_selection) = self.selections.build_columnar_selection(
8162 &display_map,
8163 row,
8164 &positions,
8165 selection.reversed,
8166 &text_layout_details,
8167 ) {
8168 state.stack.push(new_selection.id);
8169 if above {
8170 new_selections.push(new_selection);
8171 new_selections.push(selection);
8172 } else {
8173 new_selections.push(selection);
8174 new_selections.push(new_selection);
8175 }
8176
8177 continue 'outer;
8178 }
8179 }
8180 }
8181
8182 new_selections.push(selection);
8183 }
8184 } else {
8185 new_selections = selections;
8186 new_selections.retain(|s| s.id != last_added_selection);
8187 state.stack.pop();
8188 }
8189
8190 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8191 s.select(new_selections);
8192 });
8193 if state.stack.len() > 1 {
8194 self.add_selections_state = Some(state);
8195 }
8196 }
8197
8198 pub fn select_next_match_internal(
8199 &mut self,
8200 display_map: &DisplaySnapshot,
8201 replace_newest: bool,
8202 autoscroll: Option<Autoscroll>,
8203 cx: &mut ViewContext<Self>,
8204 ) -> Result<()> {
8205 fn select_next_match_ranges(
8206 this: &mut Editor,
8207 range: Range<usize>,
8208 replace_newest: bool,
8209 auto_scroll: Option<Autoscroll>,
8210 cx: &mut ViewContext<Editor>,
8211 ) {
8212 this.unfold_ranges([range.clone()], false, true, cx);
8213 this.change_selections(auto_scroll, cx, |s| {
8214 if replace_newest {
8215 s.delete(s.newest_anchor().id);
8216 }
8217 s.insert_range(range.clone());
8218 });
8219 }
8220
8221 let buffer = &display_map.buffer_snapshot;
8222 let mut selections = self.selections.all::<usize>(cx);
8223 if let Some(mut select_next_state) = self.select_next_state.take() {
8224 let query = &select_next_state.query;
8225 if !select_next_state.done {
8226 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8227 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8228 let mut next_selected_range = None;
8229
8230 let bytes_after_last_selection =
8231 buffer.bytes_in_range(last_selection.end..buffer.len());
8232 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8233 let query_matches = query
8234 .stream_find_iter(bytes_after_last_selection)
8235 .map(|result| (last_selection.end, result))
8236 .chain(
8237 query
8238 .stream_find_iter(bytes_before_first_selection)
8239 .map(|result| (0, result)),
8240 );
8241
8242 for (start_offset, query_match) in query_matches {
8243 let query_match = query_match.unwrap(); // can only fail due to I/O
8244 let offset_range =
8245 start_offset + query_match.start()..start_offset + query_match.end();
8246 let display_range = offset_range.start.to_display_point(display_map)
8247 ..offset_range.end.to_display_point(display_map);
8248
8249 if !select_next_state.wordwise
8250 || (!movement::is_inside_word(display_map, display_range.start)
8251 && !movement::is_inside_word(display_map, display_range.end))
8252 {
8253 // TODO: This is n^2, because we might check all the selections
8254 if !selections
8255 .iter()
8256 .any(|selection| selection.range().overlaps(&offset_range))
8257 {
8258 next_selected_range = Some(offset_range);
8259 break;
8260 }
8261 }
8262 }
8263
8264 if let Some(next_selected_range) = next_selected_range {
8265 select_next_match_ranges(
8266 self,
8267 next_selected_range,
8268 replace_newest,
8269 autoscroll,
8270 cx,
8271 );
8272 } else {
8273 select_next_state.done = true;
8274 }
8275 }
8276
8277 self.select_next_state = Some(select_next_state);
8278 } else {
8279 let mut only_carets = true;
8280 let mut same_text_selected = true;
8281 let mut selected_text = None;
8282
8283 let mut selections_iter = selections.iter().peekable();
8284 while let Some(selection) = selections_iter.next() {
8285 if selection.start != selection.end {
8286 only_carets = false;
8287 }
8288
8289 if same_text_selected {
8290 if selected_text.is_none() {
8291 selected_text =
8292 Some(buffer.text_for_range(selection.range()).collect::<String>());
8293 }
8294
8295 if let Some(next_selection) = selections_iter.peek() {
8296 if next_selection.range().len() == selection.range().len() {
8297 let next_selected_text = buffer
8298 .text_for_range(next_selection.range())
8299 .collect::<String>();
8300 if Some(next_selected_text) != selected_text {
8301 same_text_selected = false;
8302 selected_text = None;
8303 }
8304 } else {
8305 same_text_selected = false;
8306 selected_text = None;
8307 }
8308 }
8309 }
8310 }
8311
8312 if only_carets {
8313 for selection in &mut selections {
8314 let word_range = movement::surrounding_word(
8315 display_map,
8316 selection.start.to_display_point(display_map),
8317 );
8318 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8319 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8320 selection.goal = SelectionGoal::None;
8321 selection.reversed = false;
8322 select_next_match_ranges(
8323 self,
8324 selection.start..selection.end,
8325 replace_newest,
8326 autoscroll,
8327 cx,
8328 );
8329 }
8330
8331 if selections.len() == 1 {
8332 let selection = selections
8333 .last()
8334 .expect("ensured that there's only one selection");
8335 let query = buffer
8336 .text_for_range(selection.start..selection.end)
8337 .collect::<String>();
8338 let is_empty = query.is_empty();
8339 let select_state = SelectNextState {
8340 query: AhoCorasick::new(&[query])?,
8341 wordwise: true,
8342 done: is_empty,
8343 };
8344 self.select_next_state = Some(select_state);
8345 } else {
8346 self.select_next_state = None;
8347 }
8348 } else if let Some(selected_text) = selected_text {
8349 self.select_next_state = Some(SelectNextState {
8350 query: AhoCorasick::new(&[selected_text])?,
8351 wordwise: false,
8352 done: false,
8353 });
8354 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8355 }
8356 }
8357 Ok(())
8358 }
8359
8360 pub fn select_all_matches(
8361 &mut self,
8362 _action: &SelectAllMatches,
8363 cx: &mut ViewContext<Self>,
8364 ) -> Result<()> {
8365 self.push_to_selection_history();
8366 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8367
8368 self.select_next_match_internal(&display_map, false, None, cx)?;
8369 let Some(select_next_state) = self.select_next_state.as_mut() else {
8370 return Ok(());
8371 };
8372 if select_next_state.done {
8373 return Ok(());
8374 }
8375
8376 let mut new_selections = self.selections.all::<usize>(cx);
8377
8378 let buffer = &display_map.buffer_snapshot;
8379 let query_matches = select_next_state
8380 .query
8381 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8382
8383 for query_match in query_matches {
8384 let query_match = query_match.unwrap(); // can only fail due to I/O
8385 let offset_range = query_match.start()..query_match.end();
8386 let display_range = offset_range.start.to_display_point(&display_map)
8387 ..offset_range.end.to_display_point(&display_map);
8388
8389 if !select_next_state.wordwise
8390 || (!movement::is_inside_word(&display_map, display_range.start)
8391 && !movement::is_inside_word(&display_map, display_range.end))
8392 {
8393 self.selections.change_with(cx, |selections| {
8394 new_selections.push(Selection {
8395 id: selections.new_selection_id(),
8396 start: offset_range.start,
8397 end: offset_range.end,
8398 reversed: false,
8399 goal: SelectionGoal::None,
8400 });
8401 });
8402 }
8403 }
8404
8405 new_selections.sort_by_key(|selection| selection.start);
8406 let mut ix = 0;
8407 while ix + 1 < new_selections.len() {
8408 let current_selection = &new_selections[ix];
8409 let next_selection = &new_selections[ix + 1];
8410 if current_selection.range().overlaps(&next_selection.range()) {
8411 if current_selection.id < next_selection.id {
8412 new_selections.remove(ix + 1);
8413 } else {
8414 new_selections.remove(ix);
8415 }
8416 } else {
8417 ix += 1;
8418 }
8419 }
8420
8421 select_next_state.done = true;
8422 self.unfold_ranges(
8423 new_selections.iter().map(|selection| selection.range()),
8424 false,
8425 false,
8426 cx,
8427 );
8428 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8429 selections.select(new_selections)
8430 });
8431
8432 Ok(())
8433 }
8434
8435 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8436 self.push_to_selection_history();
8437 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8438 self.select_next_match_internal(
8439 &display_map,
8440 action.replace_newest,
8441 Some(Autoscroll::newest()),
8442 cx,
8443 )?;
8444 Ok(())
8445 }
8446
8447 pub fn select_previous(
8448 &mut self,
8449 action: &SelectPrevious,
8450 cx: &mut ViewContext<Self>,
8451 ) -> Result<()> {
8452 self.push_to_selection_history();
8453 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8454 let buffer = &display_map.buffer_snapshot;
8455 let mut selections = self.selections.all::<usize>(cx);
8456 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8457 let query = &select_prev_state.query;
8458 if !select_prev_state.done {
8459 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8460 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8461 let mut next_selected_range = None;
8462 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8463 let bytes_before_last_selection =
8464 buffer.reversed_bytes_in_range(0..last_selection.start);
8465 let bytes_after_first_selection =
8466 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8467 let query_matches = query
8468 .stream_find_iter(bytes_before_last_selection)
8469 .map(|result| (last_selection.start, result))
8470 .chain(
8471 query
8472 .stream_find_iter(bytes_after_first_selection)
8473 .map(|result| (buffer.len(), result)),
8474 );
8475 for (end_offset, query_match) in query_matches {
8476 let query_match = query_match.unwrap(); // can only fail due to I/O
8477 let offset_range =
8478 end_offset - query_match.end()..end_offset - query_match.start();
8479 let display_range = offset_range.start.to_display_point(&display_map)
8480 ..offset_range.end.to_display_point(&display_map);
8481
8482 if !select_prev_state.wordwise
8483 || (!movement::is_inside_word(&display_map, display_range.start)
8484 && !movement::is_inside_word(&display_map, display_range.end))
8485 {
8486 next_selected_range = Some(offset_range);
8487 break;
8488 }
8489 }
8490
8491 if let Some(next_selected_range) = next_selected_range {
8492 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8493 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8494 if action.replace_newest {
8495 s.delete(s.newest_anchor().id);
8496 }
8497 s.insert_range(next_selected_range);
8498 });
8499 } else {
8500 select_prev_state.done = true;
8501 }
8502 }
8503
8504 self.select_prev_state = Some(select_prev_state);
8505 } else {
8506 let mut only_carets = true;
8507 let mut same_text_selected = true;
8508 let mut selected_text = None;
8509
8510 let mut selections_iter = selections.iter().peekable();
8511 while let Some(selection) = selections_iter.next() {
8512 if selection.start != selection.end {
8513 only_carets = false;
8514 }
8515
8516 if same_text_selected {
8517 if selected_text.is_none() {
8518 selected_text =
8519 Some(buffer.text_for_range(selection.range()).collect::<String>());
8520 }
8521
8522 if let Some(next_selection) = selections_iter.peek() {
8523 if next_selection.range().len() == selection.range().len() {
8524 let next_selected_text = buffer
8525 .text_for_range(next_selection.range())
8526 .collect::<String>();
8527 if Some(next_selected_text) != selected_text {
8528 same_text_selected = false;
8529 selected_text = None;
8530 }
8531 } else {
8532 same_text_selected = false;
8533 selected_text = None;
8534 }
8535 }
8536 }
8537 }
8538
8539 if only_carets {
8540 for selection in &mut selections {
8541 let word_range = movement::surrounding_word(
8542 &display_map,
8543 selection.start.to_display_point(&display_map),
8544 );
8545 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8546 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8547 selection.goal = SelectionGoal::None;
8548 selection.reversed = false;
8549 }
8550 if selections.len() == 1 {
8551 let selection = selections
8552 .last()
8553 .expect("ensured that there's only one selection");
8554 let query = buffer
8555 .text_for_range(selection.start..selection.end)
8556 .collect::<String>();
8557 let is_empty = query.is_empty();
8558 let select_state = SelectNextState {
8559 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8560 wordwise: true,
8561 done: is_empty,
8562 };
8563 self.select_prev_state = Some(select_state);
8564 } else {
8565 self.select_prev_state = None;
8566 }
8567
8568 self.unfold_ranges(
8569 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8570 false,
8571 true,
8572 cx,
8573 );
8574 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8575 s.select(selections);
8576 });
8577 } else if let Some(selected_text) = selected_text {
8578 self.select_prev_state = Some(SelectNextState {
8579 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8580 wordwise: false,
8581 done: false,
8582 });
8583 self.select_previous(action, cx)?;
8584 }
8585 }
8586 Ok(())
8587 }
8588
8589 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8590 let text_layout_details = &self.text_layout_details(cx);
8591 self.transact(cx, |this, cx| {
8592 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8593 let mut edits = Vec::new();
8594 let mut selection_edit_ranges = Vec::new();
8595 let mut last_toggled_row = None;
8596 let snapshot = this.buffer.read(cx).read(cx);
8597 let empty_str: Arc<str> = Arc::default();
8598 let mut suffixes_inserted = Vec::new();
8599
8600 fn comment_prefix_range(
8601 snapshot: &MultiBufferSnapshot,
8602 row: MultiBufferRow,
8603 comment_prefix: &str,
8604 comment_prefix_whitespace: &str,
8605 ) -> Range<Point> {
8606 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8607
8608 let mut line_bytes = snapshot
8609 .bytes_in_range(start..snapshot.max_point())
8610 .flatten()
8611 .copied();
8612
8613 // If this line currently begins with the line comment prefix, then record
8614 // the range containing the prefix.
8615 if line_bytes
8616 .by_ref()
8617 .take(comment_prefix.len())
8618 .eq(comment_prefix.bytes())
8619 {
8620 // Include any whitespace that matches the comment prefix.
8621 let matching_whitespace_len = line_bytes
8622 .zip(comment_prefix_whitespace.bytes())
8623 .take_while(|(a, b)| a == b)
8624 .count() as u32;
8625 let end = Point::new(
8626 start.row,
8627 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8628 );
8629 start..end
8630 } else {
8631 start..start
8632 }
8633 }
8634
8635 fn comment_suffix_range(
8636 snapshot: &MultiBufferSnapshot,
8637 row: MultiBufferRow,
8638 comment_suffix: &str,
8639 comment_suffix_has_leading_space: bool,
8640 ) -> Range<Point> {
8641 let end = Point::new(row.0, snapshot.line_len(row));
8642 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8643
8644 let mut line_end_bytes = snapshot
8645 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8646 .flatten()
8647 .copied();
8648
8649 let leading_space_len = if suffix_start_column > 0
8650 && line_end_bytes.next() == Some(b' ')
8651 && comment_suffix_has_leading_space
8652 {
8653 1
8654 } else {
8655 0
8656 };
8657
8658 // If this line currently begins with the line comment prefix, then record
8659 // the range containing the prefix.
8660 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8661 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8662 start..end
8663 } else {
8664 end..end
8665 }
8666 }
8667
8668 // TODO: Handle selections that cross excerpts
8669 for selection in &mut selections {
8670 let start_column = snapshot
8671 .indent_size_for_line(MultiBufferRow(selection.start.row))
8672 .len;
8673 let language = if let Some(language) =
8674 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8675 {
8676 language
8677 } else {
8678 continue;
8679 };
8680
8681 selection_edit_ranges.clear();
8682
8683 // If multiple selections contain a given row, avoid processing that
8684 // row more than once.
8685 let mut start_row = MultiBufferRow(selection.start.row);
8686 if last_toggled_row == Some(start_row) {
8687 start_row = start_row.next_row();
8688 }
8689 let end_row =
8690 if selection.end.row > selection.start.row && selection.end.column == 0 {
8691 MultiBufferRow(selection.end.row - 1)
8692 } else {
8693 MultiBufferRow(selection.end.row)
8694 };
8695 last_toggled_row = Some(end_row);
8696
8697 if start_row > end_row {
8698 continue;
8699 }
8700
8701 // If the language has line comments, toggle those.
8702 let full_comment_prefixes = language.line_comment_prefixes();
8703 if !full_comment_prefixes.is_empty() {
8704 let first_prefix = full_comment_prefixes
8705 .first()
8706 .expect("prefixes is non-empty");
8707 let prefix_trimmed_lengths = full_comment_prefixes
8708 .iter()
8709 .map(|p| p.trim_end_matches(' ').len())
8710 .collect::<SmallVec<[usize; 4]>>();
8711
8712 let mut all_selection_lines_are_comments = true;
8713
8714 for row in start_row.0..=end_row.0 {
8715 let row = MultiBufferRow(row);
8716 if start_row < end_row && snapshot.is_line_blank(row) {
8717 continue;
8718 }
8719
8720 let prefix_range = full_comment_prefixes
8721 .iter()
8722 .zip(prefix_trimmed_lengths.iter().copied())
8723 .map(|(prefix, trimmed_prefix_len)| {
8724 comment_prefix_range(
8725 snapshot.deref(),
8726 row,
8727 &prefix[..trimmed_prefix_len],
8728 &prefix[trimmed_prefix_len..],
8729 )
8730 })
8731 .max_by_key(|range| range.end.column - range.start.column)
8732 .expect("prefixes is non-empty");
8733
8734 if prefix_range.is_empty() {
8735 all_selection_lines_are_comments = false;
8736 }
8737
8738 selection_edit_ranges.push(prefix_range);
8739 }
8740
8741 if all_selection_lines_are_comments {
8742 edits.extend(
8743 selection_edit_ranges
8744 .iter()
8745 .cloned()
8746 .map(|range| (range, empty_str.clone())),
8747 );
8748 } else {
8749 let min_column = selection_edit_ranges
8750 .iter()
8751 .map(|range| range.start.column)
8752 .min()
8753 .unwrap_or(0);
8754 edits.extend(selection_edit_ranges.iter().map(|range| {
8755 let position = Point::new(range.start.row, min_column);
8756 (position..position, first_prefix.clone())
8757 }));
8758 }
8759 } else if let Some((full_comment_prefix, comment_suffix)) =
8760 language.block_comment_delimiters()
8761 {
8762 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8763 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8764 let prefix_range = comment_prefix_range(
8765 snapshot.deref(),
8766 start_row,
8767 comment_prefix,
8768 comment_prefix_whitespace,
8769 );
8770 let suffix_range = comment_suffix_range(
8771 snapshot.deref(),
8772 end_row,
8773 comment_suffix.trim_start_matches(' '),
8774 comment_suffix.starts_with(' '),
8775 );
8776
8777 if prefix_range.is_empty() || suffix_range.is_empty() {
8778 edits.push((
8779 prefix_range.start..prefix_range.start,
8780 full_comment_prefix.clone(),
8781 ));
8782 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8783 suffixes_inserted.push((end_row, comment_suffix.len()));
8784 } else {
8785 edits.push((prefix_range, empty_str.clone()));
8786 edits.push((suffix_range, empty_str.clone()));
8787 }
8788 } else {
8789 continue;
8790 }
8791 }
8792
8793 drop(snapshot);
8794 this.buffer.update(cx, |buffer, cx| {
8795 buffer.edit(edits, None, cx);
8796 });
8797
8798 // Adjust selections so that they end before any comment suffixes that
8799 // were inserted.
8800 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8801 let mut selections = this.selections.all::<Point>(cx);
8802 let snapshot = this.buffer.read(cx).read(cx);
8803 for selection in &mut selections {
8804 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8805 match row.cmp(&MultiBufferRow(selection.end.row)) {
8806 Ordering::Less => {
8807 suffixes_inserted.next();
8808 continue;
8809 }
8810 Ordering::Greater => break,
8811 Ordering::Equal => {
8812 if selection.end.column == snapshot.line_len(row) {
8813 if selection.is_empty() {
8814 selection.start.column -= suffix_len as u32;
8815 }
8816 selection.end.column -= suffix_len as u32;
8817 }
8818 break;
8819 }
8820 }
8821 }
8822 }
8823
8824 drop(snapshot);
8825 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8826
8827 let selections = this.selections.all::<Point>(cx);
8828 let selections_on_single_row = selections.windows(2).all(|selections| {
8829 selections[0].start.row == selections[1].start.row
8830 && selections[0].end.row == selections[1].end.row
8831 && selections[0].start.row == selections[0].end.row
8832 });
8833 let selections_selecting = selections
8834 .iter()
8835 .any(|selection| selection.start != selection.end);
8836 let advance_downwards = action.advance_downwards
8837 && selections_on_single_row
8838 && !selections_selecting
8839 && !matches!(this.mode, EditorMode::SingleLine { .. });
8840
8841 if advance_downwards {
8842 let snapshot = this.buffer.read(cx).snapshot(cx);
8843
8844 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8845 s.move_cursors_with(|display_snapshot, display_point, _| {
8846 let mut point = display_point.to_point(display_snapshot);
8847 point.row += 1;
8848 point = snapshot.clip_point(point, Bias::Left);
8849 let display_point = point.to_display_point(display_snapshot);
8850 let goal = SelectionGoal::HorizontalPosition(
8851 display_snapshot
8852 .x_for_display_point(display_point, text_layout_details)
8853 .into(),
8854 );
8855 (display_point, goal)
8856 })
8857 });
8858 }
8859 });
8860 }
8861
8862 pub fn select_enclosing_symbol(
8863 &mut self,
8864 _: &SelectEnclosingSymbol,
8865 cx: &mut ViewContext<Self>,
8866 ) {
8867 let buffer = self.buffer.read(cx).snapshot(cx);
8868 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8869
8870 fn update_selection(
8871 selection: &Selection<usize>,
8872 buffer_snap: &MultiBufferSnapshot,
8873 ) -> Option<Selection<usize>> {
8874 let cursor = selection.head();
8875 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8876 for symbol in symbols.iter().rev() {
8877 let start = symbol.range.start.to_offset(buffer_snap);
8878 let end = symbol.range.end.to_offset(buffer_snap);
8879 let new_range = start..end;
8880 if start < selection.start || end > selection.end {
8881 return Some(Selection {
8882 id: selection.id,
8883 start: new_range.start,
8884 end: new_range.end,
8885 goal: SelectionGoal::None,
8886 reversed: selection.reversed,
8887 });
8888 }
8889 }
8890 None
8891 }
8892
8893 let mut selected_larger_symbol = false;
8894 let new_selections = old_selections
8895 .iter()
8896 .map(|selection| match update_selection(selection, &buffer) {
8897 Some(new_selection) => {
8898 if new_selection.range() != selection.range() {
8899 selected_larger_symbol = true;
8900 }
8901 new_selection
8902 }
8903 None => selection.clone(),
8904 })
8905 .collect::<Vec<_>>();
8906
8907 if selected_larger_symbol {
8908 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8909 s.select(new_selections);
8910 });
8911 }
8912 }
8913
8914 pub fn select_larger_syntax_node(
8915 &mut self,
8916 _: &SelectLargerSyntaxNode,
8917 cx: &mut ViewContext<Self>,
8918 ) {
8919 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8920 let buffer = self.buffer.read(cx).snapshot(cx);
8921 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8922
8923 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8924 let mut selected_larger_node = false;
8925 let new_selections = old_selections
8926 .iter()
8927 .map(|selection| {
8928 let old_range = selection.start..selection.end;
8929 let mut new_range = old_range.clone();
8930 while let Some(containing_range) =
8931 buffer.range_for_syntax_ancestor(new_range.clone())
8932 {
8933 new_range = containing_range;
8934 if !display_map.intersects_fold(new_range.start)
8935 && !display_map.intersects_fold(new_range.end)
8936 {
8937 break;
8938 }
8939 }
8940
8941 selected_larger_node |= new_range != old_range;
8942 Selection {
8943 id: selection.id,
8944 start: new_range.start,
8945 end: new_range.end,
8946 goal: SelectionGoal::None,
8947 reversed: selection.reversed,
8948 }
8949 })
8950 .collect::<Vec<_>>();
8951
8952 if selected_larger_node {
8953 stack.push(old_selections);
8954 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8955 s.select(new_selections);
8956 });
8957 }
8958 self.select_larger_syntax_node_stack = stack;
8959 }
8960
8961 pub fn select_smaller_syntax_node(
8962 &mut self,
8963 _: &SelectSmallerSyntaxNode,
8964 cx: &mut ViewContext<Self>,
8965 ) {
8966 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8967 if let Some(selections) = stack.pop() {
8968 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8969 s.select(selections.to_vec());
8970 });
8971 }
8972 self.select_larger_syntax_node_stack = stack;
8973 }
8974
8975 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8976 if !EditorSettings::get_global(cx).gutter.runnables {
8977 self.clear_tasks();
8978 return Task::ready(());
8979 }
8980 let project = self.project.clone();
8981 cx.spawn(|this, mut cx| async move {
8982 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8983 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8984 }) else {
8985 return;
8986 };
8987
8988 let Some(project) = project else {
8989 return;
8990 };
8991
8992 let hide_runnables = project
8993 .update(&mut cx, |project, cx| {
8994 // Do not display any test indicators in non-dev server remote projects.
8995 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8996 })
8997 .unwrap_or(true);
8998 if hide_runnables {
8999 return;
9000 }
9001 let new_rows =
9002 cx.background_executor()
9003 .spawn({
9004 let snapshot = display_snapshot.clone();
9005 async move {
9006 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9007 }
9008 })
9009 .await;
9010 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9011
9012 this.update(&mut cx, |this, _| {
9013 this.clear_tasks();
9014 for (key, value) in rows {
9015 this.insert_tasks(key, value);
9016 }
9017 })
9018 .ok();
9019 })
9020 }
9021 fn fetch_runnable_ranges(
9022 snapshot: &DisplaySnapshot,
9023 range: Range<Anchor>,
9024 ) -> Vec<language::RunnableRange> {
9025 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9026 }
9027
9028 fn runnable_rows(
9029 project: Model<Project>,
9030 snapshot: DisplaySnapshot,
9031 runnable_ranges: Vec<RunnableRange>,
9032 mut cx: AsyncWindowContext,
9033 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9034 runnable_ranges
9035 .into_iter()
9036 .filter_map(|mut runnable| {
9037 let tasks = cx
9038 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9039 .ok()?;
9040 if tasks.is_empty() {
9041 return None;
9042 }
9043
9044 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9045
9046 let row = snapshot
9047 .buffer_snapshot
9048 .buffer_line_for_row(MultiBufferRow(point.row))?
9049 .1
9050 .start
9051 .row;
9052
9053 let context_range =
9054 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9055 Some((
9056 (runnable.buffer_id, row),
9057 RunnableTasks {
9058 templates: tasks,
9059 offset: MultiBufferOffset(runnable.run_range.start),
9060 context_range,
9061 column: point.column,
9062 extra_variables: runnable.extra_captures,
9063 },
9064 ))
9065 })
9066 .collect()
9067 }
9068
9069 fn templates_with_tags(
9070 project: &Model<Project>,
9071 runnable: &mut Runnable,
9072 cx: &WindowContext<'_>,
9073 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9074 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9075 let (worktree_id, file) = project
9076 .buffer_for_id(runnable.buffer, cx)
9077 .and_then(|buffer| buffer.read(cx).file())
9078 .map(|file| (file.worktree_id(cx), file.clone()))
9079 .unzip();
9080
9081 (project.task_inventory().clone(), worktree_id, file)
9082 });
9083
9084 let inventory = inventory.read(cx);
9085 let tags = mem::take(&mut runnable.tags);
9086 let mut tags: Vec<_> = tags
9087 .into_iter()
9088 .flat_map(|tag| {
9089 let tag = tag.0.clone();
9090 inventory
9091 .list_tasks(
9092 file.clone(),
9093 Some(runnable.language.clone()),
9094 worktree_id,
9095 cx,
9096 )
9097 .into_iter()
9098 .filter(move |(_, template)| {
9099 template.tags.iter().any(|source_tag| source_tag == &tag)
9100 })
9101 })
9102 .sorted_by_key(|(kind, _)| kind.to_owned())
9103 .collect();
9104 if let Some((leading_tag_source, _)) = tags.first() {
9105 // Strongest source wins; if we have worktree tag binding, prefer that to
9106 // global and language bindings;
9107 // if we have a global binding, prefer that to language binding.
9108 let first_mismatch = tags
9109 .iter()
9110 .position(|(tag_source, _)| tag_source != leading_tag_source);
9111 if let Some(index) = first_mismatch {
9112 tags.truncate(index);
9113 }
9114 }
9115
9116 tags
9117 }
9118
9119 pub fn move_to_enclosing_bracket(
9120 &mut self,
9121 _: &MoveToEnclosingBracket,
9122 cx: &mut ViewContext<Self>,
9123 ) {
9124 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9125 s.move_offsets_with(|snapshot, selection| {
9126 let Some(enclosing_bracket_ranges) =
9127 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9128 else {
9129 return;
9130 };
9131
9132 let mut best_length = usize::MAX;
9133 let mut best_inside = false;
9134 let mut best_in_bracket_range = false;
9135 let mut best_destination = None;
9136 for (open, close) in enclosing_bracket_ranges {
9137 let close = close.to_inclusive();
9138 let length = close.end() - open.start;
9139 let inside = selection.start >= open.end && selection.end <= *close.start();
9140 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9141 || close.contains(&selection.head());
9142
9143 // If best is next to a bracket and current isn't, skip
9144 if !in_bracket_range && best_in_bracket_range {
9145 continue;
9146 }
9147
9148 // Prefer smaller lengths unless best is inside and current isn't
9149 if length > best_length && (best_inside || !inside) {
9150 continue;
9151 }
9152
9153 best_length = length;
9154 best_inside = inside;
9155 best_in_bracket_range = in_bracket_range;
9156 best_destination = Some(
9157 if close.contains(&selection.start) && close.contains(&selection.end) {
9158 if inside {
9159 open.end
9160 } else {
9161 open.start
9162 }
9163 } else if inside {
9164 *close.start()
9165 } else {
9166 *close.end()
9167 },
9168 );
9169 }
9170
9171 if let Some(destination) = best_destination {
9172 selection.collapse_to(destination, SelectionGoal::None);
9173 }
9174 })
9175 });
9176 }
9177
9178 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9179 self.end_selection(cx);
9180 self.selection_history.mode = SelectionHistoryMode::Undoing;
9181 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9182 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9183 self.select_next_state = entry.select_next_state;
9184 self.select_prev_state = entry.select_prev_state;
9185 self.add_selections_state = entry.add_selections_state;
9186 self.request_autoscroll(Autoscroll::newest(), cx);
9187 }
9188 self.selection_history.mode = SelectionHistoryMode::Normal;
9189 }
9190
9191 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9192 self.end_selection(cx);
9193 self.selection_history.mode = SelectionHistoryMode::Redoing;
9194 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9195 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9196 self.select_next_state = entry.select_next_state;
9197 self.select_prev_state = entry.select_prev_state;
9198 self.add_selections_state = entry.add_selections_state;
9199 self.request_autoscroll(Autoscroll::newest(), cx);
9200 }
9201 self.selection_history.mode = SelectionHistoryMode::Normal;
9202 }
9203
9204 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9205 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9206 }
9207
9208 pub fn expand_excerpts_down(
9209 &mut self,
9210 action: &ExpandExcerptsDown,
9211 cx: &mut ViewContext<Self>,
9212 ) {
9213 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9214 }
9215
9216 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9217 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9218 }
9219
9220 pub fn expand_excerpts_for_direction(
9221 &mut self,
9222 lines: u32,
9223 direction: ExpandExcerptDirection,
9224 cx: &mut ViewContext<Self>,
9225 ) {
9226 let selections = self.selections.disjoint_anchors();
9227
9228 let lines = if lines == 0 {
9229 EditorSettings::get_global(cx).expand_excerpt_lines
9230 } else {
9231 lines
9232 };
9233
9234 self.buffer.update(cx, |buffer, cx| {
9235 buffer.expand_excerpts(
9236 selections
9237 .iter()
9238 .map(|selection| selection.head().excerpt_id)
9239 .dedup(),
9240 lines,
9241 direction,
9242 cx,
9243 )
9244 })
9245 }
9246
9247 pub fn expand_excerpt(
9248 &mut self,
9249 excerpt: ExcerptId,
9250 direction: ExpandExcerptDirection,
9251 cx: &mut ViewContext<Self>,
9252 ) {
9253 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9254 self.buffer.update(cx, |buffer, cx| {
9255 buffer.expand_excerpts([excerpt], lines, direction, cx)
9256 })
9257 }
9258
9259 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9260 self.go_to_diagnostic_impl(Direction::Next, cx)
9261 }
9262
9263 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9264 self.go_to_diagnostic_impl(Direction::Prev, cx)
9265 }
9266
9267 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9268 let buffer = self.buffer.read(cx).snapshot(cx);
9269 let selection = self.selections.newest::<usize>(cx);
9270
9271 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9272 if direction == Direction::Next {
9273 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9274 let (group_id, jump_to) = popover.activation_info();
9275 if self.activate_diagnostics(group_id, cx) {
9276 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9277 let mut new_selection = s.newest_anchor().clone();
9278 new_selection.collapse_to(jump_to, SelectionGoal::None);
9279 s.select_anchors(vec![new_selection.clone()]);
9280 });
9281 }
9282 return;
9283 }
9284 }
9285
9286 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9287 active_diagnostics
9288 .primary_range
9289 .to_offset(&buffer)
9290 .to_inclusive()
9291 });
9292 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9293 if active_primary_range.contains(&selection.head()) {
9294 *active_primary_range.start()
9295 } else {
9296 selection.head()
9297 }
9298 } else {
9299 selection.head()
9300 };
9301 let snapshot = self.snapshot(cx);
9302 loop {
9303 let diagnostics = if direction == Direction::Prev {
9304 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9305 } else {
9306 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9307 }
9308 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9309 let group = diagnostics
9310 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9311 // be sorted in a stable way
9312 // skip until we are at current active diagnostic, if it exists
9313 .skip_while(|entry| {
9314 (match direction {
9315 Direction::Prev => entry.range.start >= search_start,
9316 Direction::Next => entry.range.start <= search_start,
9317 }) && self
9318 .active_diagnostics
9319 .as_ref()
9320 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9321 })
9322 .find_map(|entry| {
9323 if entry.diagnostic.is_primary
9324 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9325 && !entry.range.is_empty()
9326 // if we match with the active diagnostic, skip it
9327 && Some(entry.diagnostic.group_id)
9328 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9329 {
9330 Some((entry.range, entry.diagnostic.group_id))
9331 } else {
9332 None
9333 }
9334 });
9335
9336 if let Some((primary_range, group_id)) = group {
9337 if self.activate_diagnostics(group_id, cx) {
9338 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9339 s.select(vec![Selection {
9340 id: selection.id,
9341 start: primary_range.start,
9342 end: primary_range.start,
9343 reversed: false,
9344 goal: SelectionGoal::None,
9345 }]);
9346 });
9347 }
9348 break;
9349 } else {
9350 // Cycle around to the start of the buffer, potentially moving back to the start of
9351 // the currently active diagnostic.
9352 active_primary_range.take();
9353 if direction == Direction::Prev {
9354 if search_start == buffer.len() {
9355 break;
9356 } else {
9357 search_start = buffer.len();
9358 }
9359 } else if search_start == 0 {
9360 break;
9361 } else {
9362 search_start = 0;
9363 }
9364 }
9365 }
9366 }
9367
9368 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9369 let snapshot = self
9370 .display_map
9371 .update(cx, |display_map, cx| display_map.snapshot(cx));
9372 let selection = self.selections.newest::<Point>(cx);
9373 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9374 }
9375
9376 fn go_to_hunk_after_position(
9377 &mut self,
9378 snapshot: &DisplaySnapshot,
9379 position: Point,
9380 cx: &mut ViewContext<'_, Editor>,
9381 ) -> Option<MultiBufferDiffHunk> {
9382 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9383 snapshot,
9384 position,
9385 false,
9386 snapshot
9387 .buffer_snapshot
9388 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9389 cx,
9390 ) {
9391 return Some(hunk);
9392 }
9393
9394 let wrapped_point = Point::zero();
9395 self.go_to_next_hunk_in_direction(
9396 snapshot,
9397 wrapped_point,
9398 true,
9399 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9400 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9401 ),
9402 cx,
9403 )
9404 }
9405
9406 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9407 let snapshot = self
9408 .display_map
9409 .update(cx, |display_map, cx| display_map.snapshot(cx));
9410 let selection = self.selections.newest::<Point>(cx);
9411
9412 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9413 }
9414
9415 fn go_to_hunk_before_position(
9416 &mut self,
9417 snapshot: &DisplaySnapshot,
9418 position: Point,
9419 cx: &mut ViewContext<'_, Editor>,
9420 ) -> Option<MultiBufferDiffHunk> {
9421 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9422 snapshot,
9423 position,
9424 false,
9425 snapshot
9426 .buffer_snapshot
9427 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9428 cx,
9429 ) {
9430 return Some(hunk);
9431 }
9432
9433 let wrapped_point = snapshot.buffer_snapshot.max_point();
9434 self.go_to_next_hunk_in_direction(
9435 snapshot,
9436 wrapped_point,
9437 true,
9438 snapshot
9439 .buffer_snapshot
9440 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9441 cx,
9442 )
9443 }
9444
9445 fn go_to_next_hunk_in_direction(
9446 &mut self,
9447 snapshot: &DisplaySnapshot,
9448 initial_point: Point,
9449 is_wrapped: bool,
9450 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9451 cx: &mut ViewContext<Editor>,
9452 ) -> Option<MultiBufferDiffHunk> {
9453 let display_point = initial_point.to_display_point(snapshot);
9454 let mut hunks = hunks
9455 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9456 .filter(|(display_hunk, _)| {
9457 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9458 })
9459 .dedup();
9460
9461 if let Some((display_hunk, hunk)) = hunks.next() {
9462 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9463 let row = display_hunk.start_display_row();
9464 let point = DisplayPoint::new(row, 0);
9465 s.select_display_ranges([point..point]);
9466 });
9467
9468 Some(hunk)
9469 } else {
9470 None
9471 }
9472 }
9473
9474 pub fn go_to_definition(
9475 &mut self,
9476 _: &GoToDefinition,
9477 cx: &mut ViewContext<Self>,
9478 ) -> Task<Result<Navigated>> {
9479 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9480 cx.spawn(|editor, mut cx| async move {
9481 if definition.await? == Navigated::Yes {
9482 return Ok(Navigated::Yes);
9483 }
9484 match editor.update(&mut cx, |editor, cx| {
9485 editor.find_all_references(&FindAllReferences, cx)
9486 })? {
9487 Some(references) => references.await,
9488 None => Ok(Navigated::No),
9489 }
9490 })
9491 }
9492
9493 pub fn go_to_declaration(
9494 &mut self,
9495 _: &GoToDeclaration,
9496 cx: &mut ViewContext<Self>,
9497 ) -> Task<Result<Navigated>> {
9498 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9499 }
9500
9501 pub fn go_to_declaration_split(
9502 &mut self,
9503 _: &GoToDeclaration,
9504 cx: &mut ViewContext<Self>,
9505 ) -> Task<Result<Navigated>> {
9506 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9507 }
9508
9509 pub fn go_to_implementation(
9510 &mut self,
9511 _: &GoToImplementation,
9512 cx: &mut ViewContext<Self>,
9513 ) -> Task<Result<Navigated>> {
9514 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9515 }
9516
9517 pub fn go_to_implementation_split(
9518 &mut self,
9519 _: &GoToImplementationSplit,
9520 cx: &mut ViewContext<Self>,
9521 ) -> Task<Result<Navigated>> {
9522 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9523 }
9524
9525 pub fn go_to_type_definition(
9526 &mut self,
9527 _: &GoToTypeDefinition,
9528 cx: &mut ViewContext<Self>,
9529 ) -> Task<Result<Navigated>> {
9530 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9531 }
9532
9533 pub fn go_to_definition_split(
9534 &mut self,
9535 _: &GoToDefinitionSplit,
9536 cx: &mut ViewContext<Self>,
9537 ) -> Task<Result<Navigated>> {
9538 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9539 }
9540
9541 pub fn go_to_type_definition_split(
9542 &mut self,
9543 _: &GoToTypeDefinitionSplit,
9544 cx: &mut ViewContext<Self>,
9545 ) -> Task<Result<Navigated>> {
9546 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9547 }
9548
9549 fn go_to_definition_of_kind(
9550 &mut self,
9551 kind: GotoDefinitionKind,
9552 split: bool,
9553 cx: &mut ViewContext<Self>,
9554 ) -> Task<Result<Navigated>> {
9555 let Some(workspace) = self.workspace() else {
9556 return Task::ready(Ok(Navigated::No));
9557 };
9558 let buffer = self.buffer.read(cx);
9559 let head = self.selections.newest::<usize>(cx).head();
9560 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9561 text_anchor
9562 } else {
9563 return Task::ready(Ok(Navigated::No));
9564 };
9565
9566 let project = workspace.read(cx).project().clone();
9567 let definitions = project.update(cx, |project, cx| match kind {
9568 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9569 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9570 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9571 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9572 });
9573
9574 cx.spawn(|editor, mut cx| async move {
9575 let definitions = definitions.await?;
9576 let navigated = editor
9577 .update(&mut cx, |editor, cx| {
9578 editor.navigate_to_hover_links(
9579 Some(kind),
9580 definitions
9581 .into_iter()
9582 .filter(|location| {
9583 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9584 })
9585 .map(HoverLink::Text)
9586 .collect::<Vec<_>>(),
9587 split,
9588 cx,
9589 )
9590 })?
9591 .await?;
9592 anyhow::Ok(navigated)
9593 })
9594 }
9595
9596 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9597 let position = self.selections.newest_anchor().head();
9598 let Some((buffer, buffer_position)) =
9599 self.buffer.read(cx).text_anchor_for_position(position, cx)
9600 else {
9601 return;
9602 };
9603
9604 cx.spawn(|editor, mut cx| async move {
9605 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9606 editor.update(&mut cx, |_, cx| {
9607 cx.open_url(&url);
9608 })
9609 } else {
9610 Ok(())
9611 }
9612 })
9613 .detach();
9614 }
9615
9616 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9617 let Some(workspace) = self.workspace() else {
9618 return;
9619 };
9620
9621 let position = self.selections.newest_anchor().head();
9622
9623 let Some((buffer, buffer_position)) =
9624 self.buffer.read(cx).text_anchor_for_position(position, cx)
9625 else {
9626 return;
9627 };
9628
9629 let Some(project) = self.project.clone() else {
9630 return;
9631 };
9632
9633 cx.spawn(|_, mut cx| async move {
9634 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9635
9636 if let Some((_, path)) = result {
9637 workspace
9638 .update(&mut cx, |workspace, cx| {
9639 workspace.open_resolved_path(path, cx)
9640 })?
9641 .await?;
9642 }
9643 anyhow::Ok(())
9644 })
9645 .detach();
9646 }
9647
9648 pub(crate) fn navigate_to_hover_links(
9649 &mut self,
9650 kind: Option<GotoDefinitionKind>,
9651 mut definitions: Vec<HoverLink>,
9652 split: bool,
9653 cx: &mut ViewContext<Editor>,
9654 ) -> Task<Result<Navigated>> {
9655 // If there is one definition, just open it directly
9656 if definitions.len() == 1 {
9657 let definition = definitions.pop().unwrap();
9658
9659 enum TargetTaskResult {
9660 Location(Option<Location>),
9661 AlreadyNavigated,
9662 }
9663
9664 let target_task = match definition {
9665 HoverLink::Text(link) => {
9666 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9667 }
9668 HoverLink::InlayHint(lsp_location, server_id) => {
9669 let computation = self.compute_target_location(lsp_location, server_id, cx);
9670 cx.background_executor().spawn(async move {
9671 let location = computation.await?;
9672 Ok(TargetTaskResult::Location(location))
9673 })
9674 }
9675 HoverLink::Url(url) => {
9676 cx.open_url(&url);
9677 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9678 }
9679 HoverLink::File(path) => {
9680 if let Some(workspace) = self.workspace() {
9681 cx.spawn(|_, mut cx| async move {
9682 workspace
9683 .update(&mut cx, |workspace, cx| {
9684 workspace.open_resolved_path(path, cx)
9685 })?
9686 .await
9687 .map(|_| TargetTaskResult::AlreadyNavigated)
9688 })
9689 } else {
9690 Task::ready(Ok(TargetTaskResult::Location(None)))
9691 }
9692 }
9693 };
9694 cx.spawn(|editor, mut cx| async move {
9695 let target = match target_task.await.context("target resolution task")? {
9696 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9697 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9698 TargetTaskResult::Location(Some(target)) => target,
9699 };
9700
9701 editor.update(&mut cx, |editor, cx| {
9702 let Some(workspace) = editor.workspace() else {
9703 return Navigated::No;
9704 };
9705 let pane = workspace.read(cx).active_pane().clone();
9706
9707 let range = target.range.to_offset(target.buffer.read(cx));
9708 let range = editor.range_for_match(&range);
9709
9710 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9711 let buffer = target.buffer.read(cx);
9712 let range = check_multiline_range(buffer, range);
9713 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9714 s.select_ranges([range]);
9715 });
9716 } else {
9717 cx.window_context().defer(move |cx| {
9718 let target_editor: View<Self> =
9719 workspace.update(cx, |workspace, cx| {
9720 let pane = if split {
9721 workspace.adjacent_pane(cx)
9722 } else {
9723 workspace.active_pane().clone()
9724 };
9725
9726 workspace.open_project_item(
9727 pane,
9728 target.buffer.clone(),
9729 true,
9730 true,
9731 cx,
9732 )
9733 });
9734 target_editor.update(cx, |target_editor, cx| {
9735 // When selecting a definition in a different buffer, disable the nav history
9736 // to avoid creating a history entry at the previous cursor location.
9737 pane.update(cx, |pane, _| pane.disable_history());
9738 let buffer = target.buffer.read(cx);
9739 let range = check_multiline_range(buffer, range);
9740 target_editor.change_selections(
9741 Some(Autoscroll::focused()),
9742 cx,
9743 |s| {
9744 s.select_ranges([range]);
9745 },
9746 );
9747 pane.update(cx, |pane, _| pane.enable_history());
9748 });
9749 });
9750 }
9751 Navigated::Yes
9752 })
9753 })
9754 } else if !definitions.is_empty() {
9755 cx.spawn(|editor, mut cx| async move {
9756 let (title, location_tasks, workspace) = editor
9757 .update(&mut cx, |editor, cx| {
9758 let tab_kind = match kind {
9759 Some(GotoDefinitionKind::Implementation) => "Implementations",
9760 _ => "Definitions",
9761 };
9762 let title = definitions
9763 .iter()
9764 .find_map(|definition| match definition {
9765 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9766 let buffer = origin.buffer.read(cx);
9767 format!(
9768 "{} for {}",
9769 tab_kind,
9770 buffer
9771 .text_for_range(origin.range.clone())
9772 .collect::<String>()
9773 )
9774 }),
9775 HoverLink::InlayHint(_, _) => None,
9776 HoverLink::Url(_) => None,
9777 HoverLink::File(_) => None,
9778 })
9779 .unwrap_or(tab_kind.to_string());
9780 let location_tasks = definitions
9781 .into_iter()
9782 .map(|definition| match definition {
9783 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9784 HoverLink::InlayHint(lsp_location, server_id) => {
9785 editor.compute_target_location(lsp_location, server_id, cx)
9786 }
9787 HoverLink::Url(_) => Task::ready(Ok(None)),
9788 HoverLink::File(_) => Task::ready(Ok(None)),
9789 })
9790 .collect::<Vec<_>>();
9791 (title, location_tasks, editor.workspace().clone())
9792 })
9793 .context("location tasks preparation")?;
9794
9795 let locations = future::join_all(location_tasks)
9796 .await
9797 .into_iter()
9798 .filter_map(|location| location.transpose())
9799 .collect::<Result<_>>()
9800 .context("location tasks")?;
9801
9802 let Some(workspace) = workspace else {
9803 return Ok(Navigated::No);
9804 };
9805 let opened = workspace
9806 .update(&mut cx, |workspace, cx| {
9807 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9808 })
9809 .ok();
9810
9811 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9812 })
9813 } else {
9814 Task::ready(Ok(Navigated::No))
9815 }
9816 }
9817
9818 fn compute_target_location(
9819 &self,
9820 lsp_location: lsp::Location,
9821 server_id: LanguageServerId,
9822 cx: &mut ViewContext<Editor>,
9823 ) -> Task<anyhow::Result<Option<Location>>> {
9824 let Some(project) = self.project.clone() else {
9825 return Task::Ready(Some(Ok(None)));
9826 };
9827
9828 cx.spawn(move |editor, mut cx| async move {
9829 let location_task = editor.update(&mut cx, |editor, cx| {
9830 project.update(cx, |project, cx| {
9831 let language_server_name =
9832 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9833 project
9834 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9835 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9836 });
9837 language_server_name.map(|language_server_name| {
9838 project.open_local_buffer_via_lsp(
9839 lsp_location.uri.clone(),
9840 server_id,
9841 language_server_name,
9842 cx,
9843 )
9844 })
9845 })
9846 })?;
9847 let location = match location_task {
9848 Some(task) => Some({
9849 let target_buffer_handle = task.await.context("open local buffer")?;
9850 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9851 let target_start = target_buffer
9852 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9853 let target_end = target_buffer
9854 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9855 target_buffer.anchor_after(target_start)
9856 ..target_buffer.anchor_before(target_end)
9857 })?;
9858 Location {
9859 buffer: target_buffer_handle,
9860 range,
9861 }
9862 }),
9863 None => None,
9864 };
9865 Ok(location)
9866 })
9867 }
9868
9869 pub fn find_all_references(
9870 &mut self,
9871 _: &FindAllReferences,
9872 cx: &mut ViewContext<Self>,
9873 ) -> Option<Task<Result<Navigated>>> {
9874 let multi_buffer = self.buffer.read(cx);
9875 let selection = self.selections.newest::<usize>(cx);
9876 let head = selection.head();
9877
9878 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9879 let head_anchor = multi_buffer_snapshot.anchor_at(
9880 head,
9881 if head < selection.tail() {
9882 Bias::Right
9883 } else {
9884 Bias::Left
9885 },
9886 );
9887
9888 match self
9889 .find_all_references_task_sources
9890 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9891 {
9892 Ok(_) => {
9893 log::info!(
9894 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9895 );
9896 return None;
9897 }
9898 Err(i) => {
9899 self.find_all_references_task_sources.insert(i, head_anchor);
9900 }
9901 }
9902
9903 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9904 let workspace = self.workspace()?;
9905 let project = workspace.read(cx).project().clone();
9906 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9907 Some(cx.spawn(|editor, mut cx| async move {
9908 let _cleanup = defer({
9909 let mut cx = cx.clone();
9910 move || {
9911 let _ = editor.update(&mut cx, |editor, _| {
9912 if let Ok(i) =
9913 editor
9914 .find_all_references_task_sources
9915 .binary_search_by(|anchor| {
9916 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9917 })
9918 {
9919 editor.find_all_references_task_sources.remove(i);
9920 }
9921 });
9922 }
9923 });
9924
9925 let locations = references.await?;
9926 if locations.is_empty() {
9927 return anyhow::Ok(Navigated::No);
9928 }
9929
9930 workspace.update(&mut cx, |workspace, cx| {
9931 let title = locations
9932 .first()
9933 .as_ref()
9934 .map(|location| {
9935 let buffer = location.buffer.read(cx);
9936 format!(
9937 "References to `{}`",
9938 buffer
9939 .text_for_range(location.range.clone())
9940 .collect::<String>()
9941 )
9942 })
9943 .unwrap();
9944 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9945 Navigated::Yes
9946 })
9947 }))
9948 }
9949
9950 /// Opens a multibuffer with the given project locations in it
9951 pub fn open_locations_in_multibuffer(
9952 workspace: &mut Workspace,
9953 mut locations: Vec<Location>,
9954 title: String,
9955 split: bool,
9956 cx: &mut ViewContext<Workspace>,
9957 ) {
9958 // If there are multiple definitions, open them in a multibuffer
9959 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9960 let mut locations = locations.into_iter().peekable();
9961 let mut ranges_to_highlight = Vec::new();
9962 let capability = workspace.project().read(cx).capability();
9963
9964 let excerpt_buffer = cx.new_model(|cx| {
9965 let mut multibuffer = MultiBuffer::new(capability);
9966 while let Some(location) = locations.next() {
9967 let buffer = location.buffer.read(cx);
9968 let mut ranges_for_buffer = Vec::new();
9969 let range = location.range.to_offset(buffer);
9970 ranges_for_buffer.push(range.clone());
9971
9972 while let Some(next_location) = locations.peek() {
9973 if next_location.buffer == location.buffer {
9974 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9975 locations.next();
9976 } else {
9977 break;
9978 }
9979 }
9980
9981 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9982 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9983 location.buffer.clone(),
9984 ranges_for_buffer,
9985 DEFAULT_MULTIBUFFER_CONTEXT,
9986 cx,
9987 ))
9988 }
9989
9990 multibuffer.with_title(title)
9991 });
9992
9993 let editor = cx.new_view(|cx| {
9994 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9995 });
9996 editor.update(cx, |editor, cx| {
9997 if let Some(first_range) = ranges_to_highlight.first() {
9998 editor.change_selections(None, cx, |selections| {
9999 selections.clear_disjoint();
10000 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10001 });
10002 }
10003 editor.highlight_background::<Self>(
10004 &ranges_to_highlight,
10005 |theme| theme.editor_highlighted_line_background,
10006 cx,
10007 );
10008 });
10009
10010 let item = Box::new(editor);
10011 let item_id = item.item_id();
10012
10013 if split {
10014 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10015 } else {
10016 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10017 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10018 pane.close_current_preview_item(cx)
10019 } else {
10020 None
10021 }
10022 });
10023 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10024 }
10025 workspace.active_pane().update(cx, |pane, cx| {
10026 pane.set_preview_item_id(Some(item_id), cx);
10027 });
10028 }
10029
10030 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10031 use language::ToOffset as _;
10032
10033 let project = self.project.clone()?;
10034 let selection = self.selections.newest_anchor().clone();
10035 let (cursor_buffer, cursor_buffer_position) = self
10036 .buffer
10037 .read(cx)
10038 .text_anchor_for_position(selection.head(), cx)?;
10039 let (tail_buffer, cursor_buffer_position_end) = self
10040 .buffer
10041 .read(cx)
10042 .text_anchor_for_position(selection.tail(), cx)?;
10043 if tail_buffer != cursor_buffer {
10044 return None;
10045 }
10046
10047 let snapshot = cursor_buffer.read(cx).snapshot();
10048 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10049 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10050 let prepare_rename = project.update(cx, |project, cx| {
10051 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
10052 });
10053 drop(snapshot);
10054
10055 Some(cx.spawn(|this, mut cx| async move {
10056 let rename_range = if let Some(range) = prepare_rename.await? {
10057 Some(range)
10058 } else {
10059 this.update(&mut cx, |this, cx| {
10060 let buffer = this.buffer.read(cx).snapshot(cx);
10061 let mut buffer_highlights = this
10062 .document_highlights_for_position(selection.head(), &buffer)
10063 .filter(|highlight| {
10064 highlight.start.excerpt_id == selection.head().excerpt_id
10065 && highlight.end.excerpt_id == selection.head().excerpt_id
10066 });
10067 buffer_highlights
10068 .next()
10069 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10070 })?
10071 };
10072 if let Some(rename_range) = rename_range {
10073 this.update(&mut cx, |this, cx| {
10074 let snapshot = cursor_buffer.read(cx).snapshot();
10075 let rename_buffer_range = rename_range.to_offset(&snapshot);
10076 let cursor_offset_in_rename_range =
10077 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10078 let cursor_offset_in_rename_range_end =
10079 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10080
10081 this.take_rename(false, cx);
10082 let buffer = this.buffer.read(cx).read(cx);
10083 let cursor_offset = selection.head().to_offset(&buffer);
10084 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10085 let rename_end = rename_start + rename_buffer_range.len();
10086 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10087 let mut old_highlight_id = None;
10088 let old_name: Arc<str> = buffer
10089 .chunks(rename_start..rename_end, true)
10090 .map(|chunk| {
10091 if old_highlight_id.is_none() {
10092 old_highlight_id = chunk.syntax_highlight_id;
10093 }
10094 chunk.text
10095 })
10096 .collect::<String>()
10097 .into();
10098
10099 drop(buffer);
10100
10101 // Position the selection in the rename editor so that it matches the current selection.
10102 this.show_local_selections = false;
10103 let rename_editor = cx.new_view(|cx| {
10104 let mut editor = Editor::single_line(cx);
10105 editor.buffer.update(cx, |buffer, cx| {
10106 buffer.edit([(0..0, old_name.clone())], None, cx)
10107 });
10108 let rename_selection_range = match cursor_offset_in_rename_range
10109 .cmp(&cursor_offset_in_rename_range_end)
10110 {
10111 Ordering::Equal => {
10112 editor.select_all(&SelectAll, cx);
10113 return editor;
10114 }
10115 Ordering::Less => {
10116 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10117 }
10118 Ordering::Greater => {
10119 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10120 }
10121 };
10122 if rename_selection_range.end > old_name.len() {
10123 editor.select_all(&SelectAll, cx);
10124 } else {
10125 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10126 s.select_ranges([rename_selection_range]);
10127 });
10128 }
10129 editor
10130 });
10131 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10132 if e == &EditorEvent::Focused {
10133 cx.emit(EditorEvent::FocusedIn)
10134 }
10135 })
10136 .detach();
10137
10138 let write_highlights =
10139 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10140 let read_highlights =
10141 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10142 let ranges = write_highlights
10143 .iter()
10144 .flat_map(|(_, ranges)| ranges.iter())
10145 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10146 .cloned()
10147 .collect();
10148
10149 this.highlight_text::<Rename>(
10150 ranges,
10151 HighlightStyle {
10152 fade_out: Some(0.6),
10153 ..Default::default()
10154 },
10155 cx,
10156 );
10157 let rename_focus_handle = rename_editor.focus_handle(cx);
10158 cx.focus(&rename_focus_handle);
10159 let block_id = this.insert_blocks(
10160 [BlockProperties {
10161 style: BlockStyle::Flex,
10162 position: range.start,
10163 height: 1,
10164 render: Box::new({
10165 let rename_editor = rename_editor.clone();
10166 move |cx: &mut BlockContext| {
10167 let mut text_style = cx.editor_style.text.clone();
10168 if let Some(highlight_style) = old_highlight_id
10169 .and_then(|h| h.style(&cx.editor_style.syntax))
10170 {
10171 text_style = text_style.highlight(highlight_style);
10172 }
10173 div()
10174 .pl(cx.anchor_x)
10175 .child(EditorElement::new(
10176 &rename_editor,
10177 EditorStyle {
10178 background: cx.theme().system().transparent,
10179 local_player: cx.editor_style.local_player,
10180 text: text_style,
10181 scrollbar_width: cx.editor_style.scrollbar_width,
10182 syntax: cx.editor_style.syntax.clone(),
10183 status: cx.editor_style.status.clone(),
10184 inlay_hints_style: HighlightStyle {
10185 font_weight: Some(FontWeight::BOLD),
10186 ..make_inlay_hints_style(cx)
10187 },
10188 suggestions_style: HighlightStyle {
10189 color: Some(cx.theme().status().predictive),
10190 ..HighlightStyle::default()
10191 },
10192 ..EditorStyle::default()
10193 },
10194 ))
10195 .into_any_element()
10196 }
10197 }),
10198 disposition: BlockDisposition::Below,
10199 priority: 0,
10200 }],
10201 Some(Autoscroll::fit()),
10202 cx,
10203 )[0];
10204 this.pending_rename = Some(RenameState {
10205 range,
10206 old_name,
10207 editor: rename_editor,
10208 block_id,
10209 });
10210 })?;
10211 }
10212
10213 Ok(())
10214 }))
10215 }
10216
10217 pub fn confirm_rename(
10218 &mut self,
10219 _: &ConfirmRename,
10220 cx: &mut ViewContext<Self>,
10221 ) -> Option<Task<Result<()>>> {
10222 let rename = self.take_rename(false, cx)?;
10223 let workspace = self.workspace()?;
10224 let (start_buffer, start) = self
10225 .buffer
10226 .read(cx)
10227 .text_anchor_for_position(rename.range.start, cx)?;
10228 let (end_buffer, end) = self
10229 .buffer
10230 .read(cx)
10231 .text_anchor_for_position(rename.range.end, cx)?;
10232 if start_buffer != end_buffer {
10233 return None;
10234 }
10235
10236 let buffer = start_buffer;
10237 let range = start..end;
10238 let old_name = rename.old_name;
10239 let new_name = rename.editor.read(cx).text(cx);
10240
10241 let rename = workspace
10242 .read(cx)
10243 .project()
10244 .clone()
10245 .update(cx, |project, cx| {
10246 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10247 });
10248 let workspace = workspace.downgrade();
10249
10250 Some(cx.spawn(|editor, mut cx| async move {
10251 let project_transaction = rename.await?;
10252 Self::open_project_transaction(
10253 &editor,
10254 workspace,
10255 project_transaction,
10256 format!("Rename: {} → {}", old_name, new_name),
10257 cx.clone(),
10258 )
10259 .await?;
10260
10261 editor.update(&mut cx, |editor, cx| {
10262 editor.refresh_document_highlights(cx);
10263 })?;
10264 Ok(())
10265 }))
10266 }
10267
10268 fn take_rename(
10269 &mut self,
10270 moving_cursor: bool,
10271 cx: &mut ViewContext<Self>,
10272 ) -> Option<RenameState> {
10273 let rename = self.pending_rename.take()?;
10274 if rename.editor.focus_handle(cx).is_focused(cx) {
10275 cx.focus(&self.focus_handle);
10276 }
10277
10278 self.remove_blocks(
10279 [rename.block_id].into_iter().collect(),
10280 Some(Autoscroll::fit()),
10281 cx,
10282 );
10283 self.clear_highlights::<Rename>(cx);
10284 self.show_local_selections = true;
10285
10286 if moving_cursor {
10287 let rename_editor = rename.editor.read(cx);
10288 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10289
10290 // Update the selection to match the position of the selection inside
10291 // the rename editor.
10292 let snapshot = self.buffer.read(cx).read(cx);
10293 let rename_range = rename.range.to_offset(&snapshot);
10294 let cursor_in_editor = snapshot
10295 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10296 .min(rename_range.end);
10297 drop(snapshot);
10298
10299 self.change_selections(None, cx, |s| {
10300 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10301 });
10302 } else {
10303 self.refresh_document_highlights(cx);
10304 }
10305
10306 Some(rename)
10307 }
10308
10309 pub fn pending_rename(&self) -> Option<&RenameState> {
10310 self.pending_rename.as_ref()
10311 }
10312
10313 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10314 let project = match &self.project {
10315 Some(project) => project.clone(),
10316 None => return None,
10317 };
10318
10319 Some(self.perform_format(project, FormatTrigger::Manual, cx))
10320 }
10321
10322 fn perform_format(
10323 &mut self,
10324 project: Model<Project>,
10325 trigger: FormatTrigger,
10326 cx: &mut ViewContext<Self>,
10327 ) -> Task<Result<()>> {
10328 let buffer = self.buffer().clone();
10329 let mut buffers = buffer.read(cx).all_buffers();
10330 if trigger == FormatTrigger::Save {
10331 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10332 }
10333
10334 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10335 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10336
10337 cx.spawn(|_, mut cx| async move {
10338 let transaction = futures::select_biased! {
10339 () = timeout => {
10340 log::warn!("timed out waiting for formatting");
10341 None
10342 }
10343 transaction = format.log_err().fuse() => transaction,
10344 };
10345
10346 buffer
10347 .update(&mut cx, |buffer, cx| {
10348 if let Some(transaction) = transaction {
10349 if !buffer.is_singleton() {
10350 buffer.push_transaction(&transaction.0, cx);
10351 }
10352 }
10353
10354 cx.notify();
10355 })
10356 .ok();
10357
10358 Ok(())
10359 })
10360 }
10361
10362 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10363 if let Some(project) = self.project.clone() {
10364 self.buffer.update(cx, |multi_buffer, cx| {
10365 project.update(cx, |project, cx| {
10366 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10367 });
10368 })
10369 }
10370 }
10371
10372 fn cancel_language_server_work(
10373 &mut self,
10374 _: &CancelLanguageServerWork,
10375 cx: &mut ViewContext<Self>,
10376 ) {
10377 if let Some(project) = self.project.clone() {
10378 self.buffer.update(cx, |multi_buffer, cx| {
10379 project.update(cx, |project, cx| {
10380 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10381 });
10382 })
10383 }
10384 }
10385
10386 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10387 cx.show_character_palette();
10388 }
10389
10390 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10391 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10392 let buffer = self.buffer.read(cx).snapshot(cx);
10393 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10394 let is_valid = buffer
10395 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10396 .any(|entry| {
10397 entry.diagnostic.is_primary
10398 && !entry.range.is_empty()
10399 && entry.range.start == primary_range_start
10400 && entry.diagnostic.message == active_diagnostics.primary_message
10401 });
10402
10403 if is_valid != active_diagnostics.is_valid {
10404 active_diagnostics.is_valid = is_valid;
10405 let mut new_styles = HashMap::default();
10406 for (block_id, diagnostic) in &active_diagnostics.blocks {
10407 new_styles.insert(
10408 *block_id,
10409 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10410 );
10411 }
10412 self.display_map.update(cx, |display_map, _cx| {
10413 display_map.replace_blocks(new_styles)
10414 });
10415 }
10416 }
10417 }
10418
10419 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10420 self.dismiss_diagnostics(cx);
10421 let snapshot = self.snapshot(cx);
10422 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10423 let buffer = self.buffer.read(cx).snapshot(cx);
10424
10425 let mut primary_range = None;
10426 let mut primary_message = None;
10427 let mut group_end = Point::zero();
10428 let diagnostic_group = buffer
10429 .diagnostic_group::<MultiBufferPoint>(group_id)
10430 .filter_map(|entry| {
10431 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10432 && (entry.range.start.row == entry.range.end.row
10433 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10434 {
10435 return None;
10436 }
10437 if entry.range.end > group_end {
10438 group_end = entry.range.end;
10439 }
10440 if entry.diagnostic.is_primary {
10441 primary_range = Some(entry.range.clone());
10442 primary_message = Some(entry.diagnostic.message.clone());
10443 }
10444 Some(entry)
10445 })
10446 .collect::<Vec<_>>();
10447 let primary_range = primary_range?;
10448 let primary_message = primary_message?;
10449 let primary_range =
10450 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10451
10452 let blocks = display_map
10453 .insert_blocks(
10454 diagnostic_group.iter().map(|entry| {
10455 let diagnostic = entry.diagnostic.clone();
10456 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10457 BlockProperties {
10458 style: BlockStyle::Fixed,
10459 position: buffer.anchor_after(entry.range.start),
10460 height: message_height,
10461 render: diagnostic_block_renderer(diagnostic, None, true, true),
10462 disposition: BlockDisposition::Below,
10463 priority: 0,
10464 }
10465 }),
10466 cx,
10467 )
10468 .into_iter()
10469 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10470 .collect();
10471
10472 Some(ActiveDiagnosticGroup {
10473 primary_range,
10474 primary_message,
10475 group_id,
10476 blocks,
10477 is_valid: true,
10478 })
10479 });
10480 self.active_diagnostics.is_some()
10481 }
10482
10483 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10484 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10485 self.display_map.update(cx, |display_map, cx| {
10486 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10487 });
10488 cx.notify();
10489 }
10490 }
10491
10492 pub fn set_selections_from_remote(
10493 &mut self,
10494 selections: Vec<Selection<Anchor>>,
10495 pending_selection: Option<Selection<Anchor>>,
10496 cx: &mut ViewContext<Self>,
10497 ) {
10498 let old_cursor_position = self.selections.newest_anchor().head();
10499 self.selections.change_with(cx, |s| {
10500 s.select_anchors(selections);
10501 if let Some(pending_selection) = pending_selection {
10502 s.set_pending(pending_selection, SelectMode::Character);
10503 } else {
10504 s.clear_pending();
10505 }
10506 });
10507 self.selections_did_change(false, &old_cursor_position, true, cx);
10508 }
10509
10510 fn push_to_selection_history(&mut self) {
10511 self.selection_history.push(SelectionHistoryEntry {
10512 selections: self.selections.disjoint_anchors(),
10513 select_next_state: self.select_next_state.clone(),
10514 select_prev_state: self.select_prev_state.clone(),
10515 add_selections_state: self.add_selections_state.clone(),
10516 });
10517 }
10518
10519 pub fn transact(
10520 &mut self,
10521 cx: &mut ViewContext<Self>,
10522 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10523 ) -> Option<TransactionId> {
10524 self.start_transaction_at(Instant::now(), cx);
10525 update(self, cx);
10526 self.end_transaction_at(Instant::now(), cx)
10527 }
10528
10529 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10530 self.end_selection(cx);
10531 if let Some(tx_id) = self
10532 .buffer
10533 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10534 {
10535 self.selection_history
10536 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10537 cx.emit(EditorEvent::TransactionBegun {
10538 transaction_id: tx_id,
10539 })
10540 }
10541 }
10542
10543 fn end_transaction_at(
10544 &mut self,
10545 now: Instant,
10546 cx: &mut ViewContext<Self>,
10547 ) -> Option<TransactionId> {
10548 if let Some(transaction_id) = self
10549 .buffer
10550 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10551 {
10552 if let Some((_, end_selections)) =
10553 self.selection_history.transaction_mut(transaction_id)
10554 {
10555 *end_selections = Some(self.selections.disjoint_anchors());
10556 } else {
10557 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10558 }
10559
10560 cx.emit(EditorEvent::Edited { transaction_id });
10561 Some(transaction_id)
10562 } else {
10563 None
10564 }
10565 }
10566
10567 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10568 let selection = self.selections.newest::<Point>(cx);
10569
10570 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10571 let range = if selection.is_empty() {
10572 let point = selection.head().to_display_point(&display_map);
10573 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10574 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10575 .to_point(&display_map);
10576 start..end
10577 } else {
10578 selection.range()
10579 };
10580 if display_map.folds_in_range(range).next().is_some() {
10581 self.unfold_lines(&Default::default(), cx)
10582 } else {
10583 self.fold(&Default::default(), cx)
10584 }
10585 }
10586
10587 pub fn toggle_fold_recursive(
10588 &mut self,
10589 _: &actions::ToggleFoldRecursive,
10590 cx: &mut ViewContext<Self>,
10591 ) {
10592 let selection = self.selections.newest::<Point>(cx);
10593
10594 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10595 let range = if selection.is_empty() {
10596 let point = selection.head().to_display_point(&display_map);
10597 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10598 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10599 .to_point(&display_map);
10600 start..end
10601 } else {
10602 selection.range()
10603 };
10604 if display_map.folds_in_range(range).next().is_some() {
10605 self.unfold_recursive(&Default::default(), cx)
10606 } else {
10607 self.fold_recursive(&Default::default(), cx)
10608 }
10609 }
10610
10611 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10612 let mut fold_ranges = Vec::new();
10613 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10614 let selections = self.selections.all_adjusted(cx);
10615
10616 for selection in selections {
10617 let range = selection.range().sorted();
10618 let buffer_start_row = range.start.row;
10619
10620 if range.start.row != range.end.row {
10621 let mut found = false;
10622 let mut row = range.start.row;
10623 while row <= range.end.row {
10624 if let Some((foldable_range, fold_text)) =
10625 { display_map.foldable_range(MultiBufferRow(row)) }
10626 {
10627 found = true;
10628 row = foldable_range.end.row + 1;
10629 fold_ranges.push((foldable_range, fold_text));
10630 } else {
10631 row += 1
10632 }
10633 }
10634 if found {
10635 continue;
10636 }
10637 }
10638
10639 for row in (0..=range.start.row).rev() {
10640 if let Some((foldable_range, fold_text)) =
10641 display_map.foldable_range(MultiBufferRow(row))
10642 {
10643 if foldable_range.end.row >= buffer_start_row {
10644 fold_ranges.push((foldable_range, fold_text));
10645 if row <= range.start.row {
10646 break;
10647 }
10648 }
10649 }
10650 }
10651 }
10652
10653 self.fold_ranges(fold_ranges, true, cx);
10654 }
10655
10656 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10657 let mut fold_ranges = Vec::new();
10658 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10659
10660 for row in 0..display_map.max_buffer_row().0 {
10661 if let Some((foldable_range, fold_text)) =
10662 display_map.foldable_range(MultiBufferRow(row))
10663 {
10664 fold_ranges.push((foldable_range, fold_text));
10665 }
10666 }
10667
10668 self.fold_ranges(fold_ranges, true, cx);
10669 }
10670
10671 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10672 let mut fold_ranges = Vec::new();
10673 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10674 let selections = self.selections.all_adjusted(cx);
10675
10676 for selection in selections {
10677 let range = selection.range().sorted();
10678 let buffer_start_row = range.start.row;
10679
10680 if range.start.row != range.end.row {
10681 let mut found = false;
10682 for row in range.start.row..=range.end.row {
10683 if let Some((foldable_range, fold_text)) =
10684 { display_map.foldable_range(MultiBufferRow(row)) }
10685 {
10686 found = true;
10687 fold_ranges.push((foldable_range, fold_text));
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 } else {
10702 break;
10703 }
10704 }
10705 }
10706 }
10707
10708 self.fold_ranges(fold_ranges, true, cx);
10709 }
10710
10711 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10712 let buffer_row = fold_at.buffer_row;
10713 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10714
10715 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10716 let autoscroll = self
10717 .selections
10718 .all::<Point>(cx)
10719 .iter()
10720 .any(|selection| fold_range.overlaps(&selection.range()));
10721
10722 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10723 }
10724 }
10725
10726 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10727 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10728 let buffer = &display_map.buffer_snapshot;
10729 let selections = self.selections.all::<Point>(cx);
10730 let ranges = selections
10731 .iter()
10732 .map(|s| {
10733 let range = s.display_range(&display_map).sorted();
10734 let mut start = range.start.to_point(&display_map);
10735 let mut end = range.end.to_point(&display_map);
10736 start.column = 0;
10737 end.column = buffer.line_len(MultiBufferRow(end.row));
10738 start..end
10739 })
10740 .collect::<Vec<_>>();
10741
10742 self.unfold_ranges(ranges, true, true, cx);
10743 }
10744
10745 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10746 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10747 let selections = self.selections.all::<Point>(cx);
10748 let ranges = selections
10749 .iter()
10750 .map(|s| {
10751 let mut range = s.display_range(&display_map).sorted();
10752 *range.start.column_mut() = 0;
10753 *range.end.column_mut() = display_map.line_len(range.end.row());
10754 let start = range.start.to_point(&display_map);
10755 let end = range.end.to_point(&display_map);
10756 start..end
10757 })
10758 .collect::<Vec<_>>();
10759
10760 self.unfold_ranges(ranges, true, true, cx);
10761 }
10762
10763 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10764 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10765
10766 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10767 ..Point::new(
10768 unfold_at.buffer_row.0,
10769 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10770 );
10771
10772 let autoscroll = self
10773 .selections
10774 .all::<Point>(cx)
10775 .iter()
10776 .any(|selection| selection.range().overlaps(&intersection_range));
10777
10778 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10779 }
10780
10781 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10782 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10783 self.unfold_ranges(
10784 [Point::zero()..display_map.max_point().to_point(&display_map)],
10785 true,
10786 true,
10787 cx,
10788 );
10789 }
10790
10791 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10792 let selections = self.selections.all::<Point>(cx);
10793 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10794 let line_mode = self.selections.line_mode;
10795 let ranges = selections.into_iter().map(|s| {
10796 if line_mode {
10797 let start = Point::new(s.start.row, 0);
10798 let end = Point::new(
10799 s.end.row,
10800 display_map
10801 .buffer_snapshot
10802 .line_len(MultiBufferRow(s.end.row)),
10803 );
10804 (start..end, display_map.fold_placeholder.clone())
10805 } else {
10806 (s.start..s.end, display_map.fold_placeholder.clone())
10807 }
10808 });
10809 self.fold_ranges(ranges, true, cx);
10810 }
10811
10812 pub fn fold_ranges<T: ToOffset + Clone>(
10813 &mut self,
10814 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10815 auto_scroll: bool,
10816 cx: &mut ViewContext<Self>,
10817 ) {
10818 let mut fold_ranges = Vec::new();
10819 let mut buffers_affected = HashMap::default();
10820 let multi_buffer = self.buffer().read(cx);
10821 for (fold_range, fold_text) in ranges {
10822 if let Some((_, buffer, _)) =
10823 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10824 {
10825 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10826 };
10827 fold_ranges.push((fold_range, fold_text));
10828 }
10829
10830 let mut ranges = fold_ranges.into_iter().peekable();
10831 if ranges.peek().is_some() {
10832 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10833
10834 if auto_scroll {
10835 self.request_autoscroll(Autoscroll::fit(), cx);
10836 }
10837
10838 for buffer in buffers_affected.into_values() {
10839 self.sync_expanded_diff_hunks(buffer, cx);
10840 }
10841
10842 cx.notify();
10843
10844 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10845 // Clear diagnostics block when folding a range that contains it.
10846 let snapshot = self.snapshot(cx);
10847 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10848 drop(snapshot);
10849 self.active_diagnostics = Some(active_diagnostics);
10850 self.dismiss_diagnostics(cx);
10851 } else {
10852 self.active_diagnostics = Some(active_diagnostics);
10853 }
10854 }
10855
10856 self.scrollbar_marker_state.dirty = true;
10857 }
10858 }
10859
10860 pub fn unfold_ranges<T: ToOffset + Clone>(
10861 &mut self,
10862 ranges: impl IntoIterator<Item = Range<T>>,
10863 inclusive: bool,
10864 auto_scroll: bool,
10865 cx: &mut ViewContext<Self>,
10866 ) {
10867 let mut unfold_ranges = Vec::new();
10868 let mut buffers_affected = HashMap::default();
10869 let multi_buffer = self.buffer().read(cx);
10870 for range in ranges {
10871 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10872 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10873 };
10874 unfold_ranges.push(range);
10875 }
10876
10877 let mut ranges = unfold_ranges.into_iter().peekable();
10878 if ranges.peek().is_some() {
10879 self.display_map
10880 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10881 if auto_scroll {
10882 self.request_autoscroll(Autoscroll::fit(), cx);
10883 }
10884
10885 for buffer in buffers_affected.into_values() {
10886 self.sync_expanded_diff_hunks(buffer, cx);
10887 }
10888
10889 cx.notify();
10890 self.scrollbar_marker_state.dirty = true;
10891 self.active_indent_guides_state.dirty = true;
10892 }
10893 }
10894
10895 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10896 self.display_map.read(cx).fold_placeholder.clone()
10897 }
10898
10899 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10900 if hovered != self.gutter_hovered {
10901 self.gutter_hovered = hovered;
10902 cx.notify();
10903 }
10904 }
10905
10906 pub fn insert_blocks(
10907 &mut self,
10908 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10909 autoscroll: Option<Autoscroll>,
10910 cx: &mut ViewContext<Self>,
10911 ) -> Vec<CustomBlockId> {
10912 let blocks = self
10913 .display_map
10914 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10915 if let Some(autoscroll) = autoscroll {
10916 self.request_autoscroll(autoscroll, cx);
10917 }
10918 cx.notify();
10919 blocks
10920 }
10921
10922 pub fn resize_blocks(
10923 &mut self,
10924 heights: HashMap<CustomBlockId, u32>,
10925 autoscroll: Option<Autoscroll>,
10926 cx: &mut ViewContext<Self>,
10927 ) {
10928 self.display_map
10929 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10930 if let Some(autoscroll) = autoscroll {
10931 self.request_autoscroll(autoscroll, cx);
10932 }
10933 cx.notify();
10934 }
10935
10936 pub fn replace_blocks(
10937 &mut self,
10938 renderers: HashMap<CustomBlockId, RenderBlock>,
10939 autoscroll: Option<Autoscroll>,
10940 cx: &mut ViewContext<Self>,
10941 ) {
10942 self.display_map
10943 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10944 if let Some(autoscroll) = autoscroll {
10945 self.request_autoscroll(autoscroll, cx);
10946 }
10947 cx.notify();
10948 }
10949
10950 pub fn remove_blocks(
10951 &mut self,
10952 block_ids: HashSet<CustomBlockId>,
10953 autoscroll: Option<Autoscroll>,
10954 cx: &mut ViewContext<Self>,
10955 ) {
10956 self.display_map.update(cx, |display_map, cx| {
10957 display_map.remove_blocks(block_ids, cx)
10958 });
10959 if let Some(autoscroll) = autoscroll {
10960 self.request_autoscroll(autoscroll, cx);
10961 }
10962 cx.notify();
10963 }
10964
10965 pub fn row_for_block(
10966 &self,
10967 block_id: CustomBlockId,
10968 cx: &mut ViewContext<Self>,
10969 ) -> Option<DisplayRow> {
10970 self.display_map
10971 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10972 }
10973
10974 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10975 self.focused_block = Some(focused_block);
10976 }
10977
10978 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10979 self.focused_block.take()
10980 }
10981
10982 pub fn insert_creases(
10983 &mut self,
10984 creases: impl IntoIterator<Item = Crease>,
10985 cx: &mut ViewContext<Self>,
10986 ) -> Vec<CreaseId> {
10987 self.display_map
10988 .update(cx, |map, cx| map.insert_creases(creases, cx))
10989 }
10990
10991 pub fn remove_creases(
10992 &mut self,
10993 ids: impl IntoIterator<Item = CreaseId>,
10994 cx: &mut ViewContext<Self>,
10995 ) {
10996 self.display_map
10997 .update(cx, |map, cx| map.remove_creases(ids, cx));
10998 }
10999
11000 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11001 self.display_map
11002 .update(cx, |map, cx| map.snapshot(cx))
11003 .longest_row()
11004 }
11005
11006 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11007 self.display_map
11008 .update(cx, |map, cx| map.snapshot(cx))
11009 .max_point()
11010 }
11011
11012 pub fn text(&self, cx: &AppContext) -> String {
11013 self.buffer.read(cx).read(cx).text()
11014 }
11015
11016 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11017 let text = self.text(cx);
11018 let text = text.trim();
11019
11020 if text.is_empty() {
11021 return None;
11022 }
11023
11024 Some(text.to_string())
11025 }
11026
11027 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11028 self.transact(cx, |this, cx| {
11029 this.buffer
11030 .read(cx)
11031 .as_singleton()
11032 .expect("you can only call set_text on editors for singleton buffers")
11033 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11034 });
11035 }
11036
11037 pub fn display_text(&self, cx: &mut AppContext) -> String {
11038 self.display_map
11039 .update(cx, |map, cx| map.snapshot(cx))
11040 .text()
11041 }
11042
11043 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11044 let mut wrap_guides = smallvec::smallvec![];
11045
11046 if self.show_wrap_guides == Some(false) {
11047 return wrap_guides;
11048 }
11049
11050 let settings = self.buffer.read(cx).settings_at(0, cx);
11051 if settings.show_wrap_guides {
11052 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11053 wrap_guides.push((soft_wrap as usize, true));
11054 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11055 wrap_guides.push((soft_wrap as usize, true));
11056 }
11057 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11058 }
11059
11060 wrap_guides
11061 }
11062
11063 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11064 let settings = self.buffer.read(cx).settings_at(0, cx);
11065 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11066 match mode {
11067 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11068 SoftWrap::None
11069 }
11070 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11071 language_settings::SoftWrap::PreferredLineLength => {
11072 SoftWrap::Column(settings.preferred_line_length)
11073 }
11074 language_settings::SoftWrap::Bounded => {
11075 SoftWrap::Bounded(settings.preferred_line_length)
11076 }
11077 }
11078 }
11079
11080 pub fn set_soft_wrap_mode(
11081 &mut self,
11082 mode: language_settings::SoftWrap,
11083 cx: &mut ViewContext<Self>,
11084 ) {
11085 self.soft_wrap_mode_override = Some(mode);
11086 cx.notify();
11087 }
11088
11089 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11090 let rem_size = cx.rem_size();
11091 self.display_map.update(cx, |map, cx| {
11092 map.set_font(
11093 style.text.font(),
11094 style.text.font_size.to_pixels(rem_size),
11095 cx,
11096 )
11097 });
11098 self.style = Some(style);
11099 }
11100
11101 pub fn style(&self) -> Option<&EditorStyle> {
11102 self.style.as_ref()
11103 }
11104
11105 // Called by the element. This method is not designed to be called outside of the editor
11106 // element's layout code because it does not notify when rewrapping is computed synchronously.
11107 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11108 self.display_map
11109 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11110 }
11111
11112 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11113 if self.soft_wrap_mode_override.is_some() {
11114 self.soft_wrap_mode_override.take();
11115 } else {
11116 let soft_wrap = match self.soft_wrap_mode(cx) {
11117 SoftWrap::GitDiff => return,
11118 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11119 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11120 language_settings::SoftWrap::None
11121 }
11122 };
11123 self.soft_wrap_mode_override = Some(soft_wrap);
11124 }
11125 cx.notify();
11126 }
11127
11128 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11129 let Some(workspace) = self.workspace() else {
11130 return;
11131 };
11132 let fs = workspace.read(cx).app_state().fs.clone();
11133 let current_show = TabBarSettings::get_global(cx).show;
11134 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11135 setting.show = Some(!current_show);
11136 });
11137 }
11138
11139 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11140 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11141 self.buffer
11142 .read(cx)
11143 .settings_at(0, cx)
11144 .indent_guides
11145 .enabled
11146 });
11147 self.show_indent_guides = Some(!currently_enabled);
11148 cx.notify();
11149 }
11150
11151 fn should_show_indent_guides(&self) -> Option<bool> {
11152 self.show_indent_guides
11153 }
11154
11155 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11156 let mut editor_settings = EditorSettings::get_global(cx).clone();
11157 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11158 EditorSettings::override_global(editor_settings, cx);
11159 }
11160
11161 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11162 self.use_relative_line_numbers
11163 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11164 }
11165
11166 pub fn toggle_relative_line_numbers(
11167 &mut self,
11168 _: &ToggleRelativeLineNumbers,
11169 cx: &mut ViewContext<Self>,
11170 ) {
11171 let is_relative = self.should_use_relative_line_numbers(cx);
11172 self.set_relative_line_number(Some(!is_relative), cx)
11173 }
11174
11175 pub fn set_relative_line_number(
11176 &mut self,
11177 is_relative: Option<bool>,
11178 cx: &mut ViewContext<Self>,
11179 ) {
11180 self.use_relative_line_numbers = is_relative;
11181 cx.notify();
11182 }
11183
11184 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11185 self.show_gutter = show_gutter;
11186 cx.notify();
11187 }
11188
11189 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11190 self.show_line_numbers = Some(show_line_numbers);
11191 cx.notify();
11192 }
11193
11194 pub fn set_show_git_diff_gutter(
11195 &mut self,
11196 show_git_diff_gutter: bool,
11197 cx: &mut ViewContext<Self>,
11198 ) {
11199 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11200 cx.notify();
11201 }
11202
11203 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11204 self.show_code_actions = Some(show_code_actions);
11205 cx.notify();
11206 }
11207
11208 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11209 self.show_runnables = Some(show_runnables);
11210 cx.notify();
11211 }
11212
11213 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11214 if self.display_map.read(cx).masked != masked {
11215 self.display_map.update(cx, |map, _| map.masked = masked);
11216 }
11217 cx.notify()
11218 }
11219
11220 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11221 self.show_wrap_guides = Some(show_wrap_guides);
11222 cx.notify();
11223 }
11224
11225 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11226 self.show_indent_guides = Some(show_indent_guides);
11227 cx.notify();
11228 }
11229
11230 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11231 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11232 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11233 if let Some(dir) = file.abs_path(cx).parent() {
11234 return Some(dir.to_owned());
11235 }
11236 }
11237
11238 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11239 return Some(project_path.path.to_path_buf());
11240 }
11241 }
11242
11243 None
11244 }
11245
11246 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11247 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11248 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11249 cx.reveal_path(&file.abs_path(cx));
11250 }
11251 }
11252 }
11253
11254 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11255 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11256 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11257 if let Some(path) = file.abs_path(cx).to_str() {
11258 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11259 }
11260 }
11261 }
11262 }
11263
11264 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11265 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11266 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11267 if let Some(path) = file.path().to_str() {
11268 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11269 }
11270 }
11271 }
11272 }
11273
11274 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11275 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11276
11277 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11278 self.start_git_blame(true, cx);
11279 }
11280
11281 cx.notify();
11282 }
11283
11284 pub fn toggle_git_blame_inline(
11285 &mut self,
11286 _: &ToggleGitBlameInline,
11287 cx: &mut ViewContext<Self>,
11288 ) {
11289 self.toggle_git_blame_inline_internal(true, cx);
11290 cx.notify();
11291 }
11292
11293 pub fn git_blame_inline_enabled(&self) -> bool {
11294 self.git_blame_inline_enabled
11295 }
11296
11297 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11298 self.show_selection_menu = self
11299 .show_selection_menu
11300 .map(|show_selections_menu| !show_selections_menu)
11301 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11302
11303 cx.notify();
11304 }
11305
11306 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11307 self.show_selection_menu
11308 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11309 }
11310
11311 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11312 if let Some(project) = self.project.as_ref() {
11313 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11314 return;
11315 };
11316
11317 if buffer.read(cx).file().is_none() {
11318 return;
11319 }
11320
11321 let focused = self.focus_handle(cx).contains_focused(cx);
11322
11323 let project = project.clone();
11324 let blame =
11325 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11326 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11327 self.blame = Some(blame);
11328 }
11329 }
11330
11331 fn toggle_git_blame_inline_internal(
11332 &mut self,
11333 user_triggered: bool,
11334 cx: &mut ViewContext<Self>,
11335 ) {
11336 if self.git_blame_inline_enabled {
11337 self.git_blame_inline_enabled = false;
11338 self.show_git_blame_inline = false;
11339 self.show_git_blame_inline_delay_task.take();
11340 } else {
11341 self.git_blame_inline_enabled = true;
11342 self.start_git_blame_inline(user_triggered, cx);
11343 }
11344
11345 cx.notify();
11346 }
11347
11348 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11349 self.start_git_blame(user_triggered, cx);
11350
11351 if ProjectSettings::get_global(cx)
11352 .git
11353 .inline_blame_delay()
11354 .is_some()
11355 {
11356 self.start_inline_blame_timer(cx);
11357 } else {
11358 self.show_git_blame_inline = true
11359 }
11360 }
11361
11362 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11363 self.blame.as_ref()
11364 }
11365
11366 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11367 self.show_git_blame_gutter && self.has_blame_entries(cx)
11368 }
11369
11370 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11371 self.show_git_blame_inline
11372 && self.focus_handle.is_focused(cx)
11373 && !self.newest_selection_head_on_empty_line(cx)
11374 && self.has_blame_entries(cx)
11375 }
11376
11377 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11378 self.blame()
11379 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11380 }
11381
11382 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11383 let cursor_anchor = self.selections.newest_anchor().head();
11384
11385 let snapshot = self.buffer.read(cx).snapshot(cx);
11386 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11387
11388 snapshot.line_len(buffer_row) == 0
11389 }
11390
11391 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11392 let (path, selection, repo) = maybe!({
11393 let project_handle = self.project.as_ref()?.clone();
11394 let project = project_handle.read(cx);
11395
11396 let selection = self.selections.newest::<Point>(cx);
11397 let selection_range = selection.range();
11398
11399 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11400 (buffer, selection_range.start.row..selection_range.end.row)
11401 } else {
11402 let buffer_ranges = self
11403 .buffer()
11404 .read(cx)
11405 .range_to_buffer_ranges(selection_range, cx);
11406
11407 let (buffer, range, _) = if selection.reversed {
11408 buffer_ranges.first()
11409 } else {
11410 buffer_ranges.last()
11411 }?;
11412
11413 let snapshot = buffer.read(cx).snapshot();
11414 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11415 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11416 (buffer.clone(), selection)
11417 };
11418
11419 let path = buffer
11420 .read(cx)
11421 .file()?
11422 .as_local()?
11423 .path()
11424 .to_str()?
11425 .to_string();
11426 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11427 Some((path, selection, repo))
11428 })
11429 .ok_or_else(|| anyhow!("unable to open git repository"))?;
11430
11431 const REMOTE_NAME: &str = "origin";
11432 let origin_url = repo
11433 .remote_url(REMOTE_NAME)
11434 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11435 let sha = repo
11436 .head_sha()
11437 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11438
11439 let (provider, remote) =
11440 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11441 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11442
11443 Ok(provider.build_permalink(
11444 remote,
11445 BuildPermalinkParams {
11446 sha: &sha,
11447 path: &path,
11448 selection: Some(selection),
11449 },
11450 ))
11451 }
11452
11453 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11454 let permalink = self.get_permalink_to_line(cx);
11455
11456 match permalink {
11457 Ok(permalink) => {
11458 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11459 }
11460 Err(err) => {
11461 let message = format!("Failed to copy permalink: {err}");
11462
11463 Err::<(), anyhow::Error>(err).log_err();
11464
11465 if let Some(workspace) = self.workspace() {
11466 workspace.update(cx, |workspace, cx| {
11467 struct CopyPermalinkToLine;
11468
11469 workspace.show_toast(
11470 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11471 cx,
11472 )
11473 })
11474 }
11475 }
11476 }
11477 }
11478
11479 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11480 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11481 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11482 if let Some(path) = file.path().to_str() {
11483 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11484 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11485 }
11486 }
11487 }
11488 }
11489
11490 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11491 let permalink = self.get_permalink_to_line(cx);
11492
11493 match permalink {
11494 Ok(permalink) => {
11495 cx.open_url(permalink.as_ref());
11496 }
11497 Err(err) => {
11498 let message = format!("Failed to open permalink: {err}");
11499
11500 Err::<(), anyhow::Error>(err).log_err();
11501
11502 if let Some(workspace) = self.workspace() {
11503 workspace.update(cx, |workspace, cx| {
11504 struct OpenPermalinkToLine;
11505
11506 workspace.show_toast(
11507 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11508 cx,
11509 )
11510 })
11511 }
11512 }
11513 }
11514 }
11515
11516 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11517 /// last highlight added will be used.
11518 ///
11519 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11520 pub fn highlight_rows<T: 'static>(
11521 &mut self,
11522 range: Range<Anchor>,
11523 color: Hsla,
11524 should_autoscroll: bool,
11525 cx: &mut ViewContext<Self>,
11526 ) {
11527 let snapshot = self.buffer().read(cx).snapshot(cx);
11528 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11529 let ix = row_highlights.binary_search_by(|highlight| {
11530 Ordering::Equal
11531 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11532 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11533 });
11534
11535 if let Err(mut ix) = ix {
11536 let index = post_inc(&mut self.highlight_order);
11537
11538 // If this range intersects with the preceding highlight, then merge it with
11539 // the preceding highlight. Otherwise insert a new highlight.
11540 let mut merged = false;
11541 if ix > 0 {
11542 let prev_highlight = &mut row_highlights[ix - 1];
11543 if prev_highlight
11544 .range
11545 .end
11546 .cmp(&range.start, &snapshot)
11547 .is_ge()
11548 {
11549 ix -= 1;
11550 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11551 prev_highlight.range.end = range.end;
11552 }
11553 merged = true;
11554 prev_highlight.index = index;
11555 prev_highlight.color = color;
11556 prev_highlight.should_autoscroll = should_autoscroll;
11557 }
11558 }
11559
11560 if !merged {
11561 row_highlights.insert(
11562 ix,
11563 RowHighlight {
11564 range: range.clone(),
11565 index,
11566 color,
11567 should_autoscroll,
11568 },
11569 );
11570 }
11571
11572 // If any of the following highlights intersect with this one, merge them.
11573 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11574 let highlight = &row_highlights[ix];
11575 if next_highlight
11576 .range
11577 .start
11578 .cmp(&highlight.range.end, &snapshot)
11579 .is_le()
11580 {
11581 if next_highlight
11582 .range
11583 .end
11584 .cmp(&highlight.range.end, &snapshot)
11585 .is_gt()
11586 {
11587 row_highlights[ix].range.end = next_highlight.range.end;
11588 }
11589 row_highlights.remove(ix + 1);
11590 } else {
11591 break;
11592 }
11593 }
11594 }
11595 }
11596
11597 /// Remove any highlighted row ranges of the given type that intersect the
11598 /// given ranges.
11599 pub fn remove_highlighted_rows<T: 'static>(
11600 &mut self,
11601 ranges_to_remove: Vec<Range<Anchor>>,
11602 cx: &mut ViewContext<Self>,
11603 ) {
11604 let snapshot = self.buffer().read(cx).snapshot(cx);
11605 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11606 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11607 row_highlights.retain(|highlight| {
11608 while let Some(range_to_remove) = ranges_to_remove.peek() {
11609 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11610 Ordering::Less | Ordering::Equal => {
11611 ranges_to_remove.next();
11612 }
11613 Ordering::Greater => {
11614 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11615 Ordering::Less | Ordering::Equal => {
11616 return false;
11617 }
11618 Ordering::Greater => break,
11619 }
11620 }
11621 }
11622 }
11623
11624 true
11625 })
11626 }
11627
11628 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11629 pub fn clear_row_highlights<T: 'static>(&mut self) {
11630 self.highlighted_rows.remove(&TypeId::of::<T>());
11631 }
11632
11633 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11634 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11635 self.highlighted_rows
11636 .get(&TypeId::of::<T>())
11637 .map_or(&[] as &[_], |vec| vec.as_slice())
11638 .iter()
11639 .map(|highlight| (highlight.range.clone(), highlight.color))
11640 }
11641
11642 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11643 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11644 /// Allows to ignore certain kinds of highlights.
11645 pub fn highlighted_display_rows(
11646 &mut self,
11647 cx: &mut WindowContext,
11648 ) -> BTreeMap<DisplayRow, Hsla> {
11649 let snapshot = self.snapshot(cx);
11650 let mut used_highlight_orders = HashMap::default();
11651 self.highlighted_rows
11652 .iter()
11653 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11654 .fold(
11655 BTreeMap::<DisplayRow, Hsla>::new(),
11656 |mut unique_rows, highlight| {
11657 let start = highlight.range.start.to_display_point(&snapshot);
11658 let end = highlight.range.end.to_display_point(&snapshot);
11659 let start_row = start.row().0;
11660 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11661 && end.column() == 0
11662 {
11663 end.row().0.saturating_sub(1)
11664 } else {
11665 end.row().0
11666 };
11667 for row in start_row..=end_row {
11668 let used_index =
11669 used_highlight_orders.entry(row).or_insert(highlight.index);
11670 if highlight.index >= *used_index {
11671 *used_index = highlight.index;
11672 unique_rows.insert(DisplayRow(row), highlight.color);
11673 }
11674 }
11675 unique_rows
11676 },
11677 )
11678 }
11679
11680 pub fn highlighted_display_row_for_autoscroll(
11681 &self,
11682 snapshot: &DisplaySnapshot,
11683 ) -> Option<DisplayRow> {
11684 self.highlighted_rows
11685 .values()
11686 .flat_map(|highlighted_rows| highlighted_rows.iter())
11687 .filter_map(|highlight| {
11688 if highlight.should_autoscroll {
11689 Some(highlight.range.start.to_display_point(snapshot).row())
11690 } else {
11691 None
11692 }
11693 })
11694 .min()
11695 }
11696
11697 pub fn set_search_within_ranges(
11698 &mut self,
11699 ranges: &[Range<Anchor>],
11700 cx: &mut ViewContext<Self>,
11701 ) {
11702 self.highlight_background::<SearchWithinRange>(
11703 ranges,
11704 |colors| colors.editor_document_highlight_read_background,
11705 cx,
11706 )
11707 }
11708
11709 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11710 self.breadcrumb_header = Some(new_header);
11711 }
11712
11713 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11714 self.clear_background_highlights::<SearchWithinRange>(cx);
11715 }
11716
11717 pub fn highlight_background<T: 'static>(
11718 &mut self,
11719 ranges: &[Range<Anchor>],
11720 color_fetcher: fn(&ThemeColors) -> Hsla,
11721 cx: &mut ViewContext<Self>,
11722 ) {
11723 self.background_highlights
11724 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11725 self.scrollbar_marker_state.dirty = true;
11726 cx.notify();
11727 }
11728
11729 pub fn clear_background_highlights<T: 'static>(
11730 &mut self,
11731 cx: &mut ViewContext<Self>,
11732 ) -> Option<BackgroundHighlight> {
11733 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11734 if !text_highlights.1.is_empty() {
11735 self.scrollbar_marker_state.dirty = true;
11736 cx.notify();
11737 }
11738 Some(text_highlights)
11739 }
11740
11741 pub fn highlight_gutter<T: 'static>(
11742 &mut self,
11743 ranges: &[Range<Anchor>],
11744 color_fetcher: fn(&AppContext) -> Hsla,
11745 cx: &mut ViewContext<Self>,
11746 ) {
11747 self.gutter_highlights
11748 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11749 cx.notify();
11750 }
11751
11752 pub fn clear_gutter_highlights<T: 'static>(
11753 &mut self,
11754 cx: &mut ViewContext<Self>,
11755 ) -> Option<GutterHighlight> {
11756 cx.notify();
11757 self.gutter_highlights.remove(&TypeId::of::<T>())
11758 }
11759
11760 #[cfg(feature = "test-support")]
11761 pub fn all_text_background_highlights(
11762 &mut self,
11763 cx: &mut ViewContext<Self>,
11764 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11765 let snapshot = self.snapshot(cx);
11766 let buffer = &snapshot.buffer_snapshot;
11767 let start = buffer.anchor_before(0);
11768 let end = buffer.anchor_after(buffer.len());
11769 let theme = cx.theme().colors();
11770 self.background_highlights_in_range(start..end, &snapshot, theme)
11771 }
11772
11773 #[cfg(feature = "test-support")]
11774 pub fn search_background_highlights(
11775 &mut self,
11776 cx: &mut ViewContext<Self>,
11777 ) -> Vec<Range<Point>> {
11778 let snapshot = self.buffer().read(cx).snapshot(cx);
11779
11780 let highlights = self
11781 .background_highlights
11782 .get(&TypeId::of::<items::BufferSearchHighlights>());
11783
11784 if let Some((_color, ranges)) = highlights {
11785 ranges
11786 .iter()
11787 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11788 .collect_vec()
11789 } else {
11790 vec![]
11791 }
11792 }
11793
11794 fn document_highlights_for_position<'a>(
11795 &'a self,
11796 position: Anchor,
11797 buffer: &'a MultiBufferSnapshot,
11798 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11799 let read_highlights = self
11800 .background_highlights
11801 .get(&TypeId::of::<DocumentHighlightRead>())
11802 .map(|h| &h.1);
11803 let write_highlights = self
11804 .background_highlights
11805 .get(&TypeId::of::<DocumentHighlightWrite>())
11806 .map(|h| &h.1);
11807 let left_position = position.bias_left(buffer);
11808 let right_position = position.bias_right(buffer);
11809 read_highlights
11810 .into_iter()
11811 .chain(write_highlights)
11812 .flat_map(move |ranges| {
11813 let start_ix = match ranges.binary_search_by(|probe| {
11814 let cmp = probe.end.cmp(&left_position, buffer);
11815 if cmp.is_ge() {
11816 Ordering::Greater
11817 } else {
11818 Ordering::Less
11819 }
11820 }) {
11821 Ok(i) | Err(i) => i,
11822 };
11823
11824 ranges[start_ix..]
11825 .iter()
11826 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11827 })
11828 }
11829
11830 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11831 self.background_highlights
11832 .get(&TypeId::of::<T>())
11833 .map_or(false, |(_, highlights)| !highlights.is_empty())
11834 }
11835
11836 pub fn background_highlights_in_range(
11837 &self,
11838 search_range: Range<Anchor>,
11839 display_snapshot: &DisplaySnapshot,
11840 theme: &ThemeColors,
11841 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11842 let mut results = Vec::new();
11843 for (color_fetcher, ranges) in self.background_highlights.values() {
11844 let color = color_fetcher(theme);
11845 let start_ix = match ranges.binary_search_by(|probe| {
11846 let cmp = probe
11847 .end
11848 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11849 if cmp.is_gt() {
11850 Ordering::Greater
11851 } else {
11852 Ordering::Less
11853 }
11854 }) {
11855 Ok(i) | Err(i) => i,
11856 };
11857 for range in &ranges[start_ix..] {
11858 if range
11859 .start
11860 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11861 .is_ge()
11862 {
11863 break;
11864 }
11865
11866 let start = range.start.to_display_point(display_snapshot);
11867 let end = range.end.to_display_point(display_snapshot);
11868 results.push((start..end, color))
11869 }
11870 }
11871 results
11872 }
11873
11874 pub fn background_highlight_row_ranges<T: 'static>(
11875 &self,
11876 search_range: Range<Anchor>,
11877 display_snapshot: &DisplaySnapshot,
11878 count: usize,
11879 ) -> Vec<RangeInclusive<DisplayPoint>> {
11880 let mut results = Vec::new();
11881 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11882 return vec![];
11883 };
11884
11885 let start_ix = match ranges.binary_search_by(|probe| {
11886 let cmp = probe
11887 .end
11888 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11889 if cmp.is_gt() {
11890 Ordering::Greater
11891 } else {
11892 Ordering::Less
11893 }
11894 }) {
11895 Ok(i) | Err(i) => i,
11896 };
11897 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11898 if let (Some(start_display), Some(end_display)) = (start, end) {
11899 results.push(
11900 start_display.to_display_point(display_snapshot)
11901 ..=end_display.to_display_point(display_snapshot),
11902 );
11903 }
11904 };
11905 let mut start_row: Option<Point> = None;
11906 let mut end_row: Option<Point> = None;
11907 if ranges.len() > count {
11908 return Vec::new();
11909 }
11910 for range in &ranges[start_ix..] {
11911 if range
11912 .start
11913 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11914 .is_ge()
11915 {
11916 break;
11917 }
11918 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11919 if let Some(current_row) = &end_row {
11920 if end.row == current_row.row {
11921 continue;
11922 }
11923 }
11924 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11925 if start_row.is_none() {
11926 assert_eq!(end_row, None);
11927 start_row = Some(start);
11928 end_row = Some(end);
11929 continue;
11930 }
11931 if let Some(current_end) = end_row.as_mut() {
11932 if start.row > current_end.row + 1 {
11933 push_region(start_row, end_row);
11934 start_row = Some(start);
11935 end_row = Some(end);
11936 } else {
11937 // Merge two hunks.
11938 *current_end = end;
11939 }
11940 } else {
11941 unreachable!();
11942 }
11943 }
11944 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11945 push_region(start_row, end_row);
11946 results
11947 }
11948
11949 pub fn gutter_highlights_in_range(
11950 &self,
11951 search_range: Range<Anchor>,
11952 display_snapshot: &DisplaySnapshot,
11953 cx: &AppContext,
11954 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11955 let mut results = Vec::new();
11956 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11957 let color = color_fetcher(cx);
11958 let start_ix = match ranges.binary_search_by(|probe| {
11959 let cmp = probe
11960 .end
11961 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11962 if cmp.is_gt() {
11963 Ordering::Greater
11964 } else {
11965 Ordering::Less
11966 }
11967 }) {
11968 Ok(i) | Err(i) => i,
11969 };
11970 for range in &ranges[start_ix..] {
11971 if range
11972 .start
11973 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11974 .is_ge()
11975 {
11976 break;
11977 }
11978
11979 let start = range.start.to_display_point(display_snapshot);
11980 let end = range.end.to_display_point(display_snapshot);
11981 results.push((start..end, color))
11982 }
11983 }
11984 results
11985 }
11986
11987 /// Get the text ranges corresponding to the redaction query
11988 pub fn redacted_ranges(
11989 &self,
11990 search_range: Range<Anchor>,
11991 display_snapshot: &DisplaySnapshot,
11992 cx: &WindowContext,
11993 ) -> Vec<Range<DisplayPoint>> {
11994 display_snapshot
11995 .buffer_snapshot
11996 .redacted_ranges(search_range, |file| {
11997 if let Some(file) = file {
11998 file.is_private()
11999 && EditorSettings::get(
12000 Some(SettingsLocation {
12001 worktree_id: file.worktree_id(cx),
12002 path: file.path().as_ref(),
12003 }),
12004 cx,
12005 )
12006 .redact_private_values
12007 } else {
12008 false
12009 }
12010 })
12011 .map(|range| {
12012 range.start.to_display_point(display_snapshot)
12013 ..range.end.to_display_point(display_snapshot)
12014 })
12015 .collect()
12016 }
12017
12018 pub fn highlight_text<T: 'static>(
12019 &mut self,
12020 ranges: Vec<Range<Anchor>>,
12021 style: HighlightStyle,
12022 cx: &mut ViewContext<Self>,
12023 ) {
12024 self.display_map.update(cx, |map, _| {
12025 map.highlight_text(TypeId::of::<T>(), ranges, style)
12026 });
12027 cx.notify();
12028 }
12029
12030 pub(crate) fn highlight_inlays<T: 'static>(
12031 &mut self,
12032 highlights: Vec<InlayHighlight>,
12033 style: HighlightStyle,
12034 cx: &mut ViewContext<Self>,
12035 ) {
12036 self.display_map.update(cx, |map, _| {
12037 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12038 });
12039 cx.notify();
12040 }
12041
12042 pub fn text_highlights<'a, T: 'static>(
12043 &'a self,
12044 cx: &'a AppContext,
12045 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12046 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12047 }
12048
12049 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12050 let cleared = self
12051 .display_map
12052 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12053 if cleared {
12054 cx.notify();
12055 }
12056 }
12057
12058 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12059 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12060 && self.focus_handle.is_focused(cx)
12061 }
12062
12063 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12064 self.show_cursor_when_unfocused = is_enabled;
12065 cx.notify();
12066 }
12067
12068 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12069 cx.notify();
12070 }
12071
12072 fn on_buffer_event(
12073 &mut self,
12074 multibuffer: Model<MultiBuffer>,
12075 event: &multi_buffer::Event,
12076 cx: &mut ViewContext<Self>,
12077 ) {
12078 match event {
12079 multi_buffer::Event::Edited {
12080 singleton_buffer_edited,
12081 } => {
12082 self.scrollbar_marker_state.dirty = true;
12083 self.active_indent_guides_state.dirty = true;
12084 self.refresh_active_diagnostics(cx);
12085 self.refresh_code_actions(cx);
12086 if self.has_active_inline_completion(cx) {
12087 self.update_visible_inline_completion(cx);
12088 }
12089 cx.emit(EditorEvent::BufferEdited);
12090 cx.emit(SearchEvent::MatchesInvalidated);
12091 if *singleton_buffer_edited {
12092 if let Some(project) = &self.project {
12093 let project = project.read(cx);
12094 #[allow(clippy::mutable_key_type)]
12095 let languages_affected = multibuffer
12096 .read(cx)
12097 .all_buffers()
12098 .into_iter()
12099 .filter_map(|buffer| {
12100 let buffer = buffer.read(cx);
12101 let language = buffer.language()?;
12102 if project.is_local()
12103 && project.language_servers_for_buffer(buffer, cx).count() == 0
12104 {
12105 None
12106 } else {
12107 Some(language)
12108 }
12109 })
12110 .cloned()
12111 .collect::<HashSet<_>>();
12112 if !languages_affected.is_empty() {
12113 self.refresh_inlay_hints(
12114 InlayHintRefreshReason::BufferEdited(languages_affected),
12115 cx,
12116 );
12117 }
12118 }
12119 }
12120
12121 let Some(project) = &self.project else { return };
12122 let telemetry = project.read(cx).client().telemetry().clone();
12123 refresh_linked_ranges(self, cx);
12124 telemetry.log_edit_event("editor");
12125 }
12126 multi_buffer::Event::ExcerptsAdded {
12127 buffer,
12128 predecessor,
12129 excerpts,
12130 } => {
12131 self.tasks_update_task = Some(self.refresh_runnables(cx));
12132 cx.emit(EditorEvent::ExcerptsAdded {
12133 buffer: buffer.clone(),
12134 predecessor: *predecessor,
12135 excerpts: excerpts.clone(),
12136 });
12137 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12138 }
12139 multi_buffer::Event::ExcerptsRemoved { ids } => {
12140 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12141 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12142 }
12143 multi_buffer::Event::ExcerptsEdited { ids } => {
12144 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12145 }
12146 multi_buffer::Event::ExcerptsExpanded { ids } => {
12147 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12148 }
12149 multi_buffer::Event::Reparsed(buffer_id) => {
12150 self.tasks_update_task = Some(self.refresh_runnables(cx));
12151
12152 cx.emit(EditorEvent::Reparsed(*buffer_id));
12153 }
12154 multi_buffer::Event::LanguageChanged(buffer_id) => {
12155 linked_editing_ranges::refresh_linked_ranges(self, cx);
12156 cx.emit(EditorEvent::Reparsed(*buffer_id));
12157 cx.notify();
12158 }
12159 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12160 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12161 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12162 cx.emit(EditorEvent::TitleChanged)
12163 }
12164 multi_buffer::Event::DiffBaseChanged => {
12165 self.scrollbar_marker_state.dirty = true;
12166 cx.emit(EditorEvent::DiffBaseChanged);
12167 cx.notify();
12168 }
12169 multi_buffer::Event::DiffUpdated { buffer } => {
12170 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12171 cx.notify();
12172 }
12173 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12174 multi_buffer::Event::DiagnosticsUpdated => {
12175 self.refresh_active_diagnostics(cx);
12176 self.scrollbar_marker_state.dirty = true;
12177 cx.notify();
12178 }
12179 _ => {}
12180 };
12181 }
12182
12183 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12184 cx.notify();
12185 }
12186
12187 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12188 self.tasks_update_task = Some(self.refresh_runnables(cx));
12189 self.refresh_inline_completion(true, false, cx);
12190 self.refresh_inlay_hints(
12191 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12192 self.selections.newest_anchor().head(),
12193 &self.buffer.read(cx).snapshot(cx),
12194 cx,
12195 )),
12196 cx,
12197 );
12198
12199 let old_cursor_shape = self.cursor_shape;
12200
12201 {
12202 let editor_settings = EditorSettings::get_global(cx);
12203 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12204 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12205 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12206 }
12207
12208 if old_cursor_shape != self.cursor_shape {
12209 cx.emit(EditorEvent::CursorShapeChanged);
12210 }
12211
12212 let project_settings = ProjectSettings::get_global(cx);
12213 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12214
12215 if self.mode == EditorMode::Full {
12216 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12217 if self.git_blame_inline_enabled != inline_blame_enabled {
12218 self.toggle_git_blame_inline_internal(false, cx);
12219 }
12220 }
12221
12222 cx.notify();
12223 }
12224
12225 pub fn set_searchable(&mut self, searchable: bool) {
12226 self.searchable = searchable;
12227 }
12228
12229 pub fn searchable(&self) -> bool {
12230 self.searchable
12231 }
12232
12233 fn open_proposed_changes_editor(
12234 &mut self,
12235 _: &OpenProposedChangesEditor,
12236 cx: &mut ViewContext<Self>,
12237 ) {
12238 let Some(workspace) = self.workspace() else {
12239 cx.propagate();
12240 return;
12241 };
12242
12243 let buffer = self.buffer.read(cx);
12244 let mut new_selections_by_buffer = HashMap::default();
12245 for selection in self.selections.all::<usize>(cx) {
12246 for (buffer, mut range, _) in
12247 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12248 {
12249 if selection.reversed {
12250 mem::swap(&mut range.start, &mut range.end);
12251 }
12252 let mut range = range.to_point(buffer.read(cx));
12253 range.start.column = 0;
12254 range.end.column = buffer.read(cx).line_len(range.end.row);
12255 new_selections_by_buffer
12256 .entry(buffer)
12257 .or_insert(Vec::new())
12258 .push(range)
12259 }
12260 }
12261
12262 let proposed_changes_buffers = new_selections_by_buffer
12263 .into_iter()
12264 .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
12265 .collect::<Vec<_>>();
12266 let proposed_changes_editor = cx.new_view(|cx| {
12267 ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
12268 });
12269
12270 cx.window_context().defer(move |cx| {
12271 workspace.update(cx, |workspace, cx| {
12272 workspace.active_pane().update(cx, |pane, cx| {
12273 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12274 });
12275 });
12276 });
12277 }
12278
12279 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12280 self.open_excerpts_common(true, cx)
12281 }
12282
12283 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12284 self.open_excerpts_common(false, cx)
12285 }
12286
12287 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12288 let buffer = self.buffer.read(cx);
12289 if buffer.is_singleton() {
12290 cx.propagate();
12291 return;
12292 }
12293
12294 let Some(workspace) = self.workspace() else {
12295 cx.propagate();
12296 return;
12297 };
12298
12299 let mut new_selections_by_buffer = HashMap::default();
12300 for selection in self.selections.all::<usize>(cx) {
12301 for (buffer, mut range, _) in
12302 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12303 {
12304 if selection.reversed {
12305 mem::swap(&mut range.start, &mut range.end);
12306 }
12307 new_selections_by_buffer
12308 .entry(buffer)
12309 .or_insert(Vec::new())
12310 .push(range)
12311 }
12312 }
12313
12314 // We defer the pane interaction because we ourselves are a workspace item
12315 // and activating a new item causes the pane to call a method on us reentrantly,
12316 // which panics if we're on the stack.
12317 cx.window_context().defer(move |cx| {
12318 workspace.update(cx, |workspace, cx| {
12319 let pane = if split {
12320 workspace.adjacent_pane(cx)
12321 } else {
12322 workspace.active_pane().clone()
12323 };
12324
12325 for (buffer, ranges) in new_selections_by_buffer {
12326 let editor =
12327 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12328 editor.update(cx, |editor, cx| {
12329 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12330 s.select_ranges(ranges);
12331 });
12332 });
12333 }
12334 })
12335 });
12336 }
12337
12338 fn jump(
12339 &mut self,
12340 path: ProjectPath,
12341 position: Point,
12342 anchor: language::Anchor,
12343 offset_from_top: u32,
12344 cx: &mut ViewContext<Self>,
12345 ) {
12346 let workspace = self.workspace();
12347 cx.spawn(|_, mut cx| async move {
12348 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12349 let editor = workspace.update(&mut cx, |workspace, cx| {
12350 // Reset the preview item id before opening the new item
12351 workspace.active_pane().update(cx, |pane, cx| {
12352 pane.set_preview_item_id(None, cx);
12353 });
12354 workspace.open_path_preview(path, None, true, true, cx)
12355 })?;
12356 let editor = editor
12357 .await?
12358 .downcast::<Editor>()
12359 .ok_or_else(|| anyhow!("opened item was not an editor"))?
12360 .downgrade();
12361 editor.update(&mut cx, |editor, cx| {
12362 let buffer = editor
12363 .buffer()
12364 .read(cx)
12365 .as_singleton()
12366 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12367 let buffer = buffer.read(cx);
12368 let cursor = if buffer.can_resolve(&anchor) {
12369 language::ToPoint::to_point(&anchor, buffer)
12370 } else {
12371 buffer.clip_point(position, Bias::Left)
12372 };
12373
12374 let nav_history = editor.nav_history.take();
12375 editor.change_selections(
12376 Some(Autoscroll::top_relative(offset_from_top as usize)),
12377 cx,
12378 |s| {
12379 s.select_ranges([cursor..cursor]);
12380 },
12381 );
12382 editor.nav_history = nav_history;
12383
12384 anyhow::Ok(())
12385 })??;
12386
12387 anyhow::Ok(())
12388 })
12389 .detach_and_log_err(cx);
12390 }
12391
12392 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12393 let snapshot = self.buffer.read(cx).read(cx);
12394 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12395 Some(
12396 ranges
12397 .iter()
12398 .map(move |range| {
12399 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12400 })
12401 .collect(),
12402 )
12403 }
12404
12405 fn selection_replacement_ranges(
12406 &self,
12407 range: Range<OffsetUtf16>,
12408 cx: &AppContext,
12409 ) -> Vec<Range<OffsetUtf16>> {
12410 let selections = self.selections.all::<OffsetUtf16>(cx);
12411 let newest_selection = selections
12412 .iter()
12413 .max_by_key(|selection| selection.id)
12414 .unwrap();
12415 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12416 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12417 let snapshot = self.buffer.read(cx).read(cx);
12418 selections
12419 .into_iter()
12420 .map(|mut selection| {
12421 selection.start.0 =
12422 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12423 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12424 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12425 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12426 })
12427 .collect()
12428 }
12429
12430 fn report_editor_event(
12431 &self,
12432 operation: &'static str,
12433 file_extension: Option<String>,
12434 cx: &AppContext,
12435 ) {
12436 if cfg!(any(test, feature = "test-support")) {
12437 return;
12438 }
12439
12440 let Some(project) = &self.project else { return };
12441
12442 // If None, we are in a file without an extension
12443 let file = self
12444 .buffer
12445 .read(cx)
12446 .as_singleton()
12447 .and_then(|b| b.read(cx).file());
12448 let file_extension = file_extension.or(file
12449 .as_ref()
12450 .and_then(|file| Path::new(file.file_name(cx)).extension())
12451 .and_then(|e| e.to_str())
12452 .map(|a| a.to_string()));
12453
12454 let vim_mode = cx
12455 .global::<SettingsStore>()
12456 .raw_user_settings()
12457 .get("vim_mode")
12458 == Some(&serde_json::Value::Bool(true));
12459
12460 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12461 == language::language_settings::InlineCompletionProvider::Copilot;
12462 let copilot_enabled_for_language = self
12463 .buffer
12464 .read(cx)
12465 .settings_at(0, cx)
12466 .show_inline_completions;
12467
12468 let telemetry = project.read(cx).client().telemetry().clone();
12469 telemetry.report_editor_event(
12470 file_extension,
12471 vim_mode,
12472 operation,
12473 copilot_enabled,
12474 copilot_enabled_for_language,
12475 )
12476 }
12477
12478 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12479 /// with each line being an array of {text, highlight} objects.
12480 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12481 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12482 return;
12483 };
12484
12485 #[derive(Serialize)]
12486 struct Chunk<'a> {
12487 text: String,
12488 highlight: Option<&'a str>,
12489 }
12490
12491 let snapshot = buffer.read(cx).snapshot();
12492 let range = self
12493 .selected_text_range(false, cx)
12494 .and_then(|selection| {
12495 if selection.range.is_empty() {
12496 None
12497 } else {
12498 Some(selection.range)
12499 }
12500 })
12501 .unwrap_or_else(|| 0..snapshot.len());
12502
12503 let chunks = snapshot.chunks(range, true);
12504 let mut lines = Vec::new();
12505 let mut line: VecDeque<Chunk> = VecDeque::new();
12506
12507 let Some(style) = self.style.as_ref() else {
12508 return;
12509 };
12510
12511 for chunk in chunks {
12512 let highlight = chunk
12513 .syntax_highlight_id
12514 .and_then(|id| id.name(&style.syntax));
12515 let mut chunk_lines = chunk.text.split('\n').peekable();
12516 while let Some(text) = chunk_lines.next() {
12517 let mut merged_with_last_token = false;
12518 if let Some(last_token) = line.back_mut() {
12519 if last_token.highlight == highlight {
12520 last_token.text.push_str(text);
12521 merged_with_last_token = true;
12522 }
12523 }
12524
12525 if !merged_with_last_token {
12526 line.push_back(Chunk {
12527 text: text.into(),
12528 highlight,
12529 });
12530 }
12531
12532 if chunk_lines.peek().is_some() {
12533 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12534 line.pop_front();
12535 }
12536 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12537 line.pop_back();
12538 }
12539
12540 lines.push(mem::take(&mut line));
12541 }
12542 }
12543 }
12544
12545 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12546 return;
12547 };
12548 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12549 }
12550
12551 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12552 &self.inlay_hint_cache
12553 }
12554
12555 pub fn replay_insert_event(
12556 &mut self,
12557 text: &str,
12558 relative_utf16_range: Option<Range<isize>>,
12559 cx: &mut ViewContext<Self>,
12560 ) {
12561 if !self.input_enabled {
12562 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12563 return;
12564 }
12565 if let Some(relative_utf16_range) = relative_utf16_range {
12566 let selections = self.selections.all::<OffsetUtf16>(cx);
12567 self.change_selections(None, cx, |s| {
12568 let new_ranges = selections.into_iter().map(|range| {
12569 let start = OffsetUtf16(
12570 range
12571 .head()
12572 .0
12573 .saturating_add_signed(relative_utf16_range.start),
12574 );
12575 let end = OffsetUtf16(
12576 range
12577 .head()
12578 .0
12579 .saturating_add_signed(relative_utf16_range.end),
12580 );
12581 start..end
12582 });
12583 s.select_ranges(new_ranges);
12584 });
12585 }
12586
12587 self.handle_input(text, cx);
12588 }
12589
12590 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12591 let Some(project) = self.project.as_ref() else {
12592 return false;
12593 };
12594 let project = project.read(cx);
12595
12596 let mut supports = false;
12597 self.buffer().read(cx).for_each_buffer(|buffer| {
12598 if !supports {
12599 supports = project
12600 .language_servers_for_buffer(buffer.read(cx), cx)
12601 .any(
12602 |(_, server)| match server.capabilities().inlay_hint_provider {
12603 Some(lsp::OneOf::Left(enabled)) => enabled,
12604 Some(lsp::OneOf::Right(_)) => true,
12605 None => false,
12606 },
12607 )
12608 }
12609 });
12610 supports
12611 }
12612
12613 pub fn focus(&self, cx: &mut WindowContext) {
12614 cx.focus(&self.focus_handle)
12615 }
12616
12617 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12618 self.focus_handle.is_focused(cx)
12619 }
12620
12621 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12622 cx.emit(EditorEvent::Focused);
12623
12624 if let Some(descendant) = self
12625 .last_focused_descendant
12626 .take()
12627 .and_then(|descendant| descendant.upgrade())
12628 {
12629 cx.focus(&descendant);
12630 } else {
12631 if let Some(blame) = self.blame.as_ref() {
12632 blame.update(cx, GitBlame::focus)
12633 }
12634
12635 self.blink_manager.update(cx, BlinkManager::enable);
12636 self.show_cursor_names(cx);
12637 self.buffer.update(cx, |buffer, cx| {
12638 buffer.finalize_last_transaction(cx);
12639 if self.leader_peer_id.is_none() {
12640 buffer.set_active_selections(
12641 &self.selections.disjoint_anchors(),
12642 self.selections.line_mode,
12643 self.cursor_shape,
12644 cx,
12645 );
12646 }
12647 });
12648 }
12649 }
12650
12651 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12652 cx.emit(EditorEvent::FocusedIn)
12653 }
12654
12655 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12656 if event.blurred != self.focus_handle {
12657 self.last_focused_descendant = Some(event.blurred);
12658 }
12659 }
12660
12661 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12662 self.blink_manager.update(cx, BlinkManager::disable);
12663 self.buffer
12664 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12665
12666 if let Some(blame) = self.blame.as_ref() {
12667 blame.update(cx, GitBlame::blur)
12668 }
12669 if !self.hover_state.focused(cx) {
12670 hide_hover(self, cx);
12671 }
12672
12673 self.hide_context_menu(cx);
12674 cx.emit(EditorEvent::Blurred);
12675 cx.notify();
12676 }
12677
12678 pub fn register_action<A: Action>(
12679 &mut self,
12680 listener: impl Fn(&A, &mut WindowContext) + 'static,
12681 ) -> Subscription {
12682 let id = self.next_editor_action_id.post_inc();
12683 let listener = Arc::new(listener);
12684 self.editor_actions.borrow_mut().insert(
12685 id,
12686 Box::new(move |cx| {
12687 let cx = cx.window_context();
12688 let listener = listener.clone();
12689 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12690 let action = action.downcast_ref().unwrap();
12691 if phase == DispatchPhase::Bubble {
12692 listener(action, cx)
12693 }
12694 })
12695 }),
12696 );
12697
12698 let editor_actions = self.editor_actions.clone();
12699 Subscription::new(move || {
12700 editor_actions.borrow_mut().remove(&id);
12701 })
12702 }
12703
12704 pub fn file_header_size(&self) -> u32 {
12705 self.file_header_size
12706 }
12707
12708 pub fn revert(
12709 &mut self,
12710 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12711 cx: &mut ViewContext<Self>,
12712 ) {
12713 self.buffer().update(cx, |multi_buffer, cx| {
12714 for (buffer_id, changes) in revert_changes {
12715 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12716 buffer.update(cx, |buffer, cx| {
12717 buffer.edit(
12718 changes.into_iter().map(|(range, text)| {
12719 (range, text.to_string().map(Arc::<str>::from))
12720 }),
12721 None,
12722 cx,
12723 );
12724 });
12725 }
12726 }
12727 });
12728 self.change_selections(None, cx, |selections| selections.refresh());
12729 }
12730
12731 pub fn to_pixel_point(
12732 &mut self,
12733 source: multi_buffer::Anchor,
12734 editor_snapshot: &EditorSnapshot,
12735 cx: &mut ViewContext<Self>,
12736 ) -> Option<gpui::Point<Pixels>> {
12737 let source_point = source.to_display_point(editor_snapshot);
12738 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12739 }
12740
12741 pub fn display_to_pixel_point(
12742 &mut self,
12743 source: DisplayPoint,
12744 editor_snapshot: &EditorSnapshot,
12745 cx: &mut ViewContext<Self>,
12746 ) -> Option<gpui::Point<Pixels>> {
12747 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12748 let text_layout_details = self.text_layout_details(cx);
12749 let scroll_top = text_layout_details
12750 .scroll_anchor
12751 .scroll_position(editor_snapshot)
12752 .y;
12753
12754 if source.row().as_f32() < scroll_top.floor() {
12755 return None;
12756 }
12757 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12758 let source_y = line_height * (source.row().as_f32() - scroll_top);
12759 Some(gpui::Point::new(source_x, source_y))
12760 }
12761
12762 pub fn has_active_completions_menu(&self) -> bool {
12763 self.context_menu.read().as_ref().map_or(false, |menu| {
12764 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12765 })
12766 }
12767
12768 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12769 self.addons
12770 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12771 }
12772
12773 pub fn unregister_addon<T: Addon>(&mut self) {
12774 self.addons.remove(&std::any::TypeId::of::<T>());
12775 }
12776
12777 pub fn addon<T: Addon>(&self) -> Option<&T> {
12778 let type_id = std::any::TypeId::of::<T>();
12779 self.addons
12780 .get(&type_id)
12781 .and_then(|item| item.to_any().downcast_ref::<T>())
12782 }
12783}
12784
12785fn hunks_for_selections(
12786 multi_buffer_snapshot: &MultiBufferSnapshot,
12787 selections: &[Selection<Anchor>],
12788) -> Vec<MultiBufferDiffHunk> {
12789 let buffer_rows_for_selections = selections.iter().map(|selection| {
12790 let head = selection.head();
12791 let tail = selection.tail();
12792 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12793 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12794 if start > end {
12795 end..start
12796 } else {
12797 start..end
12798 }
12799 });
12800
12801 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12802}
12803
12804pub fn hunks_for_rows(
12805 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12806 multi_buffer_snapshot: &MultiBufferSnapshot,
12807) -> Vec<MultiBufferDiffHunk> {
12808 let mut hunks = Vec::new();
12809 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12810 HashMap::default();
12811 for selected_multi_buffer_rows in rows {
12812 let query_rows =
12813 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12814 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12815 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12816 // when the caret is just above or just below the deleted hunk.
12817 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12818 let related_to_selection = if allow_adjacent {
12819 hunk.row_range.overlaps(&query_rows)
12820 || hunk.row_range.start == query_rows.end
12821 || hunk.row_range.end == query_rows.start
12822 } else {
12823 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12824 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12825 hunk.row_range.overlaps(&selected_multi_buffer_rows)
12826 || selected_multi_buffer_rows.end == hunk.row_range.start
12827 };
12828 if related_to_selection {
12829 if !processed_buffer_rows
12830 .entry(hunk.buffer_id)
12831 .or_default()
12832 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12833 {
12834 continue;
12835 }
12836 hunks.push(hunk);
12837 }
12838 }
12839 }
12840
12841 hunks
12842}
12843
12844pub trait CollaborationHub {
12845 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12846 fn user_participant_indices<'a>(
12847 &self,
12848 cx: &'a AppContext,
12849 ) -> &'a HashMap<u64, ParticipantIndex>;
12850 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12851}
12852
12853impl CollaborationHub for Model<Project> {
12854 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12855 self.read(cx).collaborators()
12856 }
12857
12858 fn user_participant_indices<'a>(
12859 &self,
12860 cx: &'a AppContext,
12861 ) -> &'a HashMap<u64, ParticipantIndex> {
12862 self.read(cx).user_store().read(cx).participant_indices()
12863 }
12864
12865 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12866 let this = self.read(cx);
12867 let user_ids = this.collaborators().values().map(|c| c.user_id);
12868 this.user_store().read_with(cx, |user_store, cx| {
12869 user_store.participant_names(user_ids, cx)
12870 })
12871 }
12872}
12873
12874pub trait CompletionProvider {
12875 fn completions(
12876 &self,
12877 buffer: &Model<Buffer>,
12878 buffer_position: text::Anchor,
12879 trigger: CompletionContext,
12880 cx: &mut ViewContext<Editor>,
12881 ) -> Task<Result<Vec<Completion>>>;
12882
12883 fn resolve_completions(
12884 &self,
12885 buffer: Model<Buffer>,
12886 completion_indices: Vec<usize>,
12887 completions: Arc<RwLock<Box<[Completion]>>>,
12888 cx: &mut ViewContext<Editor>,
12889 ) -> Task<Result<bool>>;
12890
12891 fn apply_additional_edits_for_completion(
12892 &self,
12893 buffer: Model<Buffer>,
12894 completion: Completion,
12895 push_to_history: bool,
12896 cx: &mut ViewContext<Editor>,
12897 ) -> Task<Result<Option<language::Transaction>>>;
12898
12899 fn is_completion_trigger(
12900 &self,
12901 buffer: &Model<Buffer>,
12902 position: language::Anchor,
12903 text: &str,
12904 trigger_in_words: bool,
12905 cx: &mut ViewContext<Editor>,
12906 ) -> bool;
12907
12908 fn sort_completions(&self) -> bool {
12909 true
12910 }
12911}
12912
12913pub trait CodeActionProvider {
12914 fn code_actions(
12915 &self,
12916 buffer: &Model<Buffer>,
12917 range: Range<text::Anchor>,
12918 cx: &mut WindowContext,
12919 ) -> Task<Result<Vec<CodeAction>>>;
12920
12921 fn apply_code_action(
12922 &self,
12923 buffer_handle: Model<Buffer>,
12924 action: CodeAction,
12925 excerpt_id: ExcerptId,
12926 push_to_history: bool,
12927 cx: &mut WindowContext,
12928 ) -> Task<Result<ProjectTransaction>>;
12929}
12930
12931impl CodeActionProvider for Model<Project> {
12932 fn code_actions(
12933 &self,
12934 buffer: &Model<Buffer>,
12935 range: Range<text::Anchor>,
12936 cx: &mut WindowContext,
12937 ) -> Task<Result<Vec<CodeAction>>> {
12938 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
12939 }
12940
12941 fn apply_code_action(
12942 &self,
12943 buffer_handle: Model<Buffer>,
12944 action: CodeAction,
12945 _excerpt_id: ExcerptId,
12946 push_to_history: bool,
12947 cx: &mut WindowContext,
12948 ) -> Task<Result<ProjectTransaction>> {
12949 self.update(cx, |project, cx| {
12950 project.apply_code_action(buffer_handle, action, push_to_history, cx)
12951 })
12952 }
12953}
12954
12955fn snippet_completions(
12956 project: &Project,
12957 buffer: &Model<Buffer>,
12958 buffer_position: text::Anchor,
12959 cx: &mut AppContext,
12960) -> Vec<Completion> {
12961 let language = buffer.read(cx).language_at(buffer_position);
12962 let language_name = language.as_ref().map(|language| language.lsp_id());
12963 let snippet_store = project.snippets().read(cx);
12964 let snippets = snippet_store.snippets_for(language_name, cx);
12965
12966 if snippets.is_empty() {
12967 return vec![];
12968 }
12969 let snapshot = buffer.read(cx).text_snapshot();
12970 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12971
12972 let mut lines = chunks.lines();
12973 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12974 return vec![];
12975 };
12976
12977 let scope = language.map(|language| language.default_scope());
12978 let classifier = CharClassifier::new(scope).for_completion(true);
12979 let mut last_word = line_at
12980 .chars()
12981 .rev()
12982 .take_while(|c| classifier.is_word(*c))
12983 .collect::<String>();
12984 last_word = last_word.chars().rev().collect();
12985 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12986 let to_lsp = |point: &text::Anchor| {
12987 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12988 point_to_lsp(end)
12989 };
12990 let lsp_end = to_lsp(&buffer_position);
12991 snippets
12992 .into_iter()
12993 .filter_map(|snippet| {
12994 let matching_prefix = snippet
12995 .prefix
12996 .iter()
12997 .find(|prefix| prefix.starts_with(&last_word))?;
12998 let start = as_offset - last_word.len();
12999 let start = snapshot.anchor_before(start);
13000 let range = start..buffer_position;
13001 let lsp_start = to_lsp(&start);
13002 let lsp_range = lsp::Range {
13003 start: lsp_start,
13004 end: lsp_end,
13005 };
13006 Some(Completion {
13007 old_range: range,
13008 new_text: snippet.body.clone(),
13009 label: CodeLabel {
13010 text: matching_prefix.clone(),
13011 runs: vec![],
13012 filter_range: 0..matching_prefix.len(),
13013 },
13014 server_id: LanguageServerId(usize::MAX),
13015 documentation: snippet.description.clone().map(Documentation::SingleLine),
13016 lsp_completion: lsp::CompletionItem {
13017 label: snippet.prefix.first().unwrap().clone(),
13018 kind: Some(CompletionItemKind::SNIPPET),
13019 label_details: snippet.description.as_ref().map(|description| {
13020 lsp::CompletionItemLabelDetails {
13021 detail: Some(description.clone()),
13022 description: None,
13023 }
13024 }),
13025 insert_text_format: Some(InsertTextFormat::SNIPPET),
13026 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13027 lsp::InsertReplaceEdit {
13028 new_text: snippet.body.clone(),
13029 insert: lsp_range,
13030 replace: lsp_range,
13031 },
13032 )),
13033 filter_text: Some(snippet.body.clone()),
13034 sort_text: Some(char::MAX.to_string()),
13035 ..Default::default()
13036 },
13037 confirm: None,
13038 })
13039 })
13040 .collect()
13041}
13042
13043impl CompletionProvider for Model<Project> {
13044 fn completions(
13045 &self,
13046 buffer: &Model<Buffer>,
13047 buffer_position: text::Anchor,
13048 options: CompletionContext,
13049 cx: &mut ViewContext<Editor>,
13050 ) -> Task<Result<Vec<Completion>>> {
13051 self.update(cx, |project, cx| {
13052 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13053 let project_completions = project.completions(buffer, buffer_position, options, cx);
13054 cx.background_executor().spawn(async move {
13055 let mut completions = project_completions.await?;
13056 //let snippets = snippets.into_iter().;
13057 completions.extend(snippets);
13058 Ok(completions)
13059 })
13060 })
13061 }
13062
13063 fn resolve_completions(
13064 &self,
13065 buffer: Model<Buffer>,
13066 completion_indices: Vec<usize>,
13067 completions: Arc<RwLock<Box<[Completion]>>>,
13068 cx: &mut ViewContext<Editor>,
13069 ) -> Task<Result<bool>> {
13070 self.update(cx, |project, cx| {
13071 project.resolve_completions(buffer, completion_indices, completions, cx)
13072 })
13073 }
13074
13075 fn apply_additional_edits_for_completion(
13076 &self,
13077 buffer: Model<Buffer>,
13078 completion: Completion,
13079 push_to_history: bool,
13080 cx: &mut ViewContext<Editor>,
13081 ) -> Task<Result<Option<language::Transaction>>> {
13082 self.update(cx, |project, cx| {
13083 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13084 })
13085 }
13086
13087 fn is_completion_trigger(
13088 &self,
13089 buffer: &Model<Buffer>,
13090 position: language::Anchor,
13091 text: &str,
13092 trigger_in_words: bool,
13093 cx: &mut ViewContext<Editor>,
13094 ) -> bool {
13095 if !EditorSettings::get_global(cx).show_completions_on_input {
13096 return false;
13097 }
13098
13099 let mut chars = text.chars();
13100 let char = if let Some(char) = chars.next() {
13101 char
13102 } else {
13103 return false;
13104 };
13105 if chars.next().is_some() {
13106 return false;
13107 }
13108
13109 let buffer = buffer.read(cx);
13110 let classifier = buffer
13111 .snapshot()
13112 .char_classifier_at(position)
13113 .for_completion(true);
13114 if trigger_in_words && classifier.is_word(char) {
13115 return true;
13116 }
13117
13118 buffer
13119 .completion_triggers()
13120 .iter()
13121 .any(|string| string == text)
13122 }
13123}
13124
13125fn inlay_hint_settings(
13126 location: Anchor,
13127 snapshot: &MultiBufferSnapshot,
13128 cx: &mut ViewContext<'_, Editor>,
13129) -> InlayHintSettings {
13130 let file = snapshot.file_at(location);
13131 let language = snapshot.language_at(location);
13132 let settings = all_language_settings(file, cx);
13133 settings
13134 .language(language.map(|l| l.name()).as_ref())
13135 .inlay_hints
13136}
13137
13138fn consume_contiguous_rows(
13139 contiguous_row_selections: &mut Vec<Selection<Point>>,
13140 selection: &Selection<Point>,
13141 display_map: &DisplaySnapshot,
13142 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13143) -> (MultiBufferRow, MultiBufferRow) {
13144 contiguous_row_selections.push(selection.clone());
13145 let start_row = MultiBufferRow(selection.start.row);
13146 let mut end_row = ending_row(selection, display_map);
13147
13148 while let Some(next_selection) = selections.peek() {
13149 if next_selection.start.row <= end_row.0 {
13150 end_row = ending_row(next_selection, display_map);
13151 contiguous_row_selections.push(selections.next().unwrap().clone());
13152 } else {
13153 break;
13154 }
13155 }
13156 (start_row, end_row)
13157}
13158
13159fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13160 if next_selection.end.column > 0 || next_selection.is_empty() {
13161 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13162 } else {
13163 MultiBufferRow(next_selection.end.row)
13164 }
13165}
13166
13167impl EditorSnapshot {
13168 pub fn remote_selections_in_range<'a>(
13169 &'a self,
13170 range: &'a Range<Anchor>,
13171 collaboration_hub: &dyn CollaborationHub,
13172 cx: &'a AppContext,
13173 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13174 let participant_names = collaboration_hub.user_names(cx);
13175 let participant_indices = collaboration_hub.user_participant_indices(cx);
13176 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13177 let collaborators_by_replica_id = collaborators_by_peer_id
13178 .iter()
13179 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13180 .collect::<HashMap<_, _>>();
13181 self.buffer_snapshot
13182 .selections_in_range(range, false)
13183 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13184 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13185 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13186 let user_name = participant_names.get(&collaborator.user_id).cloned();
13187 Some(RemoteSelection {
13188 replica_id,
13189 selection,
13190 cursor_shape,
13191 line_mode,
13192 participant_index,
13193 peer_id: collaborator.peer_id,
13194 user_name,
13195 })
13196 })
13197 }
13198
13199 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13200 self.display_snapshot.buffer_snapshot.language_at(position)
13201 }
13202
13203 pub fn is_focused(&self) -> bool {
13204 self.is_focused
13205 }
13206
13207 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13208 self.placeholder_text.as_ref()
13209 }
13210
13211 pub fn scroll_position(&self) -> gpui::Point<f32> {
13212 self.scroll_anchor.scroll_position(&self.display_snapshot)
13213 }
13214
13215 fn gutter_dimensions(
13216 &self,
13217 font_id: FontId,
13218 font_size: Pixels,
13219 em_width: Pixels,
13220 em_advance: Pixels,
13221 max_line_number_width: Pixels,
13222 cx: &AppContext,
13223 ) -> GutterDimensions {
13224 if !self.show_gutter {
13225 return GutterDimensions::default();
13226 }
13227 let descent = cx.text_system().descent(font_id, font_size);
13228
13229 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13230 matches!(
13231 ProjectSettings::get_global(cx).git.git_gutter,
13232 Some(GitGutterSetting::TrackedFiles)
13233 )
13234 });
13235 let gutter_settings = EditorSettings::get_global(cx).gutter;
13236 let show_line_numbers = self
13237 .show_line_numbers
13238 .unwrap_or(gutter_settings.line_numbers);
13239 let line_gutter_width = if show_line_numbers {
13240 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13241 let min_width_for_number_on_gutter = em_advance * 4.0;
13242 max_line_number_width.max(min_width_for_number_on_gutter)
13243 } else {
13244 0.0.into()
13245 };
13246
13247 let show_code_actions = self
13248 .show_code_actions
13249 .unwrap_or(gutter_settings.code_actions);
13250
13251 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13252
13253 let git_blame_entries_width =
13254 self.git_blame_gutter_max_author_length
13255 .map(|max_author_length| {
13256 // Length of the author name, but also space for the commit hash,
13257 // the spacing and the timestamp.
13258 let max_char_count = max_author_length
13259 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13260 + 7 // length of commit sha
13261 + 14 // length of max relative timestamp ("60 minutes ago")
13262 + 4; // gaps and margins
13263
13264 em_advance * max_char_count
13265 });
13266
13267 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13268 left_padding += if show_code_actions || show_runnables {
13269 em_width * 3.0
13270 } else if show_git_gutter && show_line_numbers {
13271 em_width * 2.0
13272 } else if show_git_gutter || show_line_numbers {
13273 em_width
13274 } else {
13275 px(0.)
13276 };
13277
13278 let right_padding = if gutter_settings.folds && show_line_numbers {
13279 em_width * 4.0
13280 } else if gutter_settings.folds {
13281 em_width * 3.0
13282 } else if show_line_numbers {
13283 em_width
13284 } else {
13285 px(0.)
13286 };
13287
13288 GutterDimensions {
13289 left_padding,
13290 right_padding,
13291 width: line_gutter_width + left_padding + right_padding,
13292 margin: -descent,
13293 git_blame_entries_width,
13294 }
13295 }
13296
13297 pub fn render_fold_toggle(
13298 &self,
13299 buffer_row: MultiBufferRow,
13300 row_contains_cursor: bool,
13301 editor: View<Editor>,
13302 cx: &mut WindowContext,
13303 ) -> Option<AnyElement> {
13304 let folded = self.is_line_folded(buffer_row);
13305
13306 if let Some(crease) = self
13307 .crease_snapshot
13308 .query_row(buffer_row, &self.buffer_snapshot)
13309 {
13310 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13311 if folded {
13312 editor.update(cx, |editor, cx| {
13313 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13314 });
13315 } else {
13316 editor.update(cx, |editor, cx| {
13317 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13318 });
13319 }
13320 });
13321
13322 Some((crease.render_toggle)(
13323 buffer_row,
13324 folded,
13325 toggle_callback,
13326 cx,
13327 ))
13328 } else if folded
13329 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13330 {
13331 Some(
13332 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13333 .selected(folded)
13334 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13335 if folded {
13336 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13337 } else {
13338 this.fold_at(&FoldAt { buffer_row }, cx);
13339 }
13340 }))
13341 .into_any_element(),
13342 )
13343 } else {
13344 None
13345 }
13346 }
13347
13348 pub fn render_crease_trailer(
13349 &self,
13350 buffer_row: MultiBufferRow,
13351 cx: &mut WindowContext,
13352 ) -> Option<AnyElement> {
13353 let folded = self.is_line_folded(buffer_row);
13354 let crease = self
13355 .crease_snapshot
13356 .query_row(buffer_row, &self.buffer_snapshot)?;
13357 Some((crease.render_trailer)(buffer_row, folded, cx))
13358 }
13359}
13360
13361impl Deref for EditorSnapshot {
13362 type Target = DisplaySnapshot;
13363
13364 fn deref(&self) -> &Self::Target {
13365 &self.display_snapshot
13366 }
13367}
13368
13369#[derive(Clone, Debug, PartialEq, Eq)]
13370pub enum EditorEvent {
13371 InputIgnored {
13372 text: Arc<str>,
13373 },
13374 InputHandled {
13375 utf16_range_to_replace: Option<Range<isize>>,
13376 text: Arc<str>,
13377 },
13378 ExcerptsAdded {
13379 buffer: Model<Buffer>,
13380 predecessor: ExcerptId,
13381 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13382 },
13383 ExcerptsRemoved {
13384 ids: Vec<ExcerptId>,
13385 },
13386 ExcerptsEdited {
13387 ids: Vec<ExcerptId>,
13388 },
13389 ExcerptsExpanded {
13390 ids: Vec<ExcerptId>,
13391 },
13392 BufferEdited,
13393 Edited {
13394 transaction_id: clock::Lamport,
13395 },
13396 Reparsed(BufferId),
13397 Focused,
13398 FocusedIn,
13399 Blurred,
13400 DirtyChanged,
13401 Saved,
13402 TitleChanged,
13403 DiffBaseChanged,
13404 SelectionsChanged {
13405 local: bool,
13406 },
13407 ScrollPositionChanged {
13408 local: bool,
13409 autoscroll: bool,
13410 },
13411 Closed,
13412 TransactionUndone {
13413 transaction_id: clock::Lamport,
13414 },
13415 TransactionBegun {
13416 transaction_id: clock::Lamport,
13417 },
13418 CursorShapeChanged,
13419}
13420
13421impl EventEmitter<EditorEvent> for Editor {}
13422
13423impl FocusableView for Editor {
13424 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13425 self.focus_handle.clone()
13426 }
13427}
13428
13429impl Render for Editor {
13430 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13431 let settings = ThemeSettings::get_global(cx);
13432
13433 let text_style = match self.mode {
13434 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13435 color: cx.theme().colors().editor_foreground,
13436 font_family: settings.ui_font.family.clone(),
13437 font_features: settings.ui_font.features.clone(),
13438 font_fallbacks: settings.ui_font.fallbacks.clone(),
13439 font_size: rems(0.875).into(),
13440 font_weight: settings.ui_font.weight,
13441 line_height: relative(settings.buffer_line_height.value()),
13442 ..Default::default()
13443 },
13444 EditorMode::Full => TextStyle {
13445 color: cx.theme().colors().editor_foreground,
13446 font_family: settings.buffer_font.family.clone(),
13447 font_features: settings.buffer_font.features.clone(),
13448 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13449 font_size: settings.buffer_font_size(cx).into(),
13450 font_weight: settings.buffer_font.weight,
13451 line_height: relative(settings.buffer_line_height.value()),
13452 ..Default::default()
13453 },
13454 };
13455
13456 let background = match self.mode {
13457 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13458 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13459 EditorMode::Full => cx.theme().colors().editor_background,
13460 };
13461
13462 EditorElement::new(
13463 cx.view(),
13464 EditorStyle {
13465 background,
13466 local_player: cx.theme().players().local(),
13467 text: text_style,
13468 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13469 syntax: cx.theme().syntax().clone(),
13470 status: cx.theme().status().clone(),
13471 inlay_hints_style: make_inlay_hints_style(cx),
13472 suggestions_style: HighlightStyle {
13473 color: Some(cx.theme().status().predictive),
13474 ..HighlightStyle::default()
13475 },
13476 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13477 },
13478 )
13479 }
13480}
13481
13482impl ViewInputHandler for Editor {
13483 fn text_for_range(
13484 &mut self,
13485 range_utf16: Range<usize>,
13486 cx: &mut ViewContext<Self>,
13487 ) -> Option<String> {
13488 Some(
13489 self.buffer
13490 .read(cx)
13491 .read(cx)
13492 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13493 .collect(),
13494 )
13495 }
13496
13497 fn selected_text_range(
13498 &mut self,
13499 ignore_disabled_input: bool,
13500 cx: &mut ViewContext<Self>,
13501 ) -> Option<UTF16Selection> {
13502 // Prevent the IME menu from appearing when holding down an alphabetic key
13503 // while input is disabled.
13504 if !ignore_disabled_input && !self.input_enabled {
13505 return None;
13506 }
13507
13508 let selection = self.selections.newest::<OffsetUtf16>(cx);
13509 let range = selection.range();
13510
13511 Some(UTF16Selection {
13512 range: range.start.0..range.end.0,
13513 reversed: selection.reversed,
13514 })
13515 }
13516
13517 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13518 let snapshot = self.buffer.read(cx).read(cx);
13519 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13520 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13521 }
13522
13523 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13524 self.clear_highlights::<InputComposition>(cx);
13525 self.ime_transaction.take();
13526 }
13527
13528 fn replace_text_in_range(
13529 &mut self,
13530 range_utf16: Option<Range<usize>>,
13531 text: &str,
13532 cx: &mut ViewContext<Self>,
13533 ) {
13534 if !self.input_enabled {
13535 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13536 return;
13537 }
13538
13539 self.transact(cx, |this, cx| {
13540 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13541 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13542 Some(this.selection_replacement_ranges(range_utf16, cx))
13543 } else {
13544 this.marked_text_ranges(cx)
13545 };
13546
13547 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13548 let newest_selection_id = this.selections.newest_anchor().id;
13549 this.selections
13550 .all::<OffsetUtf16>(cx)
13551 .iter()
13552 .zip(ranges_to_replace.iter())
13553 .find_map(|(selection, range)| {
13554 if selection.id == newest_selection_id {
13555 Some(
13556 (range.start.0 as isize - selection.head().0 as isize)
13557 ..(range.end.0 as isize - selection.head().0 as isize),
13558 )
13559 } else {
13560 None
13561 }
13562 })
13563 });
13564
13565 cx.emit(EditorEvent::InputHandled {
13566 utf16_range_to_replace: range_to_replace,
13567 text: text.into(),
13568 });
13569
13570 if let Some(new_selected_ranges) = new_selected_ranges {
13571 this.change_selections(None, cx, |selections| {
13572 selections.select_ranges(new_selected_ranges)
13573 });
13574 this.backspace(&Default::default(), cx);
13575 }
13576
13577 this.handle_input(text, cx);
13578 });
13579
13580 if let Some(transaction) = self.ime_transaction {
13581 self.buffer.update(cx, |buffer, cx| {
13582 buffer.group_until_transaction(transaction, cx);
13583 });
13584 }
13585
13586 self.unmark_text(cx);
13587 }
13588
13589 fn replace_and_mark_text_in_range(
13590 &mut self,
13591 range_utf16: Option<Range<usize>>,
13592 text: &str,
13593 new_selected_range_utf16: Option<Range<usize>>,
13594 cx: &mut ViewContext<Self>,
13595 ) {
13596 if !self.input_enabled {
13597 return;
13598 }
13599
13600 let transaction = self.transact(cx, |this, cx| {
13601 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13602 let snapshot = this.buffer.read(cx).read(cx);
13603 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13604 for marked_range in &mut marked_ranges {
13605 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13606 marked_range.start.0 += relative_range_utf16.start;
13607 marked_range.start =
13608 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13609 marked_range.end =
13610 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13611 }
13612 }
13613 Some(marked_ranges)
13614 } else if let Some(range_utf16) = range_utf16 {
13615 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13616 Some(this.selection_replacement_ranges(range_utf16, cx))
13617 } else {
13618 None
13619 };
13620
13621 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13622 let newest_selection_id = this.selections.newest_anchor().id;
13623 this.selections
13624 .all::<OffsetUtf16>(cx)
13625 .iter()
13626 .zip(ranges_to_replace.iter())
13627 .find_map(|(selection, range)| {
13628 if selection.id == newest_selection_id {
13629 Some(
13630 (range.start.0 as isize - selection.head().0 as isize)
13631 ..(range.end.0 as isize - selection.head().0 as isize),
13632 )
13633 } else {
13634 None
13635 }
13636 })
13637 });
13638
13639 cx.emit(EditorEvent::InputHandled {
13640 utf16_range_to_replace: range_to_replace,
13641 text: text.into(),
13642 });
13643
13644 if let Some(ranges) = ranges_to_replace {
13645 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13646 }
13647
13648 let marked_ranges = {
13649 let snapshot = this.buffer.read(cx).read(cx);
13650 this.selections
13651 .disjoint_anchors()
13652 .iter()
13653 .map(|selection| {
13654 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13655 })
13656 .collect::<Vec<_>>()
13657 };
13658
13659 if text.is_empty() {
13660 this.unmark_text(cx);
13661 } else {
13662 this.highlight_text::<InputComposition>(
13663 marked_ranges.clone(),
13664 HighlightStyle {
13665 underline: Some(UnderlineStyle {
13666 thickness: px(1.),
13667 color: None,
13668 wavy: false,
13669 }),
13670 ..Default::default()
13671 },
13672 cx,
13673 );
13674 }
13675
13676 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13677 let use_autoclose = this.use_autoclose;
13678 let use_auto_surround = this.use_auto_surround;
13679 this.set_use_autoclose(false);
13680 this.set_use_auto_surround(false);
13681 this.handle_input(text, cx);
13682 this.set_use_autoclose(use_autoclose);
13683 this.set_use_auto_surround(use_auto_surround);
13684
13685 if let Some(new_selected_range) = new_selected_range_utf16 {
13686 let snapshot = this.buffer.read(cx).read(cx);
13687 let new_selected_ranges = marked_ranges
13688 .into_iter()
13689 .map(|marked_range| {
13690 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13691 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13692 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13693 snapshot.clip_offset_utf16(new_start, Bias::Left)
13694 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13695 })
13696 .collect::<Vec<_>>();
13697
13698 drop(snapshot);
13699 this.change_selections(None, cx, |selections| {
13700 selections.select_ranges(new_selected_ranges)
13701 });
13702 }
13703 });
13704
13705 self.ime_transaction = self.ime_transaction.or(transaction);
13706 if let Some(transaction) = self.ime_transaction {
13707 self.buffer.update(cx, |buffer, cx| {
13708 buffer.group_until_transaction(transaction, cx);
13709 });
13710 }
13711
13712 if self.text_highlights::<InputComposition>(cx).is_none() {
13713 self.ime_transaction.take();
13714 }
13715 }
13716
13717 fn bounds_for_range(
13718 &mut self,
13719 range_utf16: Range<usize>,
13720 element_bounds: gpui::Bounds<Pixels>,
13721 cx: &mut ViewContext<Self>,
13722 ) -> Option<gpui::Bounds<Pixels>> {
13723 let text_layout_details = self.text_layout_details(cx);
13724 let style = &text_layout_details.editor_style;
13725 let font_id = cx.text_system().resolve_font(&style.text.font());
13726 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13727 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13728
13729 let em_width = cx
13730 .text_system()
13731 .typographic_bounds(font_id, font_size, 'm')
13732 .unwrap()
13733 .size
13734 .width;
13735
13736 let snapshot = self.snapshot(cx);
13737 let scroll_position = snapshot.scroll_position();
13738 let scroll_left = scroll_position.x * em_width;
13739
13740 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13741 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13742 + self.gutter_dimensions.width;
13743 let y = line_height * (start.row().as_f32() - scroll_position.y);
13744
13745 Some(Bounds {
13746 origin: element_bounds.origin + point(x, y),
13747 size: size(em_width, line_height),
13748 })
13749 }
13750}
13751
13752trait SelectionExt {
13753 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13754 fn spanned_rows(
13755 &self,
13756 include_end_if_at_line_start: bool,
13757 map: &DisplaySnapshot,
13758 ) -> Range<MultiBufferRow>;
13759}
13760
13761impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13762 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13763 let start = self
13764 .start
13765 .to_point(&map.buffer_snapshot)
13766 .to_display_point(map);
13767 let end = self
13768 .end
13769 .to_point(&map.buffer_snapshot)
13770 .to_display_point(map);
13771 if self.reversed {
13772 end..start
13773 } else {
13774 start..end
13775 }
13776 }
13777
13778 fn spanned_rows(
13779 &self,
13780 include_end_if_at_line_start: bool,
13781 map: &DisplaySnapshot,
13782 ) -> Range<MultiBufferRow> {
13783 let start = self.start.to_point(&map.buffer_snapshot);
13784 let mut end = self.end.to_point(&map.buffer_snapshot);
13785 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13786 end.row -= 1;
13787 }
13788
13789 let buffer_start = map.prev_line_boundary(start).0;
13790 let buffer_end = map.next_line_boundary(end).0;
13791 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13792 }
13793}
13794
13795impl<T: InvalidationRegion> InvalidationStack<T> {
13796 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13797 where
13798 S: Clone + ToOffset,
13799 {
13800 while let Some(region) = self.last() {
13801 let all_selections_inside_invalidation_ranges =
13802 if selections.len() == region.ranges().len() {
13803 selections
13804 .iter()
13805 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13806 .all(|(selection, invalidation_range)| {
13807 let head = selection.head().to_offset(buffer);
13808 invalidation_range.start <= head && invalidation_range.end >= head
13809 })
13810 } else {
13811 false
13812 };
13813
13814 if all_selections_inside_invalidation_ranges {
13815 break;
13816 } else {
13817 self.pop();
13818 }
13819 }
13820 }
13821}
13822
13823impl<T> Default for InvalidationStack<T> {
13824 fn default() -> Self {
13825 Self(Default::default())
13826 }
13827}
13828
13829impl<T> Deref for InvalidationStack<T> {
13830 type Target = Vec<T>;
13831
13832 fn deref(&self) -> &Self::Target {
13833 &self.0
13834 }
13835}
13836
13837impl<T> DerefMut for InvalidationStack<T> {
13838 fn deref_mut(&mut self) -> &mut Self::Target {
13839 &mut self.0
13840 }
13841}
13842
13843impl InvalidationRegion for SnippetState {
13844 fn ranges(&self) -> &[Range<Anchor>] {
13845 &self.ranges[self.active_index]
13846 }
13847}
13848
13849pub fn diagnostic_block_renderer(
13850 diagnostic: Diagnostic,
13851 max_message_rows: Option<u8>,
13852 allow_closing: bool,
13853 _is_valid: bool,
13854) -> RenderBlock {
13855 let (text_without_backticks, code_ranges) =
13856 highlight_diagnostic_message(&diagnostic, max_message_rows);
13857
13858 Box::new(move |cx: &mut BlockContext| {
13859 let group_id: SharedString = cx.block_id.to_string().into();
13860
13861 let mut text_style = cx.text_style().clone();
13862 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13863 let theme_settings = ThemeSettings::get_global(cx);
13864 text_style.font_family = theme_settings.buffer_font.family.clone();
13865 text_style.font_style = theme_settings.buffer_font.style;
13866 text_style.font_features = theme_settings.buffer_font.features.clone();
13867 text_style.font_weight = theme_settings.buffer_font.weight;
13868
13869 let multi_line_diagnostic = diagnostic.message.contains('\n');
13870
13871 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13872 if multi_line_diagnostic {
13873 v_flex()
13874 } else {
13875 h_flex()
13876 }
13877 .when(allow_closing, |div| {
13878 div.children(diagnostic.is_primary.then(|| {
13879 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13880 .icon_color(Color::Muted)
13881 .size(ButtonSize::Compact)
13882 .style(ButtonStyle::Transparent)
13883 .visible_on_hover(group_id.clone())
13884 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13885 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13886 }))
13887 })
13888 .child(
13889 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13890 .icon_color(Color::Muted)
13891 .size(ButtonSize::Compact)
13892 .style(ButtonStyle::Transparent)
13893 .visible_on_hover(group_id.clone())
13894 .on_click({
13895 let message = diagnostic.message.clone();
13896 move |_click, cx| {
13897 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13898 }
13899 })
13900 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13901 )
13902 };
13903
13904 let icon_size = buttons(&diagnostic, cx.block_id)
13905 .into_any_element()
13906 .layout_as_root(AvailableSpace::min_size(), cx);
13907
13908 h_flex()
13909 .id(cx.block_id)
13910 .group(group_id.clone())
13911 .relative()
13912 .size_full()
13913 .pl(cx.gutter_dimensions.width)
13914 .w(cx.max_width + cx.gutter_dimensions.width)
13915 .child(
13916 div()
13917 .flex()
13918 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13919 .flex_shrink(),
13920 )
13921 .child(buttons(&diagnostic, cx.block_id))
13922 .child(div().flex().flex_shrink_0().child(
13923 StyledText::new(text_without_backticks.clone()).with_highlights(
13924 &text_style,
13925 code_ranges.iter().map(|range| {
13926 (
13927 range.clone(),
13928 HighlightStyle {
13929 font_weight: Some(FontWeight::BOLD),
13930 ..Default::default()
13931 },
13932 )
13933 }),
13934 ),
13935 ))
13936 .into_any_element()
13937 })
13938}
13939
13940pub fn highlight_diagnostic_message(
13941 diagnostic: &Diagnostic,
13942 mut max_message_rows: Option<u8>,
13943) -> (SharedString, Vec<Range<usize>>) {
13944 let mut text_without_backticks = String::new();
13945 let mut code_ranges = Vec::new();
13946
13947 if let Some(source) = &diagnostic.source {
13948 text_without_backticks.push_str(source);
13949 code_ranges.push(0..source.len());
13950 text_without_backticks.push_str(": ");
13951 }
13952
13953 let mut prev_offset = 0;
13954 let mut in_code_block = false;
13955 let has_row_limit = max_message_rows.is_some();
13956 let mut newline_indices = diagnostic
13957 .message
13958 .match_indices('\n')
13959 .filter(|_| has_row_limit)
13960 .map(|(ix, _)| ix)
13961 .fuse()
13962 .peekable();
13963
13964 for (quote_ix, _) in diagnostic
13965 .message
13966 .match_indices('`')
13967 .chain([(diagnostic.message.len(), "")])
13968 {
13969 let mut first_newline_ix = None;
13970 let mut last_newline_ix = None;
13971 while let Some(newline_ix) = newline_indices.peek() {
13972 if *newline_ix < quote_ix {
13973 if first_newline_ix.is_none() {
13974 first_newline_ix = Some(*newline_ix);
13975 }
13976 last_newline_ix = Some(*newline_ix);
13977
13978 if let Some(rows_left) = &mut max_message_rows {
13979 if *rows_left == 0 {
13980 break;
13981 } else {
13982 *rows_left -= 1;
13983 }
13984 }
13985 let _ = newline_indices.next();
13986 } else {
13987 break;
13988 }
13989 }
13990 let prev_len = text_without_backticks.len();
13991 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13992 text_without_backticks.push_str(new_text);
13993 if in_code_block {
13994 code_ranges.push(prev_len..text_without_backticks.len());
13995 }
13996 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13997 in_code_block = !in_code_block;
13998 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13999 text_without_backticks.push_str("...");
14000 break;
14001 }
14002 }
14003
14004 (text_without_backticks.into(), code_ranges)
14005}
14006
14007fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14008 match severity {
14009 DiagnosticSeverity::ERROR => colors.error,
14010 DiagnosticSeverity::WARNING => colors.warning,
14011 DiagnosticSeverity::INFORMATION => colors.info,
14012 DiagnosticSeverity::HINT => colors.info,
14013 _ => colors.ignored,
14014 }
14015}
14016
14017pub fn styled_runs_for_code_label<'a>(
14018 label: &'a CodeLabel,
14019 syntax_theme: &'a theme::SyntaxTheme,
14020) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14021 let fade_out = HighlightStyle {
14022 fade_out: Some(0.35),
14023 ..Default::default()
14024 };
14025
14026 let mut prev_end = label.filter_range.end;
14027 label
14028 .runs
14029 .iter()
14030 .enumerate()
14031 .flat_map(move |(ix, (range, highlight_id))| {
14032 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14033 style
14034 } else {
14035 return Default::default();
14036 };
14037 let mut muted_style = style;
14038 muted_style.highlight(fade_out);
14039
14040 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14041 if range.start >= label.filter_range.end {
14042 if range.start > prev_end {
14043 runs.push((prev_end..range.start, fade_out));
14044 }
14045 runs.push((range.clone(), muted_style));
14046 } else if range.end <= label.filter_range.end {
14047 runs.push((range.clone(), style));
14048 } else {
14049 runs.push((range.start..label.filter_range.end, style));
14050 runs.push((label.filter_range.end..range.end, muted_style));
14051 }
14052 prev_end = cmp::max(prev_end, range.end);
14053
14054 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14055 runs.push((prev_end..label.text.len(), fade_out));
14056 }
14057
14058 runs
14059 })
14060}
14061
14062pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14063 let mut prev_index = 0;
14064 let mut prev_codepoint: Option<char> = None;
14065 text.char_indices()
14066 .chain([(text.len(), '\0')])
14067 .filter_map(move |(index, codepoint)| {
14068 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14069 let is_boundary = index == text.len()
14070 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14071 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14072 if is_boundary {
14073 let chunk = &text[prev_index..index];
14074 prev_index = index;
14075 Some(chunk)
14076 } else {
14077 None
14078 }
14079 })
14080}
14081
14082pub trait RangeToAnchorExt: Sized {
14083 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14084
14085 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14086 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14087 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14088 }
14089}
14090
14091impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14092 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14093 let start_offset = self.start.to_offset(snapshot);
14094 let end_offset = self.end.to_offset(snapshot);
14095 if start_offset == end_offset {
14096 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14097 } else {
14098 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14099 }
14100 }
14101}
14102
14103pub trait RowExt {
14104 fn as_f32(&self) -> f32;
14105
14106 fn next_row(&self) -> Self;
14107
14108 fn previous_row(&self) -> Self;
14109
14110 fn minus(&self, other: Self) -> u32;
14111}
14112
14113impl RowExt for DisplayRow {
14114 fn as_f32(&self) -> f32 {
14115 self.0 as f32
14116 }
14117
14118 fn next_row(&self) -> Self {
14119 Self(self.0 + 1)
14120 }
14121
14122 fn previous_row(&self) -> Self {
14123 Self(self.0.saturating_sub(1))
14124 }
14125
14126 fn minus(&self, other: Self) -> u32 {
14127 self.0 - other.0
14128 }
14129}
14130
14131impl RowExt for MultiBufferRow {
14132 fn as_f32(&self) -> f32 {
14133 self.0 as f32
14134 }
14135
14136 fn next_row(&self) -> Self {
14137 Self(self.0 + 1)
14138 }
14139
14140 fn previous_row(&self) -> Self {
14141 Self(self.0.saturating_sub(1))
14142 }
14143
14144 fn minus(&self, other: Self) -> u32 {
14145 self.0 - other.0
14146 }
14147}
14148
14149trait RowRangeExt {
14150 type Row;
14151
14152 fn len(&self) -> usize;
14153
14154 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14155}
14156
14157impl RowRangeExt for Range<MultiBufferRow> {
14158 type Row = MultiBufferRow;
14159
14160 fn len(&self) -> usize {
14161 (self.end.0 - self.start.0) as usize
14162 }
14163
14164 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14165 (self.start.0..self.end.0).map(MultiBufferRow)
14166 }
14167}
14168
14169impl RowRangeExt for Range<DisplayRow> {
14170 type Row = DisplayRow;
14171
14172 fn len(&self) -> usize {
14173 (self.end.0 - self.start.0) as usize
14174 }
14175
14176 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14177 (self.start.0..self.end.0).map(DisplayRow)
14178 }
14179}
14180
14181fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14182 if hunk.diff_base_byte_range.is_empty() {
14183 DiffHunkStatus::Added
14184 } else if hunk.row_range.is_empty() {
14185 DiffHunkStatus::Removed
14186 } else {
14187 DiffHunkStatus::Modified
14188 }
14189}
14190
14191/// If select range has more than one line, we
14192/// just point the cursor to range.start.
14193fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14194 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14195 range
14196 } else {
14197 range.start..range.start
14198 }
14199}