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_expanded_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 fn apply_selected_diff_hunks(&mut self, _: &ApplyDiffHunk, cx: &mut ViewContext<Self>) {
6209 let snapshot = self.buffer.read(cx).snapshot(cx);
6210 let hunks = hunks_for_selections(&snapshot, &self.selections.disjoint_anchors());
6211 self.transact(cx, |editor, cx| {
6212 for hunk in hunks {
6213 if let Some(buffer) = editor.buffer.read(cx).buffer(hunk.buffer_id) {
6214 buffer.update(cx, |buffer, cx| {
6215 buffer.merge_into_base(Some(hunk.buffer_range.to_offset(buffer)), cx);
6216 });
6217 }
6218 }
6219 });
6220 }
6221
6222 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6223 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6224 let project_path = buffer.read(cx).project_path(cx)?;
6225 let project = self.project.as_ref()?.read(cx);
6226 let entry = project.entry_for_path(&project_path, cx)?;
6227 let abs_path = project.absolute_path(&project_path, cx)?;
6228 let parent = if entry.is_symlink {
6229 abs_path.canonicalize().ok()?
6230 } else {
6231 abs_path
6232 }
6233 .parent()?
6234 .to_path_buf();
6235 Some(parent)
6236 }) {
6237 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6238 }
6239 }
6240
6241 fn gather_revert_changes(
6242 &mut self,
6243 selections: &[Selection<Anchor>],
6244 cx: &mut ViewContext<'_, Editor>,
6245 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6246 let mut revert_changes = HashMap::default();
6247 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6248 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6249 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6250 }
6251 revert_changes
6252 }
6253
6254 pub fn prepare_revert_change(
6255 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6256 multi_buffer: &Model<MultiBuffer>,
6257 hunk: &MultiBufferDiffHunk,
6258 cx: &AppContext,
6259 ) -> Option<()> {
6260 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6261 let buffer = buffer.read(cx);
6262 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6263 let buffer_snapshot = buffer.snapshot();
6264 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6265 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6266 probe
6267 .0
6268 .start
6269 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6270 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6271 }) {
6272 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6273 Some(())
6274 } else {
6275 None
6276 }
6277 }
6278
6279 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6280 self.manipulate_lines(cx, |lines| lines.reverse())
6281 }
6282
6283 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6284 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6285 }
6286
6287 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6288 where
6289 Fn: FnMut(&mut Vec<&str>),
6290 {
6291 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6292 let buffer = self.buffer.read(cx).snapshot(cx);
6293
6294 let mut edits = Vec::new();
6295
6296 let selections = self.selections.all::<Point>(cx);
6297 let mut selections = selections.iter().peekable();
6298 let mut contiguous_row_selections = Vec::new();
6299 let mut new_selections = Vec::new();
6300 let mut added_lines = 0;
6301 let mut removed_lines = 0;
6302
6303 while let Some(selection) = selections.next() {
6304 let (start_row, end_row) = consume_contiguous_rows(
6305 &mut contiguous_row_selections,
6306 selection,
6307 &display_map,
6308 &mut selections,
6309 );
6310
6311 let start_point = Point::new(start_row.0, 0);
6312 let end_point = Point::new(
6313 end_row.previous_row().0,
6314 buffer.line_len(end_row.previous_row()),
6315 );
6316 let text = buffer
6317 .text_for_range(start_point..end_point)
6318 .collect::<String>();
6319
6320 let mut lines = text.split('\n').collect_vec();
6321
6322 let lines_before = lines.len();
6323 callback(&mut lines);
6324 let lines_after = lines.len();
6325
6326 edits.push((start_point..end_point, lines.join("\n")));
6327
6328 // Selections must change based on added and removed line count
6329 let start_row =
6330 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6331 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6332 new_selections.push(Selection {
6333 id: selection.id,
6334 start: start_row,
6335 end: end_row,
6336 goal: SelectionGoal::None,
6337 reversed: selection.reversed,
6338 });
6339
6340 if lines_after > lines_before {
6341 added_lines += lines_after - lines_before;
6342 } else if lines_before > lines_after {
6343 removed_lines += lines_before - lines_after;
6344 }
6345 }
6346
6347 self.transact(cx, |this, cx| {
6348 let buffer = this.buffer.update(cx, |buffer, cx| {
6349 buffer.edit(edits, None, cx);
6350 buffer.snapshot(cx)
6351 });
6352
6353 // Recalculate offsets on newly edited buffer
6354 let new_selections = new_selections
6355 .iter()
6356 .map(|s| {
6357 let start_point = Point::new(s.start.0, 0);
6358 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6359 Selection {
6360 id: s.id,
6361 start: buffer.point_to_offset(start_point),
6362 end: buffer.point_to_offset(end_point),
6363 goal: s.goal,
6364 reversed: s.reversed,
6365 }
6366 })
6367 .collect();
6368
6369 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6370 s.select(new_selections);
6371 });
6372
6373 this.request_autoscroll(Autoscroll::fit(), cx);
6374 });
6375 }
6376
6377 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6378 self.manipulate_text(cx, |text| text.to_uppercase())
6379 }
6380
6381 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6382 self.manipulate_text(cx, |text| text.to_lowercase())
6383 }
6384
6385 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6386 self.manipulate_text(cx, |text| {
6387 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6388 // https://github.com/rutrum/convert-case/issues/16
6389 text.split('\n')
6390 .map(|line| line.to_case(Case::Title))
6391 .join("\n")
6392 })
6393 }
6394
6395 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6396 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6397 }
6398
6399 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6400 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6401 }
6402
6403 pub fn convert_to_upper_camel_case(
6404 &mut self,
6405 _: &ConvertToUpperCamelCase,
6406 cx: &mut ViewContext<Self>,
6407 ) {
6408 self.manipulate_text(cx, |text| {
6409 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6410 // https://github.com/rutrum/convert-case/issues/16
6411 text.split('\n')
6412 .map(|line| line.to_case(Case::UpperCamel))
6413 .join("\n")
6414 })
6415 }
6416
6417 pub fn convert_to_lower_camel_case(
6418 &mut self,
6419 _: &ConvertToLowerCamelCase,
6420 cx: &mut ViewContext<Self>,
6421 ) {
6422 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6423 }
6424
6425 pub fn convert_to_opposite_case(
6426 &mut self,
6427 _: &ConvertToOppositeCase,
6428 cx: &mut ViewContext<Self>,
6429 ) {
6430 self.manipulate_text(cx, |text| {
6431 text.chars()
6432 .fold(String::with_capacity(text.len()), |mut t, c| {
6433 if c.is_uppercase() {
6434 t.extend(c.to_lowercase());
6435 } else {
6436 t.extend(c.to_uppercase());
6437 }
6438 t
6439 })
6440 })
6441 }
6442
6443 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6444 where
6445 Fn: FnMut(&str) -> String,
6446 {
6447 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6448 let buffer = self.buffer.read(cx).snapshot(cx);
6449
6450 let mut new_selections = Vec::new();
6451 let mut edits = Vec::new();
6452 let mut selection_adjustment = 0i32;
6453
6454 for selection in self.selections.all::<usize>(cx) {
6455 let selection_is_empty = selection.is_empty();
6456
6457 let (start, end) = if selection_is_empty {
6458 let word_range = movement::surrounding_word(
6459 &display_map,
6460 selection.start.to_display_point(&display_map),
6461 );
6462 let start = word_range.start.to_offset(&display_map, Bias::Left);
6463 let end = word_range.end.to_offset(&display_map, Bias::Left);
6464 (start, end)
6465 } else {
6466 (selection.start, selection.end)
6467 };
6468
6469 let text = buffer.text_for_range(start..end).collect::<String>();
6470 let old_length = text.len() as i32;
6471 let text = callback(&text);
6472
6473 new_selections.push(Selection {
6474 start: (start as i32 - selection_adjustment) as usize,
6475 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6476 goal: SelectionGoal::None,
6477 ..selection
6478 });
6479
6480 selection_adjustment += old_length - text.len() as i32;
6481
6482 edits.push((start..end, text));
6483 }
6484
6485 self.transact(cx, |this, cx| {
6486 this.buffer.update(cx, |buffer, cx| {
6487 buffer.edit(edits, None, cx);
6488 });
6489
6490 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6491 s.select(new_selections);
6492 });
6493
6494 this.request_autoscroll(Autoscroll::fit(), cx);
6495 });
6496 }
6497
6498 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6499 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6500 let buffer = &display_map.buffer_snapshot;
6501 let selections = self.selections.all::<Point>(cx);
6502
6503 let mut edits = Vec::new();
6504 let mut selections_iter = selections.iter().peekable();
6505 while let Some(selection) = selections_iter.next() {
6506 // Avoid duplicating the same lines twice.
6507 let mut rows = selection.spanned_rows(false, &display_map);
6508
6509 while let Some(next_selection) = selections_iter.peek() {
6510 let next_rows = next_selection.spanned_rows(false, &display_map);
6511 if next_rows.start < rows.end {
6512 rows.end = next_rows.end;
6513 selections_iter.next().unwrap();
6514 } else {
6515 break;
6516 }
6517 }
6518
6519 // Copy the text from the selected row region and splice it either at the start
6520 // or end of the region.
6521 let start = Point::new(rows.start.0, 0);
6522 let end = Point::new(
6523 rows.end.previous_row().0,
6524 buffer.line_len(rows.end.previous_row()),
6525 );
6526 let text = buffer
6527 .text_for_range(start..end)
6528 .chain(Some("\n"))
6529 .collect::<String>();
6530 let insert_location = if upwards {
6531 Point::new(rows.end.0, 0)
6532 } else {
6533 start
6534 };
6535 edits.push((insert_location..insert_location, text));
6536 }
6537
6538 self.transact(cx, |this, cx| {
6539 this.buffer.update(cx, |buffer, cx| {
6540 buffer.edit(edits, None, cx);
6541 });
6542
6543 this.request_autoscroll(Autoscroll::fit(), cx);
6544 });
6545 }
6546
6547 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6548 self.duplicate_line(true, cx);
6549 }
6550
6551 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6552 self.duplicate_line(false, cx);
6553 }
6554
6555 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6556 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6557 let buffer = self.buffer.read(cx).snapshot(cx);
6558
6559 let mut edits = Vec::new();
6560 let mut unfold_ranges = Vec::new();
6561 let mut refold_ranges = Vec::new();
6562
6563 let selections = self.selections.all::<Point>(cx);
6564 let mut selections = selections.iter().peekable();
6565 let mut contiguous_row_selections = Vec::new();
6566 let mut new_selections = Vec::new();
6567
6568 while let Some(selection) = selections.next() {
6569 // Find all the selections that span a contiguous row range
6570 let (start_row, end_row) = consume_contiguous_rows(
6571 &mut contiguous_row_selections,
6572 selection,
6573 &display_map,
6574 &mut selections,
6575 );
6576
6577 // Move the text spanned by the row range to be before the line preceding the row range
6578 if start_row.0 > 0 {
6579 let range_to_move = Point::new(
6580 start_row.previous_row().0,
6581 buffer.line_len(start_row.previous_row()),
6582 )
6583 ..Point::new(
6584 end_row.previous_row().0,
6585 buffer.line_len(end_row.previous_row()),
6586 );
6587 let insertion_point = display_map
6588 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6589 .0;
6590
6591 // Don't move lines across excerpts
6592 if buffer
6593 .excerpt_boundaries_in_range((
6594 Bound::Excluded(insertion_point),
6595 Bound::Included(range_to_move.end),
6596 ))
6597 .next()
6598 .is_none()
6599 {
6600 let text = buffer
6601 .text_for_range(range_to_move.clone())
6602 .flat_map(|s| s.chars())
6603 .skip(1)
6604 .chain(['\n'])
6605 .collect::<String>();
6606
6607 edits.push((
6608 buffer.anchor_after(range_to_move.start)
6609 ..buffer.anchor_before(range_to_move.end),
6610 String::new(),
6611 ));
6612 let insertion_anchor = buffer.anchor_after(insertion_point);
6613 edits.push((insertion_anchor..insertion_anchor, text));
6614
6615 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6616
6617 // Move selections up
6618 new_selections.extend(contiguous_row_selections.drain(..).map(
6619 |mut selection| {
6620 selection.start.row -= row_delta;
6621 selection.end.row -= row_delta;
6622 selection
6623 },
6624 ));
6625
6626 // Move folds up
6627 unfold_ranges.push(range_to_move.clone());
6628 for fold in display_map.folds_in_range(
6629 buffer.anchor_before(range_to_move.start)
6630 ..buffer.anchor_after(range_to_move.end),
6631 ) {
6632 let mut start = fold.range.start.to_point(&buffer);
6633 let mut end = fold.range.end.to_point(&buffer);
6634 start.row -= row_delta;
6635 end.row -= row_delta;
6636 refold_ranges.push((start..end, fold.placeholder.clone()));
6637 }
6638 }
6639 }
6640
6641 // If we didn't move line(s), preserve the existing selections
6642 new_selections.append(&mut contiguous_row_selections);
6643 }
6644
6645 self.transact(cx, |this, cx| {
6646 this.unfold_ranges(unfold_ranges, true, true, cx);
6647 this.buffer.update(cx, |buffer, cx| {
6648 for (range, text) in edits {
6649 buffer.edit([(range, text)], None, cx);
6650 }
6651 });
6652 this.fold_ranges(refold_ranges, true, cx);
6653 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6654 s.select(new_selections);
6655 })
6656 });
6657 }
6658
6659 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6660 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6661 let buffer = self.buffer.read(cx).snapshot(cx);
6662
6663 let mut edits = Vec::new();
6664 let mut unfold_ranges = Vec::new();
6665 let mut refold_ranges = Vec::new();
6666
6667 let selections = self.selections.all::<Point>(cx);
6668 let mut selections = selections.iter().peekable();
6669 let mut contiguous_row_selections = Vec::new();
6670 let mut new_selections = Vec::new();
6671
6672 while let Some(selection) = selections.next() {
6673 // Find all the selections that span a contiguous row range
6674 let (start_row, end_row) = consume_contiguous_rows(
6675 &mut contiguous_row_selections,
6676 selection,
6677 &display_map,
6678 &mut selections,
6679 );
6680
6681 // Move the text spanned by the row range to be after the last line of the row range
6682 if end_row.0 <= buffer.max_point().row {
6683 let range_to_move =
6684 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6685 let insertion_point = display_map
6686 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6687 .0;
6688
6689 // Don't move lines across excerpt boundaries
6690 if buffer
6691 .excerpt_boundaries_in_range((
6692 Bound::Excluded(range_to_move.start),
6693 Bound::Included(insertion_point),
6694 ))
6695 .next()
6696 .is_none()
6697 {
6698 let mut text = String::from("\n");
6699 text.extend(buffer.text_for_range(range_to_move.clone()));
6700 text.pop(); // Drop trailing newline
6701 edits.push((
6702 buffer.anchor_after(range_to_move.start)
6703 ..buffer.anchor_before(range_to_move.end),
6704 String::new(),
6705 ));
6706 let insertion_anchor = buffer.anchor_after(insertion_point);
6707 edits.push((insertion_anchor..insertion_anchor, text));
6708
6709 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6710
6711 // Move selections down
6712 new_selections.extend(contiguous_row_selections.drain(..).map(
6713 |mut selection| {
6714 selection.start.row += row_delta;
6715 selection.end.row += row_delta;
6716 selection
6717 },
6718 ));
6719
6720 // Move folds down
6721 unfold_ranges.push(range_to_move.clone());
6722 for fold in display_map.folds_in_range(
6723 buffer.anchor_before(range_to_move.start)
6724 ..buffer.anchor_after(range_to_move.end),
6725 ) {
6726 let mut start = fold.range.start.to_point(&buffer);
6727 let mut end = fold.range.end.to_point(&buffer);
6728 start.row += row_delta;
6729 end.row += row_delta;
6730 refold_ranges.push((start..end, fold.placeholder.clone()));
6731 }
6732 }
6733 }
6734
6735 // If we didn't move line(s), preserve the existing selections
6736 new_selections.append(&mut contiguous_row_selections);
6737 }
6738
6739 self.transact(cx, |this, cx| {
6740 this.unfold_ranges(unfold_ranges, true, true, cx);
6741 this.buffer.update(cx, |buffer, cx| {
6742 for (range, text) in edits {
6743 buffer.edit([(range, text)], None, cx);
6744 }
6745 });
6746 this.fold_ranges(refold_ranges, true, cx);
6747 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6748 });
6749 }
6750
6751 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6752 let text_layout_details = &self.text_layout_details(cx);
6753 self.transact(cx, |this, cx| {
6754 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6755 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6756 let line_mode = s.line_mode;
6757 s.move_with(|display_map, selection| {
6758 if !selection.is_empty() || line_mode {
6759 return;
6760 }
6761
6762 let mut head = selection.head();
6763 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6764 if head.column() == display_map.line_len(head.row()) {
6765 transpose_offset = display_map
6766 .buffer_snapshot
6767 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6768 }
6769
6770 if transpose_offset == 0 {
6771 return;
6772 }
6773
6774 *head.column_mut() += 1;
6775 head = display_map.clip_point(head, Bias::Right);
6776 let goal = SelectionGoal::HorizontalPosition(
6777 display_map
6778 .x_for_display_point(head, text_layout_details)
6779 .into(),
6780 );
6781 selection.collapse_to(head, goal);
6782
6783 let transpose_start = display_map
6784 .buffer_snapshot
6785 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6786 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6787 let transpose_end = display_map
6788 .buffer_snapshot
6789 .clip_offset(transpose_offset + 1, Bias::Right);
6790 if let Some(ch) =
6791 display_map.buffer_snapshot.chars_at(transpose_start).next()
6792 {
6793 edits.push((transpose_start..transpose_offset, String::new()));
6794 edits.push((transpose_end..transpose_end, ch.to_string()));
6795 }
6796 }
6797 });
6798 edits
6799 });
6800 this.buffer
6801 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6802 let selections = this.selections.all::<usize>(cx);
6803 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6804 s.select(selections);
6805 });
6806 });
6807 }
6808
6809 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6810 self.rewrap_impl(true, cx)
6811 }
6812
6813 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6814 let buffer = self.buffer.read(cx).snapshot(cx);
6815 let selections = self.selections.all::<Point>(cx);
6816 let mut selections = selections.iter().peekable();
6817
6818 let mut edits = Vec::new();
6819 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6820
6821 while let Some(selection) = selections.next() {
6822 let mut start_row = selection.start.row;
6823 let mut end_row = selection.end.row;
6824
6825 // Skip selections that overlap with a range that has already been rewrapped.
6826 let selection_range = start_row..end_row;
6827 if rewrapped_row_ranges
6828 .iter()
6829 .any(|range| range.overlaps(&selection_range))
6830 {
6831 continue;
6832 }
6833
6834 let mut should_rewrap = !only_text;
6835
6836 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6837 match language_scope.language_name().0.as_ref() {
6838 "Markdown" | "Plain Text" => {
6839 should_rewrap = true;
6840 }
6841 _ => {}
6842 }
6843 }
6844
6845 // Since not all lines in the selection may be at the same indent
6846 // level, choose the indent size that is the most common between all
6847 // of the lines.
6848 //
6849 // If there is a tie, we use the deepest indent.
6850 let (indent_size, indent_end) = {
6851 let mut indent_size_occurrences = HashMap::default();
6852 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6853
6854 for row in start_row..=end_row {
6855 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6856 rows_by_indent_size.entry(indent).or_default().push(row);
6857 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6858 }
6859
6860 let indent_size = indent_size_occurrences
6861 .into_iter()
6862 .max_by_key(|(indent, count)| (*count, indent.len))
6863 .map(|(indent, _)| indent)
6864 .unwrap_or_default();
6865 let row = rows_by_indent_size[&indent_size][0];
6866 let indent_end = Point::new(row, indent_size.len);
6867
6868 (indent_size, indent_end)
6869 };
6870
6871 let mut line_prefix = indent_size.chars().collect::<String>();
6872
6873 if let Some(comment_prefix) =
6874 buffer
6875 .language_scope_at(selection.head())
6876 .and_then(|language| {
6877 language
6878 .line_comment_prefixes()
6879 .iter()
6880 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6881 .cloned()
6882 })
6883 {
6884 line_prefix.push_str(&comment_prefix);
6885 should_rewrap = true;
6886 }
6887
6888 if selection.is_empty() {
6889 'expand_upwards: while start_row > 0 {
6890 let prev_row = start_row - 1;
6891 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6892 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6893 {
6894 start_row = prev_row;
6895 } else {
6896 break 'expand_upwards;
6897 }
6898 }
6899
6900 'expand_downwards: while end_row < buffer.max_point().row {
6901 let next_row = end_row + 1;
6902 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6903 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6904 {
6905 end_row = next_row;
6906 } else {
6907 break 'expand_downwards;
6908 }
6909 }
6910 }
6911
6912 if !should_rewrap {
6913 continue;
6914 }
6915
6916 let start = Point::new(start_row, 0);
6917 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6918 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6919 let Some(lines_without_prefixes) = selection_text
6920 .lines()
6921 .map(|line| {
6922 line.strip_prefix(&line_prefix)
6923 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6924 .ok_or_else(|| {
6925 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6926 })
6927 })
6928 .collect::<Result<Vec<_>, _>>()
6929 .log_err()
6930 else {
6931 continue;
6932 };
6933
6934 let unwrapped_text = lines_without_prefixes.join(" ");
6935 let wrap_column = buffer
6936 .settings_at(Point::new(start_row, 0), cx)
6937 .preferred_line_length as usize;
6938 let mut wrapped_text = String::new();
6939 let mut current_line = line_prefix.clone();
6940 for word in unwrapped_text.split_whitespace() {
6941 if current_line.len() + word.len() >= wrap_column {
6942 wrapped_text.push_str(¤t_line);
6943 wrapped_text.push('\n');
6944 current_line.truncate(line_prefix.len());
6945 }
6946
6947 if current_line.len() > line_prefix.len() {
6948 current_line.push(' ');
6949 }
6950
6951 current_line.push_str(word);
6952 }
6953
6954 if !current_line.is_empty() {
6955 wrapped_text.push_str(¤t_line);
6956 }
6957
6958 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
6959 let mut offset = start.to_offset(&buffer);
6960 let mut moved_since_edit = true;
6961
6962 for change in diff.iter_all_changes() {
6963 let value = change.value();
6964 match change.tag() {
6965 ChangeTag::Equal => {
6966 offset += value.len();
6967 moved_since_edit = true;
6968 }
6969 ChangeTag::Delete => {
6970 let start = buffer.anchor_after(offset);
6971 let end = buffer.anchor_before(offset + value.len());
6972
6973 if moved_since_edit {
6974 edits.push((start..end, String::new()));
6975 } else {
6976 edits.last_mut().unwrap().0.end = end;
6977 }
6978
6979 offset += value.len();
6980 moved_since_edit = false;
6981 }
6982 ChangeTag::Insert => {
6983 if moved_since_edit {
6984 let anchor = buffer.anchor_after(offset);
6985 edits.push((anchor..anchor, value.to_string()));
6986 } else {
6987 edits.last_mut().unwrap().1.push_str(value);
6988 }
6989
6990 moved_since_edit = false;
6991 }
6992 }
6993 }
6994
6995 rewrapped_row_ranges.push(start_row..=end_row);
6996 }
6997
6998 self.buffer
6999 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
7000 }
7001
7002 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
7003 let mut text = String::new();
7004 let buffer = self.buffer.read(cx).snapshot(cx);
7005 let mut selections = self.selections.all::<Point>(cx);
7006 let mut clipboard_selections = Vec::with_capacity(selections.len());
7007 {
7008 let max_point = buffer.max_point();
7009 let mut is_first = true;
7010 for selection in &mut selections {
7011 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7012 if is_entire_line {
7013 selection.start = Point::new(selection.start.row, 0);
7014 if !selection.is_empty() && selection.end.column == 0 {
7015 selection.end = cmp::min(max_point, selection.end);
7016 } else {
7017 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
7018 }
7019 selection.goal = SelectionGoal::None;
7020 }
7021 if is_first {
7022 is_first = false;
7023 } else {
7024 text += "\n";
7025 }
7026 let mut len = 0;
7027 for chunk in buffer.text_for_range(selection.start..selection.end) {
7028 text.push_str(chunk);
7029 len += chunk.len();
7030 }
7031 clipboard_selections.push(ClipboardSelection {
7032 len,
7033 is_entire_line,
7034 first_line_indent: buffer
7035 .indent_size_for_line(MultiBufferRow(selection.start.row))
7036 .len,
7037 });
7038 }
7039 }
7040
7041 self.transact(cx, |this, cx| {
7042 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7043 s.select(selections);
7044 });
7045 this.insert("", cx);
7046 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7047 text,
7048 clipboard_selections,
7049 ));
7050 });
7051 }
7052
7053 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
7054 let selections = self.selections.all::<Point>(cx);
7055 let buffer = self.buffer.read(cx).read(cx);
7056 let mut text = String::new();
7057
7058 let mut clipboard_selections = Vec::with_capacity(selections.len());
7059 {
7060 let max_point = buffer.max_point();
7061 let mut is_first = true;
7062 for selection in selections.iter() {
7063 let mut start = selection.start;
7064 let mut end = selection.end;
7065 let is_entire_line = selection.is_empty() || self.selections.line_mode;
7066 if is_entire_line {
7067 start = Point::new(start.row, 0);
7068 end = cmp::min(max_point, Point::new(end.row + 1, 0));
7069 }
7070 if is_first {
7071 is_first = false;
7072 } else {
7073 text += "\n";
7074 }
7075 let mut len = 0;
7076 for chunk in buffer.text_for_range(start..end) {
7077 text.push_str(chunk);
7078 len += chunk.len();
7079 }
7080 clipboard_selections.push(ClipboardSelection {
7081 len,
7082 is_entire_line,
7083 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
7084 });
7085 }
7086 }
7087
7088 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
7089 text,
7090 clipboard_selections,
7091 ));
7092 }
7093
7094 pub fn do_paste(
7095 &mut self,
7096 text: &String,
7097 clipboard_selections: Option<Vec<ClipboardSelection>>,
7098 handle_entire_lines: bool,
7099 cx: &mut ViewContext<Self>,
7100 ) {
7101 if self.read_only(cx) {
7102 return;
7103 }
7104
7105 let clipboard_text = Cow::Borrowed(text);
7106
7107 self.transact(cx, |this, cx| {
7108 if let Some(mut clipboard_selections) = clipboard_selections {
7109 let old_selections = this.selections.all::<usize>(cx);
7110 let all_selections_were_entire_line =
7111 clipboard_selections.iter().all(|s| s.is_entire_line);
7112 let first_selection_indent_column =
7113 clipboard_selections.first().map(|s| s.first_line_indent);
7114 if clipboard_selections.len() != old_selections.len() {
7115 clipboard_selections.drain(..);
7116 }
7117
7118 this.buffer.update(cx, |buffer, cx| {
7119 let snapshot = buffer.read(cx);
7120 let mut start_offset = 0;
7121 let mut edits = Vec::new();
7122 let mut original_indent_columns = Vec::new();
7123 for (ix, selection) in old_selections.iter().enumerate() {
7124 let to_insert;
7125 let entire_line;
7126 let original_indent_column;
7127 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7128 let end_offset = start_offset + clipboard_selection.len;
7129 to_insert = &clipboard_text[start_offset..end_offset];
7130 entire_line = clipboard_selection.is_entire_line;
7131 start_offset = end_offset + 1;
7132 original_indent_column = Some(clipboard_selection.first_line_indent);
7133 } else {
7134 to_insert = clipboard_text.as_str();
7135 entire_line = all_selections_were_entire_line;
7136 original_indent_column = first_selection_indent_column
7137 }
7138
7139 // If the corresponding selection was empty when this slice of the
7140 // clipboard text was written, then the entire line containing the
7141 // selection was copied. If this selection is also currently empty,
7142 // then paste the line before the current line of the buffer.
7143 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7144 let column = selection.start.to_point(&snapshot).column as usize;
7145 let line_start = selection.start - column;
7146 line_start..line_start
7147 } else {
7148 selection.range()
7149 };
7150
7151 edits.push((range, to_insert));
7152 original_indent_columns.extend(original_indent_column);
7153 }
7154 drop(snapshot);
7155
7156 buffer.edit(
7157 edits,
7158 Some(AutoindentMode::Block {
7159 original_indent_columns,
7160 }),
7161 cx,
7162 );
7163 });
7164
7165 let selections = this.selections.all::<usize>(cx);
7166 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7167 } else {
7168 this.insert(&clipboard_text, cx);
7169 }
7170 });
7171 }
7172
7173 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7174 if let Some(item) = cx.read_from_clipboard() {
7175 let entries = item.entries();
7176
7177 match entries.first() {
7178 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7179 // of all the pasted entries.
7180 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7181 .do_paste(
7182 clipboard_string.text(),
7183 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7184 true,
7185 cx,
7186 ),
7187 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7188 }
7189 }
7190 }
7191
7192 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7193 if self.read_only(cx) {
7194 return;
7195 }
7196
7197 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7198 if let Some((selections, _)) =
7199 self.selection_history.transaction(transaction_id).cloned()
7200 {
7201 self.change_selections(None, cx, |s| {
7202 s.select_anchors(selections.to_vec());
7203 });
7204 }
7205 self.request_autoscroll(Autoscroll::fit(), cx);
7206 self.unmark_text(cx);
7207 self.refresh_inline_completion(true, false, cx);
7208 cx.emit(EditorEvent::Edited { transaction_id });
7209 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7210 }
7211 }
7212
7213 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7214 if self.read_only(cx) {
7215 return;
7216 }
7217
7218 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7219 if let Some((_, Some(selections))) =
7220 self.selection_history.transaction(transaction_id).cloned()
7221 {
7222 self.change_selections(None, cx, |s| {
7223 s.select_anchors(selections.to_vec());
7224 });
7225 }
7226 self.request_autoscroll(Autoscroll::fit(), cx);
7227 self.unmark_text(cx);
7228 self.refresh_inline_completion(true, false, cx);
7229 cx.emit(EditorEvent::Edited { transaction_id });
7230 }
7231 }
7232
7233 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7234 self.buffer
7235 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7236 }
7237
7238 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7239 self.buffer
7240 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7241 }
7242
7243 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7244 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7245 let line_mode = s.line_mode;
7246 s.move_with(|map, selection| {
7247 let cursor = if selection.is_empty() && !line_mode {
7248 movement::left(map, selection.start)
7249 } else {
7250 selection.start
7251 };
7252 selection.collapse_to(cursor, SelectionGoal::None);
7253 });
7254 })
7255 }
7256
7257 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7258 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7259 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7260 })
7261 }
7262
7263 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7264 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7265 let line_mode = s.line_mode;
7266 s.move_with(|map, selection| {
7267 let cursor = if selection.is_empty() && !line_mode {
7268 movement::right(map, selection.end)
7269 } else {
7270 selection.end
7271 };
7272 selection.collapse_to(cursor, SelectionGoal::None)
7273 });
7274 })
7275 }
7276
7277 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7278 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7279 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7280 })
7281 }
7282
7283 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7284 if self.take_rename(true, cx).is_some() {
7285 return;
7286 }
7287
7288 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7289 cx.propagate();
7290 return;
7291 }
7292
7293 let text_layout_details = &self.text_layout_details(cx);
7294 let selection_count = self.selections.count();
7295 let first_selection = self.selections.first_anchor();
7296
7297 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7298 let line_mode = s.line_mode;
7299 s.move_with(|map, selection| {
7300 if !selection.is_empty() && !line_mode {
7301 selection.goal = SelectionGoal::None;
7302 }
7303 let (cursor, goal) = movement::up(
7304 map,
7305 selection.start,
7306 selection.goal,
7307 false,
7308 text_layout_details,
7309 );
7310 selection.collapse_to(cursor, goal);
7311 });
7312 });
7313
7314 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7315 {
7316 cx.propagate();
7317 }
7318 }
7319
7320 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7321 if self.take_rename(true, cx).is_some() {
7322 return;
7323 }
7324
7325 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7326 cx.propagate();
7327 return;
7328 }
7329
7330 let text_layout_details = &self.text_layout_details(cx);
7331
7332 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7333 let line_mode = s.line_mode;
7334 s.move_with(|map, selection| {
7335 if !selection.is_empty() && !line_mode {
7336 selection.goal = SelectionGoal::None;
7337 }
7338 let (cursor, goal) = movement::up_by_rows(
7339 map,
7340 selection.start,
7341 action.lines,
7342 selection.goal,
7343 false,
7344 text_layout_details,
7345 );
7346 selection.collapse_to(cursor, goal);
7347 });
7348 })
7349 }
7350
7351 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7352 if self.take_rename(true, cx).is_some() {
7353 return;
7354 }
7355
7356 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7357 cx.propagate();
7358 return;
7359 }
7360
7361 let text_layout_details = &self.text_layout_details(cx);
7362
7363 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7364 let line_mode = s.line_mode;
7365 s.move_with(|map, selection| {
7366 if !selection.is_empty() && !line_mode {
7367 selection.goal = SelectionGoal::None;
7368 }
7369 let (cursor, goal) = movement::down_by_rows(
7370 map,
7371 selection.start,
7372 action.lines,
7373 selection.goal,
7374 false,
7375 text_layout_details,
7376 );
7377 selection.collapse_to(cursor, goal);
7378 });
7379 })
7380 }
7381
7382 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7383 let text_layout_details = &self.text_layout_details(cx);
7384 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7385 s.move_heads_with(|map, head, goal| {
7386 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7387 })
7388 })
7389 }
7390
7391 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7392 let text_layout_details = &self.text_layout_details(cx);
7393 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7394 s.move_heads_with(|map, head, goal| {
7395 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7396 })
7397 })
7398 }
7399
7400 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7401 let Some(row_count) = self.visible_row_count() else {
7402 return;
7403 };
7404
7405 let text_layout_details = &self.text_layout_details(cx);
7406
7407 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7408 s.move_heads_with(|map, head, goal| {
7409 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7410 })
7411 })
7412 }
7413
7414 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7415 if self.take_rename(true, cx).is_some() {
7416 return;
7417 }
7418
7419 if self
7420 .context_menu
7421 .write()
7422 .as_mut()
7423 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7424 .unwrap_or(false)
7425 {
7426 return;
7427 }
7428
7429 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7430 cx.propagate();
7431 return;
7432 }
7433
7434 let Some(row_count) = self.visible_row_count() else {
7435 return;
7436 };
7437
7438 let autoscroll = if action.center_cursor {
7439 Autoscroll::center()
7440 } else {
7441 Autoscroll::fit()
7442 };
7443
7444 let text_layout_details = &self.text_layout_details(cx);
7445
7446 self.change_selections(Some(autoscroll), cx, |s| {
7447 let line_mode = s.line_mode;
7448 s.move_with(|map, selection| {
7449 if !selection.is_empty() && !line_mode {
7450 selection.goal = SelectionGoal::None;
7451 }
7452 let (cursor, goal) = movement::up_by_rows(
7453 map,
7454 selection.end,
7455 row_count,
7456 selection.goal,
7457 false,
7458 text_layout_details,
7459 );
7460 selection.collapse_to(cursor, goal);
7461 });
7462 });
7463 }
7464
7465 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7466 let text_layout_details = &self.text_layout_details(cx);
7467 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7468 s.move_heads_with(|map, head, goal| {
7469 movement::up(map, head, goal, false, text_layout_details)
7470 })
7471 })
7472 }
7473
7474 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7475 self.take_rename(true, cx);
7476
7477 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7478 cx.propagate();
7479 return;
7480 }
7481
7482 let text_layout_details = &self.text_layout_details(cx);
7483 let selection_count = self.selections.count();
7484 let first_selection = self.selections.first_anchor();
7485
7486 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7487 let line_mode = s.line_mode;
7488 s.move_with(|map, selection| {
7489 if !selection.is_empty() && !line_mode {
7490 selection.goal = SelectionGoal::None;
7491 }
7492 let (cursor, goal) = movement::down(
7493 map,
7494 selection.end,
7495 selection.goal,
7496 false,
7497 text_layout_details,
7498 );
7499 selection.collapse_to(cursor, goal);
7500 });
7501 });
7502
7503 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7504 {
7505 cx.propagate();
7506 }
7507 }
7508
7509 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7510 let Some(row_count) = self.visible_row_count() else {
7511 return;
7512 };
7513
7514 let text_layout_details = &self.text_layout_details(cx);
7515
7516 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7517 s.move_heads_with(|map, head, goal| {
7518 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7519 })
7520 })
7521 }
7522
7523 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7524 if self.take_rename(true, cx).is_some() {
7525 return;
7526 }
7527
7528 if self
7529 .context_menu
7530 .write()
7531 .as_mut()
7532 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7533 .unwrap_or(false)
7534 {
7535 return;
7536 }
7537
7538 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7539 cx.propagate();
7540 return;
7541 }
7542
7543 let Some(row_count) = self.visible_row_count() else {
7544 return;
7545 };
7546
7547 let autoscroll = if action.center_cursor {
7548 Autoscroll::center()
7549 } else {
7550 Autoscroll::fit()
7551 };
7552
7553 let text_layout_details = &self.text_layout_details(cx);
7554 self.change_selections(Some(autoscroll), cx, |s| {
7555 let line_mode = s.line_mode;
7556 s.move_with(|map, selection| {
7557 if !selection.is_empty() && !line_mode {
7558 selection.goal = SelectionGoal::None;
7559 }
7560 let (cursor, goal) = movement::down_by_rows(
7561 map,
7562 selection.end,
7563 row_count,
7564 selection.goal,
7565 false,
7566 text_layout_details,
7567 );
7568 selection.collapse_to(cursor, goal);
7569 });
7570 });
7571 }
7572
7573 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7574 let text_layout_details = &self.text_layout_details(cx);
7575 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7576 s.move_heads_with(|map, head, goal| {
7577 movement::down(map, head, goal, false, text_layout_details)
7578 })
7579 });
7580 }
7581
7582 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7583 if let Some(context_menu) = self.context_menu.write().as_mut() {
7584 context_menu.select_first(self.project.as_ref(), cx);
7585 }
7586 }
7587
7588 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7589 if let Some(context_menu) = self.context_menu.write().as_mut() {
7590 context_menu.select_prev(self.project.as_ref(), cx);
7591 }
7592 }
7593
7594 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7595 if let Some(context_menu) = self.context_menu.write().as_mut() {
7596 context_menu.select_next(self.project.as_ref(), cx);
7597 }
7598 }
7599
7600 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7601 if let Some(context_menu) = self.context_menu.write().as_mut() {
7602 context_menu.select_last(self.project.as_ref(), cx);
7603 }
7604 }
7605
7606 pub fn move_to_previous_word_start(
7607 &mut self,
7608 _: &MoveToPreviousWordStart,
7609 cx: &mut ViewContext<Self>,
7610 ) {
7611 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7612 s.move_cursors_with(|map, head, _| {
7613 (
7614 movement::previous_word_start(map, head),
7615 SelectionGoal::None,
7616 )
7617 });
7618 })
7619 }
7620
7621 pub fn move_to_previous_subword_start(
7622 &mut self,
7623 _: &MoveToPreviousSubwordStart,
7624 cx: &mut ViewContext<Self>,
7625 ) {
7626 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7627 s.move_cursors_with(|map, head, _| {
7628 (
7629 movement::previous_subword_start(map, head),
7630 SelectionGoal::None,
7631 )
7632 });
7633 })
7634 }
7635
7636 pub fn select_to_previous_word_start(
7637 &mut self,
7638 _: &SelectToPreviousWordStart,
7639 cx: &mut ViewContext<Self>,
7640 ) {
7641 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7642 s.move_heads_with(|map, head, _| {
7643 (
7644 movement::previous_word_start(map, head),
7645 SelectionGoal::None,
7646 )
7647 });
7648 })
7649 }
7650
7651 pub fn select_to_previous_subword_start(
7652 &mut self,
7653 _: &SelectToPreviousSubwordStart,
7654 cx: &mut ViewContext<Self>,
7655 ) {
7656 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7657 s.move_heads_with(|map, head, _| {
7658 (
7659 movement::previous_subword_start(map, head),
7660 SelectionGoal::None,
7661 )
7662 });
7663 })
7664 }
7665
7666 pub fn delete_to_previous_word_start(
7667 &mut self,
7668 action: &DeleteToPreviousWordStart,
7669 cx: &mut ViewContext<Self>,
7670 ) {
7671 self.transact(cx, |this, cx| {
7672 this.select_autoclose_pair(cx);
7673 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7674 let line_mode = s.line_mode;
7675 s.move_with(|map, selection| {
7676 if selection.is_empty() && !line_mode {
7677 let cursor = if action.ignore_newlines {
7678 movement::previous_word_start(map, selection.head())
7679 } else {
7680 movement::previous_word_start_or_newline(map, selection.head())
7681 };
7682 selection.set_head(cursor, SelectionGoal::None);
7683 }
7684 });
7685 });
7686 this.insert("", cx);
7687 });
7688 }
7689
7690 pub fn delete_to_previous_subword_start(
7691 &mut self,
7692 _: &DeleteToPreviousSubwordStart,
7693 cx: &mut ViewContext<Self>,
7694 ) {
7695 self.transact(cx, |this, cx| {
7696 this.select_autoclose_pair(cx);
7697 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7698 let line_mode = s.line_mode;
7699 s.move_with(|map, selection| {
7700 if selection.is_empty() && !line_mode {
7701 let cursor = movement::previous_subword_start(map, selection.head());
7702 selection.set_head(cursor, SelectionGoal::None);
7703 }
7704 });
7705 });
7706 this.insert("", cx);
7707 });
7708 }
7709
7710 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7711 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7712 s.move_cursors_with(|map, head, _| {
7713 (movement::next_word_end(map, head), SelectionGoal::None)
7714 });
7715 })
7716 }
7717
7718 pub fn move_to_next_subword_end(
7719 &mut self,
7720 _: &MoveToNextSubwordEnd,
7721 cx: &mut ViewContext<Self>,
7722 ) {
7723 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7724 s.move_cursors_with(|map, head, _| {
7725 (movement::next_subword_end(map, head), SelectionGoal::None)
7726 });
7727 })
7728 }
7729
7730 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7731 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7732 s.move_heads_with(|map, head, _| {
7733 (movement::next_word_end(map, head), SelectionGoal::None)
7734 });
7735 })
7736 }
7737
7738 pub fn select_to_next_subword_end(
7739 &mut self,
7740 _: &SelectToNextSubwordEnd,
7741 cx: &mut ViewContext<Self>,
7742 ) {
7743 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7744 s.move_heads_with(|map, head, _| {
7745 (movement::next_subword_end(map, head), SelectionGoal::None)
7746 });
7747 })
7748 }
7749
7750 pub fn delete_to_next_word_end(
7751 &mut self,
7752 action: &DeleteToNextWordEnd,
7753 cx: &mut ViewContext<Self>,
7754 ) {
7755 self.transact(cx, |this, cx| {
7756 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7757 let line_mode = s.line_mode;
7758 s.move_with(|map, selection| {
7759 if selection.is_empty() && !line_mode {
7760 let cursor = if action.ignore_newlines {
7761 movement::next_word_end(map, selection.head())
7762 } else {
7763 movement::next_word_end_or_newline(map, selection.head())
7764 };
7765 selection.set_head(cursor, SelectionGoal::None);
7766 }
7767 });
7768 });
7769 this.insert("", cx);
7770 });
7771 }
7772
7773 pub fn delete_to_next_subword_end(
7774 &mut self,
7775 _: &DeleteToNextSubwordEnd,
7776 cx: &mut ViewContext<Self>,
7777 ) {
7778 self.transact(cx, |this, cx| {
7779 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7780 s.move_with(|map, selection| {
7781 if selection.is_empty() {
7782 let cursor = movement::next_subword_end(map, selection.head());
7783 selection.set_head(cursor, SelectionGoal::None);
7784 }
7785 });
7786 });
7787 this.insert("", cx);
7788 });
7789 }
7790
7791 pub fn move_to_beginning_of_line(
7792 &mut self,
7793 action: &MoveToBeginningOfLine,
7794 cx: &mut ViewContext<Self>,
7795 ) {
7796 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7797 s.move_cursors_with(|map, head, _| {
7798 (
7799 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7800 SelectionGoal::None,
7801 )
7802 });
7803 })
7804 }
7805
7806 pub fn select_to_beginning_of_line(
7807 &mut self,
7808 action: &SelectToBeginningOfLine,
7809 cx: &mut ViewContext<Self>,
7810 ) {
7811 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7812 s.move_heads_with(|map, head, _| {
7813 (
7814 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7815 SelectionGoal::None,
7816 )
7817 });
7818 });
7819 }
7820
7821 pub fn delete_to_beginning_of_line(
7822 &mut self,
7823 _: &DeleteToBeginningOfLine,
7824 cx: &mut ViewContext<Self>,
7825 ) {
7826 self.transact(cx, |this, cx| {
7827 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7828 s.move_with(|_, selection| {
7829 selection.reversed = true;
7830 });
7831 });
7832
7833 this.select_to_beginning_of_line(
7834 &SelectToBeginningOfLine {
7835 stop_at_soft_wraps: false,
7836 },
7837 cx,
7838 );
7839 this.backspace(&Backspace, cx);
7840 });
7841 }
7842
7843 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7844 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7845 s.move_cursors_with(|map, head, _| {
7846 (
7847 movement::line_end(map, head, action.stop_at_soft_wraps),
7848 SelectionGoal::None,
7849 )
7850 });
7851 })
7852 }
7853
7854 pub fn select_to_end_of_line(
7855 &mut self,
7856 action: &SelectToEndOfLine,
7857 cx: &mut ViewContext<Self>,
7858 ) {
7859 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7860 s.move_heads_with(|map, head, _| {
7861 (
7862 movement::line_end(map, head, action.stop_at_soft_wraps),
7863 SelectionGoal::None,
7864 )
7865 });
7866 })
7867 }
7868
7869 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7870 self.transact(cx, |this, cx| {
7871 this.select_to_end_of_line(
7872 &SelectToEndOfLine {
7873 stop_at_soft_wraps: false,
7874 },
7875 cx,
7876 );
7877 this.delete(&Delete, cx);
7878 });
7879 }
7880
7881 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7882 self.transact(cx, |this, cx| {
7883 this.select_to_end_of_line(
7884 &SelectToEndOfLine {
7885 stop_at_soft_wraps: false,
7886 },
7887 cx,
7888 );
7889 this.cut(&Cut, cx);
7890 });
7891 }
7892
7893 pub fn move_to_start_of_paragraph(
7894 &mut self,
7895 _: &MoveToStartOfParagraph,
7896 cx: &mut ViewContext<Self>,
7897 ) {
7898 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7899 cx.propagate();
7900 return;
7901 }
7902
7903 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7904 s.move_with(|map, selection| {
7905 selection.collapse_to(
7906 movement::start_of_paragraph(map, selection.head(), 1),
7907 SelectionGoal::None,
7908 )
7909 });
7910 })
7911 }
7912
7913 pub fn move_to_end_of_paragraph(
7914 &mut self,
7915 _: &MoveToEndOfParagraph,
7916 cx: &mut ViewContext<Self>,
7917 ) {
7918 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7919 cx.propagate();
7920 return;
7921 }
7922
7923 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7924 s.move_with(|map, selection| {
7925 selection.collapse_to(
7926 movement::end_of_paragraph(map, selection.head(), 1),
7927 SelectionGoal::None,
7928 )
7929 });
7930 })
7931 }
7932
7933 pub fn select_to_start_of_paragraph(
7934 &mut self,
7935 _: &SelectToStartOfParagraph,
7936 cx: &mut ViewContext<Self>,
7937 ) {
7938 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7939 cx.propagate();
7940 return;
7941 }
7942
7943 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7944 s.move_heads_with(|map, head, _| {
7945 (
7946 movement::start_of_paragraph(map, head, 1),
7947 SelectionGoal::None,
7948 )
7949 });
7950 })
7951 }
7952
7953 pub fn select_to_end_of_paragraph(
7954 &mut self,
7955 _: &SelectToEndOfParagraph,
7956 cx: &mut ViewContext<Self>,
7957 ) {
7958 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7959 cx.propagate();
7960 return;
7961 }
7962
7963 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7964 s.move_heads_with(|map, head, _| {
7965 (
7966 movement::end_of_paragraph(map, head, 1),
7967 SelectionGoal::None,
7968 )
7969 });
7970 })
7971 }
7972
7973 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7974 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7975 cx.propagate();
7976 return;
7977 }
7978
7979 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7980 s.select_ranges(vec![0..0]);
7981 });
7982 }
7983
7984 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7985 let mut selection = self.selections.last::<Point>(cx);
7986 selection.set_head(Point::zero(), SelectionGoal::None);
7987
7988 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7989 s.select(vec![selection]);
7990 });
7991 }
7992
7993 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7994 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7995 cx.propagate();
7996 return;
7997 }
7998
7999 let cursor = self.buffer.read(cx).read(cx).len();
8000 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8001 s.select_ranges(vec![cursor..cursor])
8002 });
8003 }
8004
8005 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
8006 self.nav_history = nav_history;
8007 }
8008
8009 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
8010 self.nav_history.as_ref()
8011 }
8012
8013 fn push_to_nav_history(
8014 &mut self,
8015 cursor_anchor: Anchor,
8016 new_position: Option<Point>,
8017 cx: &mut ViewContext<Self>,
8018 ) {
8019 if let Some(nav_history) = self.nav_history.as_mut() {
8020 let buffer = self.buffer.read(cx).read(cx);
8021 let cursor_position = cursor_anchor.to_point(&buffer);
8022 let scroll_state = self.scroll_manager.anchor();
8023 let scroll_top_row = scroll_state.top_row(&buffer);
8024 drop(buffer);
8025
8026 if let Some(new_position) = new_position {
8027 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
8028 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
8029 return;
8030 }
8031 }
8032
8033 nav_history.push(
8034 Some(NavigationData {
8035 cursor_anchor,
8036 cursor_position,
8037 scroll_anchor: scroll_state,
8038 scroll_top_row,
8039 }),
8040 cx,
8041 );
8042 }
8043 }
8044
8045 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
8046 let buffer = self.buffer.read(cx).snapshot(cx);
8047 let mut selection = self.selections.first::<usize>(cx);
8048 selection.set_head(buffer.len(), SelectionGoal::None);
8049 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8050 s.select(vec![selection]);
8051 });
8052 }
8053
8054 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
8055 let end = self.buffer.read(cx).read(cx).len();
8056 self.change_selections(None, cx, |s| {
8057 s.select_ranges(vec![0..end]);
8058 });
8059 }
8060
8061 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
8062 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8063 let mut selections = self.selections.all::<Point>(cx);
8064 let max_point = display_map.buffer_snapshot.max_point();
8065 for selection in &mut selections {
8066 let rows = selection.spanned_rows(true, &display_map);
8067 selection.start = Point::new(rows.start.0, 0);
8068 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
8069 selection.reversed = false;
8070 }
8071 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8072 s.select(selections);
8073 });
8074 }
8075
8076 pub fn split_selection_into_lines(
8077 &mut self,
8078 _: &SplitSelectionIntoLines,
8079 cx: &mut ViewContext<Self>,
8080 ) {
8081 let mut to_unfold = Vec::new();
8082 let mut new_selection_ranges = Vec::new();
8083 {
8084 let selections = self.selections.all::<Point>(cx);
8085 let buffer = self.buffer.read(cx).read(cx);
8086 for selection in selections {
8087 for row in selection.start.row..selection.end.row {
8088 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
8089 new_selection_ranges.push(cursor..cursor);
8090 }
8091 new_selection_ranges.push(selection.end..selection.end);
8092 to_unfold.push(selection.start..selection.end);
8093 }
8094 }
8095 self.unfold_ranges(to_unfold, true, true, cx);
8096 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8097 s.select_ranges(new_selection_ranges);
8098 });
8099 }
8100
8101 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8102 self.add_selection(true, cx);
8103 }
8104
8105 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8106 self.add_selection(false, cx);
8107 }
8108
8109 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8110 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8111 let mut selections = self.selections.all::<Point>(cx);
8112 let text_layout_details = self.text_layout_details(cx);
8113 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8114 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8115 let range = oldest_selection.display_range(&display_map).sorted();
8116
8117 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8118 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8119 let positions = start_x.min(end_x)..start_x.max(end_x);
8120
8121 selections.clear();
8122 let mut stack = Vec::new();
8123 for row in range.start.row().0..=range.end.row().0 {
8124 if let Some(selection) = self.selections.build_columnar_selection(
8125 &display_map,
8126 DisplayRow(row),
8127 &positions,
8128 oldest_selection.reversed,
8129 &text_layout_details,
8130 ) {
8131 stack.push(selection.id);
8132 selections.push(selection);
8133 }
8134 }
8135
8136 if above {
8137 stack.reverse();
8138 }
8139
8140 AddSelectionsState { above, stack }
8141 });
8142
8143 let last_added_selection = *state.stack.last().unwrap();
8144 let mut new_selections = Vec::new();
8145 if above == state.above {
8146 let end_row = if above {
8147 DisplayRow(0)
8148 } else {
8149 display_map.max_point().row()
8150 };
8151
8152 'outer: for selection in selections {
8153 if selection.id == last_added_selection {
8154 let range = selection.display_range(&display_map).sorted();
8155 debug_assert_eq!(range.start.row(), range.end.row());
8156 let mut row = range.start.row();
8157 let positions =
8158 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8159 px(start)..px(end)
8160 } else {
8161 let start_x =
8162 display_map.x_for_display_point(range.start, &text_layout_details);
8163 let end_x =
8164 display_map.x_for_display_point(range.end, &text_layout_details);
8165 start_x.min(end_x)..start_x.max(end_x)
8166 };
8167
8168 while row != end_row {
8169 if above {
8170 row.0 -= 1;
8171 } else {
8172 row.0 += 1;
8173 }
8174
8175 if let Some(new_selection) = self.selections.build_columnar_selection(
8176 &display_map,
8177 row,
8178 &positions,
8179 selection.reversed,
8180 &text_layout_details,
8181 ) {
8182 state.stack.push(new_selection.id);
8183 if above {
8184 new_selections.push(new_selection);
8185 new_selections.push(selection);
8186 } else {
8187 new_selections.push(selection);
8188 new_selections.push(new_selection);
8189 }
8190
8191 continue 'outer;
8192 }
8193 }
8194 }
8195
8196 new_selections.push(selection);
8197 }
8198 } else {
8199 new_selections = selections;
8200 new_selections.retain(|s| s.id != last_added_selection);
8201 state.stack.pop();
8202 }
8203
8204 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8205 s.select(new_selections);
8206 });
8207 if state.stack.len() > 1 {
8208 self.add_selections_state = Some(state);
8209 }
8210 }
8211
8212 pub fn select_next_match_internal(
8213 &mut self,
8214 display_map: &DisplaySnapshot,
8215 replace_newest: bool,
8216 autoscroll: Option<Autoscroll>,
8217 cx: &mut ViewContext<Self>,
8218 ) -> Result<()> {
8219 fn select_next_match_ranges(
8220 this: &mut Editor,
8221 range: Range<usize>,
8222 replace_newest: bool,
8223 auto_scroll: Option<Autoscroll>,
8224 cx: &mut ViewContext<Editor>,
8225 ) {
8226 this.unfold_ranges([range.clone()], false, true, cx);
8227 this.change_selections(auto_scroll, cx, |s| {
8228 if replace_newest {
8229 s.delete(s.newest_anchor().id);
8230 }
8231 s.insert_range(range.clone());
8232 });
8233 }
8234
8235 let buffer = &display_map.buffer_snapshot;
8236 let mut selections = self.selections.all::<usize>(cx);
8237 if let Some(mut select_next_state) = self.select_next_state.take() {
8238 let query = &select_next_state.query;
8239 if !select_next_state.done {
8240 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8241 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8242 let mut next_selected_range = None;
8243
8244 let bytes_after_last_selection =
8245 buffer.bytes_in_range(last_selection.end..buffer.len());
8246 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8247 let query_matches = query
8248 .stream_find_iter(bytes_after_last_selection)
8249 .map(|result| (last_selection.end, result))
8250 .chain(
8251 query
8252 .stream_find_iter(bytes_before_first_selection)
8253 .map(|result| (0, result)),
8254 );
8255
8256 for (start_offset, query_match) in query_matches {
8257 let query_match = query_match.unwrap(); // can only fail due to I/O
8258 let offset_range =
8259 start_offset + query_match.start()..start_offset + query_match.end();
8260 let display_range = offset_range.start.to_display_point(display_map)
8261 ..offset_range.end.to_display_point(display_map);
8262
8263 if !select_next_state.wordwise
8264 || (!movement::is_inside_word(display_map, display_range.start)
8265 && !movement::is_inside_word(display_map, display_range.end))
8266 {
8267 // TODO: This is n^2, because we might check all the selections
8268 if !selections
8269 .iter()
8270 .any(|selection| selection.range().overlaps(&offset_range))
8271 {
8272 next_selected_range = Some(offset_range);
8273 break;
8274 }
8275 }
8276 }
8277
8278 if let Some(next_selected_range) = next_selected_range {
8279 select_next_match_ranges(
8280 self,
8281 next_selected_range,
8282 replace_newest,
8283 autoscroll,
8284 cx,
8285 );
8286 } else {
8287 select_next_state.done = true;
8288 }
8289 }
8290
8291 self.select_next_state = Some(select_next_state);
8292 } else {
8293 let mut only_carets = true;
8294 let mut same_text_selected = true;
8295 let mut selected_text = None;
8296
8297 let mut selections_iter = selections.iter().peekable();
8298 while let Some(selection) = selections_iter.next() {
8299 if selection.start != selection.end {
8300 only_carets = false;
8301 }
8302
8303 if same_text_selected {
8304 if selected_text.is_none() {
8305 selected_text =
8306 Some(buffer.text_for_range(selection.range()).collect::<String>());
8307 }
8308
8309 if let Some(next_selection) = selections_iter.peek() {
8310 if next_selection.range().len() == selection.range().len() {
8311 let next_selected_text = buffer
8312 .text_for_range(next_selection.range())
8313 .collect::<String>();
8314 if Some(next_selected_text) != selected_text {
8315 same_text_selected = false;
8316 selected_text = None;
8317 }
8318 } else {
8319 same_text_selected = false;
8320 selected_text = None;
8321 }
8322 }
8323 }
8324 }
8325
8326 if only_carets {
8327 for selection in &mut selections {
8328 let word_range = movement::surrounding_word(
8329 display_map,
8330 selection.start.to_display_point(display_map),
8331 );
8332 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8333 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8334 selection.goal = SelectionGoal::None;
8335 selection.reversed = false;
8336 select_next_match_ranges(
8337 self,
8338 selection.start..selection.end,
8339 replace_newest,
8340 autoscroll,
8341 cx,
8342 );
8343 }
8344
8345 if selections.len() == 1 {
8346 let selection = selections
8347 .last()
8348 .expect("ensured that there's only one selection");
8349 let query = buffer
8350 .text_for_range(selection.start..selection.end)
8351 .collect::<String>();
8352 let is_empty = query.is_empty();
8353 let select_state = SelectNextState {
8354 query: AhoCorasick::new(&[query])?,
8355 wordwise: true,
8356 done: is_empty,
8357 };
8358 self.select_next_state = Some(select_state);
8359 } else {
8360 self.select_next_state = None;
8361 }
8362 } else if let Some(selected_text) = selected_text {
8363 self.select_next_state = Some(SelectNextState {
8364 query: AhoCorasick::new(&[selected_text])?,
8365 wordwise: false,
8366 done: false,
8367 });
8368 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8369 }
8370 }
8371 Ok(())
8372 }
8373
8374 pub fn select_all_matches(
8375 &mut self,
8376 _action: &SelectAllMatches,
8377 cx: &mut ViewContext<Self>,
8378 ) -> Result<()> {
8379 self.push_to_selection_history();
8380 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8381
8382 self.select_next_match_internal(&display_map, false, None, cx)?;
8383 let Some(select_next_state) = self.select_next_state.as_mut() else {
8384 return Ok(());
8385 };
8386 if select_next_state.done {
8387 return Ok(());
8388 }
8389
8390 let mut new_selections = self.selections.all::<usize>(cx);
8391
8392 let buffer = &display_map.buffer_snapshot;
8393 let query_matches = select_next_state
8394 .query
8395 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8396
8397 for query_match in query_matches {
8398 let query_match = query_match.unwrap(); // can only fail due to I/O
8399 let offset_range = query_match.start()..query_match.end();
8400 let display_range = offset_range.start.to_display_point(&display_map)
8401 ..offset_range.end.to_display_point(&display_map);
8402
8403 if !select_next_state.wordwise
8404 || (!movement::is_inside_word(&display_map, display_range.start)
8405 && !movement::is_inside_word(&display_map, display_range.end))
8406 {
8407 self.selections.change_with(cx, |selections| {
8408 new_selections.push(Selection {
8409 id: selections.new_selection_id(),
8410 start: offset_range.start,
8411 end: offset_range.end,
8412 reversed: false,
8413 goal: SelectionGoal::None,
8414 });
8415 });
8416 }
8417 }
8418
8419 new_selections.sort_by_key(|selection| selection.start);
8420 let mut ix = 0;
8421 while ix + 1 < new_selections.len() {
8422 let current_selection = &new_selections[ix];
8423 let next_selection = &new_selections[ix + 1];
8424 if current_selection.range().overlaps(&next_selection.range()) {
8425 if current_selection.id < next_selection.id {
8426 new_selections.remove(ix + 1);
8427 } else {
8428 new_selections.remove(ix);
8429 }
8430 } else {
8431 ix += 1;
8432 }
8433 }
8434
8435 select_next_state.done = true;
8436 self.unfold_ranges(
8437 new_selections.iter().map(|selection| selection.range()),
8438 false,
8439 false,
8440 cx,
8441 );
8442 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8443 selections.select(new_selections)
8444 });
8445
8446 Ok(())
8447 }
8448
8449 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8450 self.push_to_selection_history();
8451 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8452 self.select_next_match_internal(
8453 &display_map,
8454 action.replace_newest,
8455 Some(Autoscroll::newest()),
8456 cx,
8457 )?;
8458 Ok(())
8459 }
8460
8461 pub fn select_previous(
8462 &mut self,
8463 action: &SelectPrevious,
8464 cx: &mut ViewContext<Self>,
8465 ) -> Result<()> {
8466 self.push_to_selection_history();
8467 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8468 let buffer = &display_map.buffer_snapshot;
8469 let mut selections = self.selections.all::<usize>(cx);
8470 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8471 let query = &select_prev_state.query;
8472 if !select_prev_state.done {
8473 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8474 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8475 let mut next_selected_range = None;
8476 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8477 let bytes_before_last_selection =
8478 buffer.reversed_bytes_in_range(0..last_selection.start);
8479 let bytes_after_first_selection =
8480 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8481 let query_matches = query
8482 .stream_find_iter(bytes_before_last_selection)
8483 .map(|result| (last_selection.start, result))
8484 .chain(
8485 query
8486 .stream_find_iter(bytes_after_first_selection)
8487 .map(|result| (buffer.len(), result)),
8488 );
8489 for (end_offset, query_match) in query_matches {
8490 let query_match = query_match.unwrap(); // can only fail due to I/O
8491 let offset_range =
8492 end_offset - query_match.end()..end_offset - query_match.start();
8493 let display_range = offset_range.start.to_display_point(&display_map)
8494 ..offset_range.end.to_display_point(&display_map);
8495
8496 if !select_prev_state.wordwise
8497 || (!movement::is_inside_word(&display_map, display_range.start)
8498 && !movement::is_inside_word(&display_map, display_range.end))
8499 {
8500 next_selected_range = Some(offset_range);
8501 break;
8502 }
8503 }
8504
8505 if let Some(next_selected_range) = next_selected_range {
8506 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8507 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8508 if action.replace_newest {
8509 s.delete(s.newest_anchor().id);
8510 }
8511 s.insert_range(next_selected_range);
8512 });
8513 } else {
8514 select_prev_state.done = true;
8515 }
8516 }
8517
8518 self.select_prev_state = Some(select_prev_state);
8519 } else {
8520 let mut only_carets = true;
8521 let mut same_text_selected = true;
8522 let mut selected_text = None;
8523
8524 let mut selections_iter = selections.iter().peekable();
8525 while let Some(selection) = selections_iter.next() {
8526 if selection.start != selection.end {
8527 only_carets = false;
8528 }
8529
8530 if same_text_selected {
8531 if selected_text.is_none() {
8532 selected_text =
8533 Some(buffer.text_for_range(selection.range()).collect::<String>());
8534 }
8535
8536 if let Some(next_selection) = selections_iter.peek() {
8537 if next_selection.range().len() == selection.range().len() {
8538 let next_selected_text = buffer
8539 .text_for_range(next_selection.range())
8540 .collect::<String>();
8541 if Some(next_selected_text) != selected_text {
8542 same_text_selected = false;
8543 selected_text = None;
8544 }
8545 } else {
8546 same_text_selected = false;
8547 selected_text = None;
8548 }
8549 }
8550 }
8551 }
8552
8553 if only_carets {
8554 for selection in &mut selections {
8555 let word_range = movement::surrounding_word(
8556 &display_map,
8557 selection.start.to_display_point(&display_map),
8558 );
8559 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8560 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8561 selection.goal = SelectionGoal::None;
8562 selection.reversed = false;
8563 }
8564 if selections.len() == 1 {
8565 let selection = selections
8566 .last()
8567 .expect("ensured that there's only one selection");
8568 let query = buffer
8569 .text_for_range(selection.start..selection.end)
8570 .collect::<String>();
8571 let is_empty = query.is_empty();
8572 let select_state = SelectNextState {
8573 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8574 wordwise: true,
8575 done: is_empty,
8576 };
8577 self.select_prev_state = Some(select_state);
8578 } else {
8579 self.select_prev_state = None;
8580 }
8581
8582 self.unfold_ranges(
8583 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8584 false,
8585 true,
8586 cx,
8587 );
8588 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8589 s.select(selections);
8590 });
8591 } else if let Some(selected_text) = selected_text {
8592 self.select_prev_state = Some(SelectNextState {
8593 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8594 wordwise: false,
8595 done: false,
8596 });
8597 self.select_previous(action, cx)?;
8598 }
8599 }
8600 Ok(())
8601 }
8602
8603 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8604 let text_layout_details = &self.text_layout_details(cx);
8605 self.transact(cx, |this, cx| {
8606 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8607 let mut edits = Vec::new();
8608 let mut selection_edit_ranges = Vec::new();
8609 let mut last_toggled_row = None;
8610 let snapshot = this.buffer.read(cx).read(cx);
8611 let empty_str: Arc<str> = Arc::default();
8612 let mut suffixes_inserted = Vec::new();
8613
8614 fn comment_prefix_range(
8615 snapshot: &MultiBufferSnapshot,
8616 row: MultiBufferRow,
8617 comment_prefix: &str,
8618 comment_prefix_whitespace: &str,
8619 ) -> Range<Point> {
8620 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8621
8622 let mut line_bytes = snapshot
8623 .bytes_in_range(start..snapshot.max_point())
8624 .flatten()
8625 .copied();
8626
8627 // If this line currently begins with the line comment prefix, then record
8628 // the range containing the prefix.
8629 if line_bytes
8630 .by_ref()
8631 .take(comment_prefix.len())
8632 .eq(comment_prefix.bytes())
8633 {
8634 // Include any whitespace that matches the comment prefix.
8635 let matching_whitespace_len = line_bytes
8636 .zip(comment_prefix_whitespace.bytes())
8637 .take_while(|(a, b)| a == b)
8638 .count() as u32;
8639 let end = Point::new(
8640 start.row,
8641 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8642 );
8643 start..end
8644 } else {
8645 start..start
8646 }
8647 }
8648
8649 fn comment_suffix_range(
8650 snapshot: &MultiBufferSnapshot,
8651 row: MultiBufferRow,
8652 comment_suffix: &str,
8653 comment_suffix_has_leading_space: bool,
8654 ) -> Range<Point> {
8655 let end = Point::new(row.0, snapshot.line_len(row));
8656 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8657
8658 let mut line_end_bytes = snapshot
8659 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8660 .flatten()
8661 .copied();
8662
8663 let leading_space_len = if suffix_start_column > 0
8664 && line_end_bytes.next() == Some(b' ')
8665 && comment_suffix_has_leading_space
8666 {
8667 1
8668 } else {
8669 0
8670 };
8671
8672 // If this line currently begins with the line comment prefix, then record
8673 // the range containing the prefix.
8674 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8675 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8676 start..end
8677 } else {
8678 end..end
8679 }
8680 }
8681
8682 // TODO: Handle selections that cross excerpts
8683 for selection in &mut selections {
8684 let start_column = snapshot
8685 .indent_size_for_line(MultiBufferRow(selection.start.row))
8686 .len;
8687 let language = if let Some(language) =
8688 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8689 {
8690 language
8691 } else {
8692 continue;
8693 };
8694
8695 selection_edit_ranges.clear();
8696
8697 // If multiple selections contain a given row, avoid processing that
8698 // row more than once.
8699 let mut start_row = MultiBufferRow(selection.start.row);
8700 if last_toggled_row == Some(start_row) {
8701 start_row = start_row.next_row();
8702 }
8703 let end_row =
8704 if selection.end.row > selection.start.row && selection.end.column == 0 {
8705 MultiBufferRow(selection.end.row - 1)
8706 } else {
8707 MultiBufferRow(selection.end.row)
8708 };
8709 last_toggled_row = Some(end_row);
8710
8711 if start_row > end_row {
8712 continue;
8713 }
8714
8715 // If the language has line comments, toggle those.
8716 let full_comment_prefixes = language.line_comment_prefixes();
8717 if !full_comment_prefixes.is_empty() {
8718 let first_prefix = full_comment_prefixes
8719 .first()
8720 .expect("prefixes is non-empty");
8721 let prefix_trimmed_lengths = full_comment_prefixes
8722 .iter()
8723 .map(|p| p.trim_end_matches(' ').len())
8724 .collect::<SmallVec<[usize; 4]>>();
8725
8726 let mut all_selection_lines_are_comments = true;
8727
8728 for row in start_row.0..=end_row.0 {
8729 let row = MultiBufferRow(row);
8730 if start_row < end_row && snapshot.is_line_blank(row) {
8731 continue;
8732 }
8733
8734 let prefix_range = full_comment_prefixes
8735 .iter()
8736 .zip(prefix_trimmed_lengths.iter().copied())
8737 .map(|(prefix, trimmed_prefix_len)| {
8738 comment_prefix_range(
8739 snapshot.deref(),
8740 row,
8741 &prefix[..trimmed_prefix_len],
8742 &prefix[trimmed_prefix_len..],
8743 )
8744 })
8745 .max_by_key(|range| range.end.column - range.start.column)
8746 .expect("prefixes is non-empty");
8747
8748 if prefix_range.is_empty() {
8749 all_selection_lines_are_comments = false;
8750 }
8751
8752 selection_edit_ranges.push(prefix_range);
8753 }
8754
8755 if all_selection_lines_are_comments {
8756 edits.extend(
8757 selection_edit_ranges
8758 .iter()
8759 .cloned()
8760 .map(|range| (range, empty_str.clone())),
8761 );
8762 } else {
8763 let min_column = selection_edit_ranges
8764 .iter()
8765 .map(|range| range.start.column)
8766 .min()
8767 .unwrap_or(0);
8768 edits.extend(selection_edit_ranges.iter().map(|range| {
8769 let position = Point::new(range.start.row, min_column);
8770 (position..position, first_prefix.clone())
8771 }));
8772 }
8773 } else if let Some((full_comment_prefix, comment_suffix)) =
8774 language.block_comment_delimiters()
8775 {
8776 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8777 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8778 let prefix_range = comment_prefix_range(
8779 snapshot.deref(),
8780 start_row,
8781 comment_prefix,
8782 comment_prefix_whitespace,
8783 );
8784 let suffix_range = comment_suffix_range(
8785 snapshot.deref(),
8786 end_row,
8787 comment_suffix.trim_start_matches(' '),
8788 comment_suffix.starts_with(' '),
8789 );
8790
8791 if prefix_range.is_empty() || suffix_range.is_empty() {
8792 edits.push((
8793 prefix_range.start..prefix_range.start,
8794 full_comment_prefix.clone(),
8795 ));
8796 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8797 suffixes_inserted.push((end_row, comment_suffix.len()));
8798 } else {
8799 edits.push((prefix_range, empty_str.clone()));
8800 edits.push((suffix_range, empty_str.clone()));
8801 }
8802 } else {
8803 continue;
8804 }
8805 }
8806
8807 drop(snapshot);
8808 this.buffer.update(cx, |buffer, cx| {
8809 buffer.edit(edits, None, cx);
8810 });
8811
8812 // Adjust selections so that they end before any comment suffixes that
8813 // were inserted.
8814 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8815 let mut selections = this.selections.all::<Point>(cx);
8816 let snapshot = this.buffer.read(cx).read(cx);
8817 for selection in &mut selections {
8818 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8819 match row.cmp(&MultiBufferRow(selection.end.row)) {
8820 Ordering::Less => {
8821 suffixes_inserted.next();
8822 continue;
8823 }
8824 Ordering::Greater => break,
8825 Ordering::Equal => {
8826 if selection.end.column == snapshot.line_len(row) {
8827 if selection.is_empty() {
8828 selection.start.column -= suffix_len as u32;
8829 }
8830 selection.end.column -= suffix_len as u32;
8831 }
8832 break;
8833 }
8834 }
8835 }
8836 }
8837
8838 drop(snapshot);
8839 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8840
8841 let selections = this.selections.all::<Point>(cx);
8842 let selections_on_single_row = selections.windows(2).all(|selections| {
8843 selections[0].start.row == selections[1].start.row
8844 && selections[0].end.row == selections[1].end.row
8845 && selections[0].start.row == selections[0].end.row
8846 });
8847 let selections_selecting = selections
8848 .iter()
8849 .any(|selection| selection.start != selection.end);
8850 let advance_downwards = action.advance_downwards
8851 && selections_on_single_row
8852 && !selections_selecting
8853 && !matches!(this.mode, EditorMode::SingleLine { .. });
8854
8855 if advance_downwards {
8856 let snapshot = this.buffer.read(cx).snapshot(cx);
8857
8858 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8859 s.move_cursors_with(|display_snapshot, display_point, _| {
8860 let mut point = display_point.to_point(display_snapshot);
8861 point.row += 1;
8862 point = snapshot.clip_point(point, Bias::Left);
8863 let display_point = point.to_display_point(display_snapshot);
8864 let goal = SelectionGoal::HorizontalPosition(
8865 display_snapshot
8866 .x_for_display_point(display_point, text_layout_details)
8867 .into(),
8868 );
8869 (display_point, goal)
8870 })
8871 });
8872 }
8873 });
8874 }
8875
8876 pub fn select_enclosing_symbol(
8877 &mut self,
8878 _: &SelectEnclosingSymbol,
8879 cx: &mut ViewContext<Self>,
8880 ) {
8881 let buffer = self.buffer.read(cx).snapshot(cx);
8882 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8883
8884 fn update_selection(
8885 selection: &Selection<usize>,
8886 buffer_snap: &MultiBufferSnapshot,
8887 ) -> Option<Selection<usize>> {
8888 let cursor = selection.head();
8889 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8890 for symbol in symbols.iter().rev() {
8891 let start = symbol.range.start.to_offset(buffer_snap);
8892 let end = symbol.range.end.to_offset(buffer_snap);
8893 let new_range = start..end;
8894 if start < selection.start || end > selection.end {
8895 return Some(Selection {
8896 id: selection.id,
8897 start: new_range.start,
8898 end: new_range.end,
8899 goal: SelectionGoal::None,
8900 reversed: selection.reversed,
8901 });
8902 }
8903 }
8904 None
8905 }
8906
8907 let mut selected_larger_symbol = false;
8908 let new_selections = old_selections
8909 .iter()
8910 .map(|selection| match update_selection(selection, &buffer) {
8911 Some(new_selection) => {
8912 if new_selection.range() != selection.range() {
8913 selected_larger_symbol = true;
8914 }
8915 new_selection
8916 }
8917 None => selection.clone(),
8918 })
8919 .collect::<Vec<_>>();
8920
8921 if selected_larger_symbol {
8922 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8923 s.select(new_selections);
8924 });
8925 }
8926 }
8927
8928 pub fn select_larger_syntax_node(
8929 &mut self,
8930 _: &SelectLargerSyntaxNode,
8931 cx: &mut ViewContext<Self>,
8932 ) {
8933 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8934 let buffer = self.buffer.read(cx).snapshot(cx);
8935 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8936
8937 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8938 let mut selected_larger_node = false;
8939 let new_selections = old_selections
8940 .iter()
8941 .map(|selection| {
8942 let old_range = selection.start..selection.end;
8943 let mut new_range = old_range.clone();
8944 while let Some(containing_range) =
8945 buffer.range_for_syntax_ancestor(new_range.clone())
8946 {
8947 new_range = containing_range;
8948 if !display_map.intersects_fold(new_range.start)
8949 && !display_map.intersects_fold(new_range.end)
8950 {
8951 break;
8952 }
8953 }
8954
8955 selected_larger_node |= new_range != old_range;
8956 Selection {
8957 id: selection.id,
8958 start: new_range.start,
8959 end: new_range.end,
8960 goal: SelectionGoal::None,
8961 reversed: selection.reversed,
8962 }
8963 })
8964 .collect::<Vec<_>>();
8965
8966 if selected_larger_node {
8967 stack.push(old_selections);
8968 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8969 s.select(new_selections);
8970 });
8971 }
8972 self.select_larger_syntax_node_stack = stack;
8973 }
8974
8975 pub fn select_smaller_syntax_node(
8976 &mut self,
8977 _: &SelectSmallerSyntaxNode,
8978 cx: &mut ViewContext<Self>,
8979 ) {
8980 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8981 if let Some(selections) = stack.pop() {
8982 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8983 s.select(selections.to_vec());
8984 });
8985 }
8986 self.select_larger_syntax_node_stack = stack;
8987 }
8988
8989 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8990 if !EditorSettings::get_global(cx).gutter.runnables {
8991 self.clear_tasks();
8992 return Task::ready(());
8993 }
8994 let project = self.project.clone();
8995 cx.spawn(|this, mut cx| async move {
8996 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8997 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8998 }) else {
8999 return;
9000 };
9001
9002 let Some(project) = project else {
9003 return;
9004 };
9005
9006 let hide_runnables = project
9007 .update(&mut cx, |project, cx| {
9008 // Do not display any test indicators in non-dev server remote projects.
9009 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
9010 })
9011 .unwrap_or(true);
9012 if hide_runnables {
9013 return;
9014 }
9015 let new_rows =
9016 cx.background_executor()
9017 .spawn({
9018 let snapshot = display_snapshot.clone();
9019 async move {
9020 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
9021 }
9022 })
9023 .await;
9024 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
9025
9026 this.update(&mut cx, |this, _| {
9027 this.clear_tasks();
9028 for (key, value) in rows {
9029 this.insert_tasks(key, value);
9030 }
9031 })
9032 .ok();
9033 })
9034 }
9035 fn fetch_runnable_ranges(
9036 snapshot: &DisplaySnapshot,
9037 range: Range<Anchor>,
9038 ) -> Vec<language::RunnableRange> {
9039 snapshot.buffer_snapshot.runnable_ranges(range).collect()
9040 }
9041
9042 fn runnable_rows(
9043 project: Model<Project>,
9044 snapshot: DisplaySnapshot,
9045 runnable_ranges: Vec<RunnableRange>,
9046 mut cx: AsyncWindowContext,
9047 ) -> Vec<((BufferId, u32), RunnableTasks)> {
9048 runnable_ranges
9049 .into_iter()
9050 .filter_map(|mut runnable| {
9051 let tasks = cx
9052 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
9053 .ok()?;
9054 if tasks.is_empty() {
9055 return None;
9056 }
9057
9058 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
9059
9060 let row = snapshot
9061 .buffer_snapshot
9062 .buffer_line_for_row(MultiBufferRow(point.row))?
9063 .1
9064 .start
9065 .row;
9066
9067 let context_range =
9068 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
9069 Some((
9070 (runnable.buffer_id, row),
9071 RunnableTasks {
9072 templates: tasks,
9073 offset: MultiBufferOffset(runnable.run_range.start),
9074 context_range,
9075 column: point.column,
9076 extra_variables: runnable.extra_captures,
9077 },
9078 ))
9079 })
9080 .collect()
9081 }
9082
9083 fn templates_with_tags(
9084 project: &Model<Project>,
9085 runnable: &mut Runnable,
9086 cx: &WindowContext<'_>,
9087 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
9088 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
9089 let (worktree_id, file) = project
9090 .buffer_for_id(runnable.buffer, cx)
9091 .and_then(|buffer| buffer.read(cx).file())
9092 .map(|file| (file.worktree_id(cx), file.clone()))
9093 .unzip();
9094
9095 (project.task_inventory().clone(), worktree_id, file)
9096 });
9097
9098 let inventory = inventory.read(cx);
9099 let tags = mem::take(&mut runnable.tags);
9100 let mut tags: Vec<_> = tags
9101 .into_iter()
9102 .flat_map(|tag| {
9103 let tag = tag.0.clone();
9104 inventory
9105 .list_tasks(
9106 file.clone(),
9107 Some(runnable.language.clone()),
9108 worktree_id,
9109 cx,
9110 )
9111 .into_iter()
9112 .filter(move |(_, template)| {
9113 template.tags.iter().any(|source_tag| source_tag == &tag)
9114 })
9115 })
9116 .sorted_by_key(|(kind, _)| kind.to_owned())
9117 .collect();
9118 if let Some((leading_tag_source, _)) = tags.first() {
9119 // Strongest source wins; if we have worktree tag binding, prefer that to
9120 // global and language bindings;
9121 // if we have a global binding, prefer that to language binding.
9122 let first_mismatch = tags
9123 .iter()
9124 .position(|(tag_source, _)| tag_source != leading_tag_source);
9125 if let Some(index) = first_mismatch {
9126 tags.truncate(index);
9127 }
9128 }
9129
9130 tags
9131 }
9132
9133 pub fn move_to_enclosing_bracket(
9134 &mut self,
9135 _: &MoveToEnclosingBracket,
9136 cx: &mut ViewContext<Self>,
9137 ) {
9138 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9139 s.move_offsets_with(|snapshot, selection| {
9140 let Some(enclosing_bracket_ranges) =
9141 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9142 else {
9143 return;
9144 };
9145
9146 let mut best_length = usize::MAX;
9147 let mut best_inside = false;
9148 let mut best_in_bracket_range = false;
9149 let mut best_destination = None;
9150 for (open, close) in enclosing_bracket_ranges {
9151 let close = close.to_inclusive();
9152 let length = close.end() - open.start;
9153 let inside = selection.start >= open.end && selection.end <= *close.start();
9154 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9155 || close.contains(&selection.head());
9156
9157 // If best is next to a bracket and current isn't, skip
9158 if !in_bracket_range && best_in_bracket_range {
9159 continue;
9160 }
9161
9162 // Prefer smaller lengths unless best is inside and current isn't
9163 if length > best_length && (best_inside || !inside) {
9164 continue;
9165 }
9166
9167 best_length = length;
9168 best_inside = inside;
9169 best_in_bracket_range = in_bracket_range;
9170 best_destination = Some(
9171 if close.contains(&selection.start) && close.contains(&selection.end) {
9172 if inside {
9173 open.end
9174 } else {
9175 open.start
9176 }
9177 } else if inside {
9178 *close.start()
9179 } else {
9180 *close.end()
9181 },
9182 );
9183 }
9184
9185 if let Some(destination) = best_destination {
9186 selection.collapse_to(destination, SelectionGoal::None);
9187 }
9188 })
9189 });
9190 }
9191
9192 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9193 self.end_selection(cx);
9194 self.selection_history.mode = SelectionHistoryMode::Undoing;
9195 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9196 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9197 self.select_next_state = entry.select_next_state;
9198 self.select_prev_state = entry.select_prev_state;
9199 self.add_selections_state = entry.add_selections_state;
9200 self.request_autoscroll(Autoscroll::newest(), cx);
9201 }
9202 self.selection_history.mode = SelectionHistoryMode::Normal;
9203 }
9204
9205 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9206 self.end_selection(cx);
9207 self.selection_history.mode = SelectionHistoryMode::Redoing;
9208 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9209 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9210 self.select_next_state = entry.select_next_state;
9211 self.select_prev_state = entry.select_prev_state;
9212 self.add_selections_state = entry.add_selections_state;
9213 self.request_autoscroll(Autoscroll::newest(), cx);
9214 }
9215 self.selection_history.mode = SelectionHistoryMode::Normal;
9216 }
9217
9218 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9219 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9220 }
9221
9222 pub fn expand_excerpts_down(
9223 &mut self,
9224 action: &ExpandExcerptsDown,
9225 cx: &mut ViewContext<Self>,
9226 ) {
9227 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9228 }
9229
9230 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9231 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9232 }
9233
9234 pub fn expand_excerpts_for_direction(
9235 &mut self,
9236 lines: u32,
9237 direction: ExpandExcerptDirection,
9238 cx: &mut ViewContext<Self>,
9239 ) {
9240 let selections = self.selections.disjoint_anchors();
9241
9242 let lines = if lines == 0 {
9243 EditorSettings::get_global(cx).expand_excerpt_lines
9244 } else {
9245 lines
9246 };
9247
9248 self.buffer.update(cx, |buffer, cx| {
9249 buffer.expand_excerpts(
9250 selections
9251 .iter()
9252 .map(|selection| selection.head().excerpt_id)
9253 .dedup(),
9254 lines,
9255 direction,
9256 cx,
9257 )
9258 })
9259 }
9260
9261 pub fn expand_excerpt(
9262 &mut self,
9263 excerpt: ExcerptId,
9264 direction: ExpandExcerptDirection,
9265 cx: &mut ViewContext<Self>,
9266 ) {
9267 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9268 self.buffer.update(cx, |buffer, cx| {
9269 buffer.expand_excerpts([excerpt], lines, direction, cx)
9270 })
9271 }
9272
9273 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9274 self.go_to_diagnostic_impl(Direction::Next, cx)
9275 }
9276
9277 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9278 self.go_to_diagnostic_impl(Direction::Prev, cx)
9279 }
9280
9281 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9282 let buffer = self.buffer.read(cx).snapshot(cx);
9283 let selection = self.selections.newest::<usize>(cx);
9284
9285 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9286 if direction == Direction::Next {
9287 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9288 let (group_id, jump_to) = popover.activation_info();
9289 if self.activate_diagnostics(group_id, cx) {
9290 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9291 let mut new_selection = s.newest_anchor().clone();
9292 new_selection.collapse_to(jump_to, SelectionGoal::None);
9293 s.select_anchors(vec![new_selection.clone()]);
9294 });
9295 }
9296 return;
9297 }
9298 }
9299
9300 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9301 active_diagnostics
9302 .primary_range
9303 .to_offset(&buffer)
9304 .to_inclusive()
9305 });
9306 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9307 if active_primary_range.contains(&selection.head()) {
9308 *active_primary_range.start()
9309 } else {
9310 selection.head()
9311 }
9312 } else {
9313 selection.head()
9314 };
9315 let snapshot = self.snapshot(cx);
9316 loop {
9317 let diagnostics = if direction == Direction::Prev {
9318 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9319 } else {
9320 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9321 }
9322 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9323 let group = diagnostics
9324 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9325 // be sorted in a stable way
9326 // skip until we are at current active diagnostic, if it exists
9327 .skip_while(|entry| {
9328 (match direction {
9329 Direction::Prev => entry.range.start >= search_start,
9330 Direction::Next => entry.range.start <= search_start,
9331 }) && self
9332 .active_diagnostics
9333 .as_ref()
9334 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9335 })
9336 .find_map(|entry| {
9337 if entry.diagnostic.is_primary
9338 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9339 && !entry.range.is_empty()
9340 // if we match with the active diagnostic, skip it
9341 && Some(entry.diagnostic.group_id)
9342 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9343 {
9344 Some((entry.range, entry.diagnostic.group_id))
9345 } else {
9346 None
9347 }
9348 });
9349
9350 if let Some((primary_range, group_id)) = group {
9351 if self.activate_diagnostics(group_id, cx) {
9352 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9353 s.select(vec![Selection {
9354 id: selection.id,
9355 start: primary_range.start,
9356 end: primary_range.start,
9357 reversed: false,
9358 goal: SelectionGoal::None,
9359 }]);
9360 });
9361 }
9362 break;
9363 } else {
9364 // Cycle around to the start of the buffer, potentially moving back to the start of
9365 // the currently active diagnostic.
9366 active_primary_range.take();
9367 if direction == Direction::Prev {
9368 if search_start == buffer.len() {
9369 break;
9370 } else {
9371 search_start = buffer.len();
9372 }
9373 } else if search_start == 0 {
9374 break;
9375 } else {
9376 search_start = 0;
9377 }
9378 }
9379 }
9380 }
9381
9382 fn go_to_next_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9383 let snapshot = self
9384 .display_map
9385 .update(cx, |display_map, cx| display_map.snapshot(cx));
9386 let selection = self.selections.newest::<Point>(cx);
9387 self.go_to_hunk_after_position(&snapshot, selection.head(), cx);
9388 }
9389
9390 fn go_to_hunk_after_position(
9391 &mut self,
9392 snapshot: &DisplaySnapshot,
9393 position: Point,
9394 cx: &mut ViewContext<'_, Editor>,
9395 ) -> Option<MultiBufferDiffHunk> {
9396 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9397 snapshot,
9398 position,
9399 false,
9400 snapshot
9401 .buffer_snapshot
9402 .git_diff_hunks_in_range(MultiBufferRow(position.row + 1)..MultiBufferRow::MAX),
9403 cx,
9404 ) {
9405 return Some(hunk);
9406 }
9407
9408 let wrapped_point = Point::zero();
9409 self.go_to_next_hunk_in_direction(
9410 snapshot,
9411 wrapped_point,
9412 true,
9413 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9414 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9415 ),
9416 cx,
9417 )
9418 }
9419
9420 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9421 let snapshot = self
9422 .display_map
9423 .update(cx, |display_map, cx| display_map.snapshot(cx));
9424 let selection = self.selections.newest::<Point>(cx);
9425
9426 self.go_to_hunk_before_position(&snapshot, selection.head(), cx);
9427 }
9428
9429 fn go_to_hunk_before_position(
9430 &mut self,
9431 snapshot: &DisplaySnapshot,
9432 position: Point,
9433 cx: &mut ViewContext<'_, Editor>,
9434 ) -> Option<MultiBufferDiffHunk> {
9435 if let Some(hunk) = self.go_to_next_hunk_in_direction(
9436 snapshot,
9437 position,
9438 false,
9439 snapshot
9440 .buffer_snapshot
9441 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(position.row)),
9442 cx,
9443 ) {
9444 return Some(hunk);
9445 }
9446
9447 let wrapped_point = snapshot.buffer_snapshot.max_point();
9448 self.go_to_next_hunk_in_direction(
9449 snapshot,
9450 wrapped_point,
9451 true,
9452 snapshot
9453 .buffer_snapshot
9454 .git_diff_hunks_in_range_rev(MultiBufferRow(0)..MultiBufferRow(wrapped_point.row)),
9455 cx,
9456 )
9457 }
9458
9459 fn go_to_next_hunk_in_direction(
9460 &mut self,
9461 snapshot: &DisplaySnapshot,
9462 initial_point: Point,
9463 is_wrapped: bool,
9464 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9465 cx: &mut ViewContext<Editor>,
9466 ) -> Option<MultiBufferDiffHunk> {
9467 let display_point = initial_point.to_display_point(snapshot);
9468 let mut hunks = hunks
9469 .map(|hunk| (diff_hunk_to_display(&hunk, snapshot), hunk))
9470 .filter(|(display_hunk, _)| {
9471 is_wrapped || !display_hunk.contains_display_row(display_point.row())
9472 })
9473 .dedup();
9474
9475 if let Some((display_hunk, hunk)) = hunks.next() {
9476 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9477 let row = display_hunk.start_display_row();
9478 let point = DisplayPoint::new(row, 0);
9479 s.select_display_ranges([point..point]);
9480 });
9481
9482 Some(hunk)
9483 } else {
9484 None
9485 }
9486 }
9487
9488 pub fn go_to_definition(
9489 &mut self,
9490 _: &GoToDefinition,
9491 cx: &mut ViewContext<Self>,
9492 ) -> Task<Result<Navigated>> {
9493 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9494 cx.spawn(|editor, mut cx| async move {
9495 if definition.await? == Navigated::Yes {
9496 return Ok(Navigated::Yes);
9497 }
9498 match editor.update(&mut cx, |editor, cx| {
9499 editor.find_all_references(&FindAllReferences, cx)
9500 })? {
9501 Some(references) => references.await,
9502 None => Ok(Navigated::No),
9503 }
9504 })
9505 }
9506
9507 pub fn go_to_declaration(
9508 &mut self,
9509 _: &GoToDeclaration,
9510 cx: &mut ViewContext<Self>,
9511 ) -> Task<Result<Navigated>> {
9512 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9513 }
9514
9515 pub fn go_to_declaration_split(
9516 &mut self,
9517 _: &GoToDeclaration,
9518 cx: &mut ViewContext<Self>,
9519 ) -> Task<Result<Navigated>> {
9520 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9521 }
9522
9523 pub fn go_to_implementation(
9524 &mut self,
9525 _: &GoToImplementation,
9526 cx: &mut ViewContext<Self>,
9527 ) -> Task<Result<Navigated>> {
9528 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9529 }
9530
9531 pub fn go_to_implementation_split(
9532 &mut self,
9533 _: &GoToImplementationSplit,
9534 cx: &mut ViewContext<Self>,
9535 ) -> Task<Result<Navigated>> {
9536 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9537 }
9538
9539 pub fn go_to_type_definition(
9540 &mut self,
9541 _: &GoToTypeDefinition,
9542 cx: &mut ViewContext<Self>,
9543 ) -> Task<Result<Navigated>> {
9544 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9545 }
9546
9547 pub fn go_to_definition_split(
9548 &mut self,
9549 _: &GoToDefinitionSplit,
9550 cx: &mut ViewContext<Self>,
9551 ) -> Task<Result<Navigated>> {
9552 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9553 }
9554
9555 pub fn go_to_type_definition_split(
9556 &mut self,
9557 _: &GoToTypeDefinitionSplit,
9558 cx: &mut ViewContext<Self>,
9559 ) -> Task<Result<Navigated>> {
9560 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9561 }
9562
9563 fn go_to_definition_of_kind(
9564 &mut self,
9565 kind: GotoDefinitionKind,
9566 split: bool,
9567 cx: &mut ViewContext<Self>,
9568 ) -> Task<Result<Navigated>> {
9569 let Some(workspace) = self.workspace() else {
9570 return Task::ready(Ok(Navigated::No));
9571 };
9572 let buffer = self.buffer.read(cx);
9573 let head = self.selections.newest::<usize>(cx).head();
9574 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9575 text_anchor
9576 } else {
9577 return Task::ready(Ok(Navigated::No));
9578 };
9579
9580 let project = workspace.read(cx).project().clone();
9581 let definitions = project.update(cx, |project, cx| match kind {
9582 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9583 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9584 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9585 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9586 });
9587
9588 cx.spawn(|editor, mut cx| async move {
9589 let definitions = definitions.await?;
9590 let navigated = editor
9591 .update(&mut cx, |editor, cx| {
9592 editor.navigate_to_hover_links(
9593 Some(kind),
9594 definitions
9595 .into_iter()
9596 .filter(|location| {
9597 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9598 })
9599 .map(HoverLink::Text)
9600 .collect::<Vec<_>>(),
9601 split,
9602 cx,
9603 )
9604 })?
9605 .await?;
9606 anyhow::Ok(navigated)
9607 })
9608 }
9609
9610 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9611 let position = self.selections.newest_anchor().head();
9612 let Some((buffer, buffer_position)) =
9613 self.buffer.read(cx).text_anchor_for_position(position, cx)
9614 else {
9615 return;
9616 };
9617
9618 cx.spawn(|editor, mut cx| async move {
9619 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9620 editor.update(&mut cx, |_, cx| {
9621 cx.open_url(&url);
9622 })
9623 } else {
9624 Ok(())
9625 }
9626 })
9627 .detach();
9628 }
9629
9630 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9631 let Some(workspace) = self.workspace() else {
9632 return;
9633 };
9634
9635 let position = self.selections.newest_anchor().head();
9636
9637 let Some((buffer, buffer_position)) =
9638 self.buffer.read(cx).text_anchor_for_position(position, cx)
9639 else {
9640 return;
9641 };
9642
9643 let Some(project) = self.project.clone() else {
9644 return;
9645 };
9646
9647 cx.spawn(|_, mut cx| async move {
9648 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9649
9650 if let Some((_, path)) = result {
9651 workspace
9652 .update(&mut cx, |workspace, cx| {
9653 workspace.open_resolved_path(path, cx)
9654 })?
9655 .await?;
9656 }
9657 anyhow::Ok(())
9658 })
9659 .detach();
9660 }
9661
9662 pub(crate) fn navigate_to_hover_links(
9663 &mut self,
9664 kind: Option<GotoDefinitionKind>,
9665 mut definitions: Vec<HoverLink>,
9666 split: bool,
9667 cx: &mut ViewContext<Editor>,
9668 ) -> Task<Result<Navigated>> {
9669 // If there is one definition, just open it directly
9670 if definitions.len() == 1 {
9671 let definition = definitions.pop().unwrap();
9672
9673 enum TargetTaskResult {
9674 Location(Option<Location>),
9675 AlreadyNavigated,
9676 }
9677
9678 let target_task = match definition {
9679 HoverLink::Text(link) => {
9680 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9681 }
9682 HoverLink::InlayHint(lsp_location, server_id) => {
9683 let computation = self.compute_target_location(lsp_location, server_id, cx);
9684 cx.background_executor().spawn(async move {
9685 let location = computation.await?;
9686 Ok(TargetTaskResult::Location(location))
9687 })
9688 }
9689 HoverLink::Url(url) => {
9690 cx.open_url(&url);
9691 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9692 }
9693 HoverLink::File(path) => {
9694 if let Some(workspace) = self.workspace() {
9695 cx.spawn(|_, mut cx| async move {
9696 workspace
9697 .update(&mut cx, |workspace, cx| {
9698 workspace.open_resolved_path(path, cx)
9699 })?
9700 .await
9701 .map(|_| TargetTaskResult::AlreadyNavigated)
9702 })
9703 } else {
9704 Task::ready(Ok(TargetTaskResult::Location(None)))
9705 }
9706 }
9707 };
9708 cx.spawn(|editor, mut cx| async move {
9709 let target = match target_task.await.context("target resolution task")? {
9710 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9711 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9712 TargetTaskResult::Location(Some(target)) => target,
9713 };
9714
9715 editor.update(&mut cx, |editor, cx| {
9716 let Some(workspace) = editor.workspace() else {
9717 return Navigated::No;
9718 };
9719 let pane = workspace.read(cx).active_pane().clone();
9720
9721 let range = target.range.to_offset(target.buffer.read(cx));
9722 let range = editor.range_for_match(&range);
9723
9724 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9725 let buffer = target.buffer.read(cx);
9726 let range = check_multiline_range(buffer, range);
9727 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
9728 s.select_ranges([range]);
9729 });
9730 } else {
9731 cx.window_context().defer(move |cx| {
9732 let target_editor: View<Self> =
9733 workspace.update(cx, |workspace, cx| {
9734 let pane = if split {
9735 workspace.adjacent_pane(cx)
9736 } else {
9737 workspace.active_pane().clone()
9738 };
9739
9740 workspace.open_project_item(
9741 pane,
9742 target.buffer.clone(),
9743 true,
9744 true,
9745 cx,
9746 )
9747 });
9748 target_editor.update(cx, |target_editor, cx| {
9749 // When selecting a definition in a different buffer, disable the nav history
9750 // to avoid creating a history entry at the previous cursor location.
9751 pane.update(cx, |pane, _| pane.disable_history());
9752 let buffer = target.buffer.read(cx);
9753 let range = check_multiline_range(buffer, range);
9754 target_editor.change_selections(
9755 Some(Autoscroll::focused()),
9756 cx,
9757 |s| {
9758 s.select_ranges([range]);
9759 },
9760 );
9761 pane.update(cx, |pane, _| pane.enable_history());
9762 });
9763 });
9764 }
9765 Navigated::Yes
9766 })
9767 })
9768 } else if !definitions.is_empty() {
9769 cx.spawn(|editor, mut cx| async move {
9770 let (title, location_tasks, workspace) = editor
9771 .update(&mut cx, |editor, cx| {
9772 let tab_kind = match kind {
9773 Some(GotoDefinitionKind::Implementation) => "Implementations",
9774 _ => "Definitions",
9775 };
9776 let title = definitions
9777 .iter()
9778 .find_map(|definition| match definition {
9779 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9780 let buffer = origin.buffer.read(cx);
9781 format!(
9782 "{} for {}",
9783 tab_kind,
9784 buffer
9785 .text_for_range(origin.range.clone())
9786 .collect::<String>()
9787 )
9788 }),
9789 HoverLink::InlayHint(_, _) => None,
9790 HoverLink::Url(_) => None,
9791 HoverLink::File(_) => None,
9792 })
9793 .unwrap_or(tab_kind.to_string());
9794 let location_tasks = definitions
9795 .into_iter()
9796 .map(|definition| match definition {
9797 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9798 HoverLink::InlayHint(lsp_location, server_id) => {
9799 editor.compute_target_location(lsp_location, server_id, cx)
9800 }
9801 HoverLink::Url(_) => Task::ready(Ok(None)),
9802 HoverLink::File(_) => Task::ready(Ok(None)),
9803 })
9804 .collect::<Vec<_>>();
9805 (title, location_tasks, editor.workspace().clone())
9806 })
9807 .context("location tasks preparation")?;
9808
9809 let locations = future::join_all(location_tasks)
9810 .await
9811 .into_iter()
9812 .filter_map(|location| location.transpose())
9813 .collect::<Result<_>>()
9814 .context("location tasks")?;
9815
9816 let Some(workspace) = workspace else {
9817 return Ok(Navigated::No);
9818 };
9819 let opened = workspace
9820 .update(&mut cx, |workspace, cx| {
9821 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9822 })
9823 .ok();
9824
9825 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9826 })
9827 } else {
9828 Task::ready(Ok(Navigated::No))
9829 }
9830 }
9831
9832 fn compute_target_location(
9833 &self,
9834 lsp_location: lsp::Location,
9835 server_id: LanguageServerId,
9836 cx: &mut ViewContext<Editor>,
9837 ) -> Task<anyhow::Result<Option<Location>>> {
9838 let Some(project) = self.project.clone() else {
9839 return Task::Ready(Some(Ok(None)));
9840 };
9841
9842 cx.spawn(move |editor, mut cx| async move {
9843 let location_task = editor.update(&mut cx, |editor, cx| {
9844 project.update(cx, |project, cx| {
9845 let language_server_name =
9846 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9847 project
9848 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9849 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9850 });
9851 language_server_name.map(|language_server_name| {
9852 project.open_local_buffer_via_lsp(
9853 lsp_location.uri.clone(),
9854 server_id,
9855 language_server_name,
9856 cx,
9857 )
9858 })
9859 })
9860 })?;
9861 let location = match location_task {
9862 Some(task) => Some({
9863 let target_buffer_handle = task.await.context("open local buffer")?;
9864 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9865 let target_start = target_buffer
9866 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9867 let target_end = target_buffer
9868 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9869 target_buffer.anchor_after(target_start)
9870 ..target_buffer.anchor_before(target_end)
9871 })?;
9872 Location {
9873 buffer: target_buffer_handle,
9874 range,
9875 }
9876 }),
9877 None => None,
9878 };
9879 Ok(location)
9880 })
9881 }
9882
9883 pub fn find_all_references(
9884 &mut self,
9885 _: &FindAllReferences,
9886 cx: &mut ViewContext<Self>,
9887 ) -> Option<Task<Result<Navigated>>> {
9888 let multi_buffer = self.buffer.read(cx);
9889 let selection = self.selections.newest::<usize>(cx);
9890 let head = selection.head();
9891
9892 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9893 let head_anchor = multi_buffer_snapshot.anchor_at(
9894 head,
9895 if head < selection.tail() {
9896 Bias::Right
9897 } else {
9898 Bias::Left
9899 },
9900 );
9901
9902 match self
9903 .find_all_references_task_sources
9904 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9905 {
9906 Ok(_) => {
9907 log::info!(
9908 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9909 );
9910 return None;
9911 }
9912 Err(i) => {
9913 self.find_all_references_task_sources.insert(i, head_anchor);
9914 }
9915 }
9916
9917 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9918 let workspace = self.workspace()?;
9919 let project = workspace.read(cx).project().clone();
9920 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9921 Some(cx.spawn(|editor, mut cx| async move {
9922 let _cleanup = defer({
9923 let mut cx = cx.clone();
9924 move || {
9925 let _ = editor.update(&mut cx, |editor, _| {
9926 if let Ok(i) =
9927 editor
9928 .find_all_references_task_sources
9929 .binary_search_by(|anchor| {
9930 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9931 })
9932 {
9933 editor.find_all_references_task_sources.remove(i);
9934 }
9935 });
9936 }
9937 });
9938
9939 let locations = references.await?;
9940 if locations.is_empty() {
9941 return anyhow::Ok(Navigated::No);
9942 }
9943
9944 workspace.update(&mut cx, |workspace, cx| {
9945 let title = locations
9946 .first()
9947 .as_ref()
9948 .map(|location| {
9949 let buffer = location.buffer.read(cx);
9950 format!(
9951 "References to `{}`",
9952 buffer
9953 .text_for_range(location.range.clone())
9954 .collect::<String>()
9955 )
9956 })
9957 .unwrap();
9958 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9959 Navigated::Yes
9960 })
9961 }))
9962 }
9963
9964 /// Opens a multibuffer with the given project locations in it
9965 pub fn open_locations_in_multibuffer(
9966 workspace: &mut Workspace,
9967 mut locations: Vec<Location>,
9968 title: String,
9969 split: bool,
9970 cx: &mut ViewContext<Workspace>,
9971 ) {
9972 // If there are multiple definitions, open them in a multibuffer
9973 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9974 let mut locations = locations.into_iter().peekable();
9975 let mut ranges_to_highlight = Vec::new();
9976 let capability = workspace.project().read(cx).capability();
9977
9978 let excerpt_buffer = cx.new_model(|cx| {
9979 let mut multibuffer = MultiBuffer::new(capability);
9980 while let Some(location) = locations.next() {
9981 let buffer = location.buffer.read(cx);
9982 let mut ranges_for_buffer = Vec::new();
9983 let range = location.range.to_offset(buffer);
9984 ranges_for_buffer.push(range.clone());
9985
9986 while let Some(next_location) = locations.peek() {
9987 if next_location.buffer == location.buffer {
9988 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9989 locations.next();
9990 } else {
9991 break;
9992 }
9993 }
9994
9995 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9996 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9997 location.buffer.clone(),
9998 ranges_for_buffer,
9999 DEFAULT_MULTIBUFFER_CONTEXT,
10000 cx,
10001 ))
10002 }
10003
10004 multibuffer.with_title(title)
10005 });
10006
10007 let editor = cx.new_view(|cx| {
10008 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
10009 });
10010 editor.update(cx, |editor, cx| {
10011 if let Some(first_range) = ranges_to_highlight.first() {
10012 editor.change_selections(None, cx, |selections| {
10013 selections.clear_disjoint();
10014 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
10015 });
10016 }
10017 editor.highlight_background::<Self>(
10018 &ranges_to_highlight,
10019 |theme| theme.editor_highlighted_line_background,
10020 cx,
10021 );
10022 });
10023
10024 let item = Box::new(editor);
10025 let item_id = item.item_id();
10026
10027 if split {
10028 workspace.split_item(SplitDirection::Right, item.clone(), cx);
10029 } else {
10030 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
10031 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
10032 pane.close_current_preview_item(cx)
10033 } else {
10034 None
10035 }
10036 });
10037 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
10038 }
10039 workspace.active_pane().update(cx, |pane, cx| {
10040 pane.set_preview_item_id(Some(item_id), cx);
10041 });
10042 }
10043
10044 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10045 use language::ToOffset as _;
10046
10047 let project = self.project.clone()?;
10048 let selection = self.selections.newest_anchor().clone();
10049 let (cursor_buffer, cursor_buffer_position) = self
10050 .buffer
10051 .read(cx)
10052 .text_anchor_for_position(selection.head(), cx)?;
10053 let (tail_buffer, cursor_buffer_position_end) = self
10054 .buffer
10055 .read(cx)
10056 .text_anchor_for_position(selection.tail(), cx)?;
10057 if tail_buffer != cursor_buffer {
10058 return None;
10059 }
10060
10061 let snapshot = cursor_buffer.read(cx).snapshot();
10062 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
10063 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
10064 let prepare_rename = project.update(cx, |project, cx| {
10065 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
10066 });
10067 drop(snapshot);
10068
10069 Some(cx.spawn(|this, mut cx| async move {
10070 let rename_range = if let Some(range) = prepare_rename.await? {
10071 Some(range)
10072 } else {
10073 this.update(&mut cx, |this, cx| {
10074 let buffer = this.buffer.read(cx).snapshot(cx);
10075 let mut buffer_highlights = this
10076 .document_highlights_for_position(selection.head(), &buffer)
10077 .filter(|highlight| {
10078 highlight.start.excerpt_id == selection.head().excerpt_id
10079 && highlight.end.excerpt_id == selection.head().excerpt_id
10080 });
10081 buffer_highlights
10082 .next()
10083 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
10084 })?
10085 };
10086 if let Some(rename_range) = rename_range {
10087 this.update(&mut cx, |this, cx| {
10088 let snapshot = cursor_buffer.read(cx).snapshot();
10089 let rename_buffer_range = rename_range.to_offset(&snapshot);
10090 let cursor_offset_in_rename_range =
10091 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
10092 let cursor_offset_in_rename_range_end =
10093 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
10094
10095 this.take_rename(false, cx);
10096 let buffer = this.buffer.read(cx).read(cx);
10097 let cursor_offset = selection.head().to_offset(&buffer);
10098 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
10099 let rename_end = rename_start + rename_buffer_range.len();
10100 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
10101 let mut old_highlight_id = None;
10102 let old_name: Arc<str> = buffer
10103 .chunks(rename_start..rename_end, true)
10104 .map(|chunk| {
10105 if old_highlight_id.is_none() {
10106 old_highlight_id = chunk.syntax_highlight_id;
10107 }
10108 chunk.text
10109 })
10110 .collect::<String>()
10111 .into();
10112
10113 drop(buffer);
10114
10115 // Position the selection in the rename editor so that it matches the current selection.
10116 this.show_local_selections = false;
10117 let rename_editor = cx.new_view(|cx| {
10118 let mut editor = Editor::single_line(cx);
10119 editor.buffer.update(cx, |buffer, cx| {
10120 buffer.edit([(0..0, old_name.clone())], None, cx)
10121 });
10122 let rename_selection_range = match cursor_offset_in_rename_range
10123 .cmp(&cursor_offset_in_rename_range_end)
10124 {
10125 Ordering::Equal => {
10126 editor.select_all(&SelectAll, cx);
10127 return editor;
10128 }
10129 Ordering::Less => {
10130 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10131 }
10132 Ordering::Greater => {
10133 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10134 }
10135 };
10136 if rename_selection_range.end > old_name.len() {
10137 editor.select_all(&SelectAll, cx);
10138 } else {
10139 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10140 s.select_ranges([rename_selection_range]);
10141 });
10142 }
10143 editor
10144 });
10145 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10146 if e == &EditorEvent::Focused {
10147 cx.emit(EditorEvent::FocusedIn)
10148 }
10149 })
10150 .detach();
10151
10152 let write_highlights =
10153 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10154 let read_highlights =
10155 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10156 let ranges = write_highlights
10157 .iter()
10158 .flat_map(|(_, ranges)| ranges.iter())
10159 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10160 .cloned()
10161 .collect();
10162
10163 this.highlight_text::<Rename>(
10164 ranges,
10165 HighlightStyle {
10166 fade_out: Some(0.6),
10167 ..Default::default()
10168 },
10169 cx,
10170 );
10171 let rename_focus_handle = rename_editor.focus_handle(cx);
10172 cx.focus(&rename_focus_handle);
10173 let block_id = this.insert_blocks(
10174 [BlockProperties {
10175 style: BlockStyle::Flex,
10176 position: range.start,
10177 height: 1,
10178 render: Box::new({
10179 let rename_editor = rename_editor.clone();
10180 move |cx: &mut BlockContext| {
10181 let mut text_style = cx.editor_style.text.clone();
10182 if let Some(highlight_style) = old_highlight_id
10183 .and_then(|h| h.style(&cx.editor_style.syntax))
10184 {
10185 text_style = text_style.highlight(highlight_style);
10186 }
10187 div()
10188 .pl(cx.anchor_x)
10189 .child(EditorElement::new(
10190 &rename_editor,
10191 EditorStyle {
10192 background: cx.theme().system().transparent,
10193 local_player: cx.editor_style.local_player,
10194 text: text_style,
10195 scrollbar_width: cx.editor_style.scrollbar_width,
10196 syntax: cx.editor_style.syntax.clone(),
10197 status: cx.editor_style.status.clone(),
10198 inlay_hints_style: HighlightStyle {
10199 font_weight: Some(FontWeight::BOLD),
10200 ..make_inlay_hints_style(cx)
10201 },
10202 suggestions_style: HighlightStyle {
10203 color: Some(cx.theme().status().predictive),
10204 ..HighlightStyle::default()
10205 },
10206 ..EditorStyle::default()
10207 },
10208 ))
10209 .into_any_element()
10210 }
10211 }),
10212 disposition: BlockDisposition::Below,
10213 priority: 0,
10214 }],
10215 Some(Autoscroll::fit()),
10216 cx,
10217 )[0];
10218 this.pending_rename = Some(RenameState {
10219 range,
10220 old_name,
10221 editor: rename_editor,
10222 block_id,
10223 });
10224 })?;
10225 }
10226
10227 Ok(())
10228 }))
10229 }
10230
10231 pub fn confirm_rename(
10232 &mut self,
10233 _: &ConfirmRename,
10234 cx: &mut ViewContext<Self>,
10235 ) -> Option<Task<Result<()>>> {
10236 let rename = self.take_rename(false, cx)?;
10237 let workspace = self.workspace()?;
10238 let (start_buffer, start) = self
10239 .buffer
10240 .read(cx)
10241 .text_anchor_for_position(rename.range.start, cx)?;
10242 let (end_buffer, end) = self
10243 .buffer
10244 .read(cx)
10245 .text_anchor_for_position(rename.range.end, cx)?;
10246 if start_buffer != end_buffer {
10247 return None;
10248 }
10249
10250 let buffer = start_buffer;
10251 let range = start..end;
10252 let old_name = rename.old_name;
10253 let new_name = rename.editor.read(cx).text(cx);
10254
10255 let rename = workspace
10256 .read(cx)
10257 .project()
10258 .clone()
10259 .update(cx, |project, cx| {
10260 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10261 });
10262 let workspace = workspace.downgrade();
10263
10264 Some(cx.spawn(|editor, mut cx| async move {
10265 let project_transaction = rename.await?;
10266 Self::open_project_transaction(
10267 &editor,
10268 workspace,
10269 project_transaction,
10270 format!("Rename: {} → {}", old_name, new_name),
10271 cx.clone(),
10272 )
10273 .await?;
10274
10275 editor.update(&mut cx, |editor, cx| {
10276 editor.refresh_document_highlights(cx);
10277 })?;
10278 Ok(())
10279 }))
10280 }
10281
10282 fn take_rename(
10283 &mut self,
10284 moving_cursor: bool,
10285 cx: &mut ViewContext<Self>,
10286 ) -> Option<RenameState> {
10287 let rename = self.pending_rename.take()?;
10288 if rename.editor.focus_handle(cx).is_focused(cx) {
10289 cx.focus(&self.focus_handle);
10290 }
10291
10292 self.remove_blocks(
10293 [rename.block_id].into_iter().collect(),
10294 Some(Autoscroll::fit()),
10295 cx,
10296 );
10297 self.clear_highlights::<Rename>(cx);
10298 self.show_local_selections = true;
10299
10300 if moving_cursor {
10301 let rename_editor = rename.editor.read(cx);
10302 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10303
10304 // Update the selection to match the position of the selection inside
10305 // the rename editor.
10306 let snapshot = self.buffer.read(cx).read(cx);
10307 let rename_range = rename.range.to_offset(&snapshot);
10308 let cursor_in_editor = snapshot
10309 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10310 .min(rename_range.end);
10311 drop(snapshot);
10312
10313 self.change_selections(None, cx, |s| {
10314 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10315 });
10316 } else {
10317 self.refresh_document_highlights(cx);
10318 }
10319
10320 Some(rename)
10321 }
10322
10323 pub fn pending_rename(&self) -> Option<&RenameState> {
10324 self.pending_rename.as_ref()
10325 }
10326
10327 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10328 let project = match &self.project {
10329 Some(project) => project.clone(),
10330 None => return None,
10331 };
10332
10333 Some(self.perform_format(project, FormatTrigger::Manual, cx))
10334 }
10335
10336 fn perform_format(
10337 &mut self,
10338 project: Model<Project>,
10339 trigger: FormatTrigger,
10340 cx: &mut ViewContext<Self>,
10341 ) -> Task<Result<()>> {
10342 let buffer = self.buffer().clone();
10343 let mut buffers = buffer.read(cx).all_buffers();
10344 if trigger == FormatTrigger::Save {
10345 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10346 }
10347
10348 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10349 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10350
10351 cx.spawn(|_, mut cx| async move {
10352 let transaction = futures::select_biased! {
10353 () = timeout => {
10354 log::warn!("timed out waiting for formatting");
10355 None
10356 }
10357 transaction = format.log_err().fuse() => transaction,
10358 };
10359
10360 buffer
10361 .update(&mut cx, |buffer, cx| {
10362 if let Some(transaction) = transaction {
10363 if !buffer.is_singleton() {
10364 buffer.push_transaction(&transaction.0, cx);
10365 }
10366 }
10367
10368 cx.notify();
10369 })
10370 .ok();
10371
10372 Ok(())
10373 })
10374 }
10375
10376 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10377 if let Some(project) = self.project.clone() {
10378 self.buffer.update(cx, |multi_buffer, cx| {
10379 project.update(cx, |project, cx| {
10380 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10381 });
10382 })
10383 }
10384 }
10385
10386 fn cancel_language_server_work(
10387 &mut self,
10388 _: &CancelLanguageServerWork,
10389 cx: &mut ViewContext<Self>,
10390 ) {
10391 if let Some(project) = self.project.clone() {
10392 self.buffer.update(cx, |multi_buffer, cx| {
10393 project.update(cx, |project, cx| {
10394 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10395 });
10396 })
10397 }
10398 }
10399
10400 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10401 cx.show_character_palette();
10402 }
10403
10404 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10405 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10406 let buffer = self.buffer.read(cx).snapshot(cx);
10407 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10408 let is_valid = buffer
10409 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10410 .any(|entry| {
10411 entry.diagnostic.is_primary
10412 && !entry.range.is_empty()
10413 && entry.range.start == primary_range_start
10414 && entry.diagnostic.message == active_diagnostics.primary_message
10415 });
10416
10417 if is_valid != active_diagnostics.is_valid {
10418 active_diagnostics.is_valid = is_valid;
10419 let mut new_styles = HashMap::default();
10420 for (block_id, diagnostic) in &active_diagnostics.blocks {
10421 new_styles.insert(
10422 *block_id,
10423 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10424 );
10425 }
10426 self.display_map.update(cx, |display_map, _cx| {
10427 display_map.replace_blocks(new_styles)
10428 });
10429 }
10430 }
10431 }
10432
10433 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10434 self.dismiss_diagnostics(cx);
10435 let snapshot = self.snapshot(cx);
10436 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10437 let buffer = self.buffer.read(cx).snapshot(cx);
10438
10439 let mut primary_range = None;
10440 let mut primary_message = None;
10441 let mut group_end = Point::zero();
10442 let diagnostic_group = buffer
10443 .diagnostic_group::<MultiBufferPoint>(group_id)
10444 .filter_map(|entry| {
10445 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10446 && (entry.range.start.row == entry.range.end.row
10447 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10448 {
10449 return None;
10450 }
10451 if entry.range.end > group_end {
10452 group_end = entry.range.end;
10453 }
10454 if entry.diagnostic.is_primary {
10455 primary_range = Some(entry.range.clone());
10456 primary_message = Some(entry.diagnostic.message.clone());
10457 }
10458 Some(entry)
10459 })
10460 .collect::<Vec<_>>();
10461 let primary_range = primary_range?;
10462 let primary_message = primary_message?;
10463 let primary_range =
10464 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10465
10466 let blocks = display_map
10467 .insert_blocks(
10468 diagnostic_group.iter().map(|entry| {
10469 let diagnostic = entry.diagnostic.clone();
10470 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10471 BlockProperties {
10472 style: BlockStyle::Fixed,
10473 position: buffer.anchor_after(entry.range.start),
10474 height: message_height,
10475 render: diagnostic_block_renderer(diagnostic, None, true, true),
10476 disposition: BlockDisposition::Below,
10477 priority: 0,
10478 }
10479 }),
10480 cx,
10481 )
10482 .into_iter()
10483 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10484 .collect();
10485
10486 Some(ActiveDiagnosticGroup {
10487 primary_range,
10488 primary_message,
10489 group_id,
10490 blocks,
10491 is_valid: true,
10492 })
10493 });
10494 self.active_diagnostics.is_some()
10495 }
10496
10497 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10498 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10499 self.display_map.update(cx, |display_map, cx| {
10500 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10501 });
10502 cx.notify();
10503 }
10504 }
10505
10506 pub fn set_selections_from_remote(
10507 &mut self,
10508 selections: Vec<Selection<Anchor>>,
10509 pending_selection: Option<Selection<Anchor>>,
10510 cx: &mut ViewContext<Self>,
10511 ) {
10512 let old_cursor_position = self.selections.newest_anchor().head();
10513 self.selections.change_with(cx, |s| {
10514 s.select_anchors(selections);
10515 if let Some(pending_selection) = pending_selection {
10516 s.set_pending(pending_selection, SelectMode::Character);
10517 } else {
10518 s.clear_pending();
10519 }
10520 });
10521 self.selections_did_change(false, &old_cursor_position, true, cx);
10522 }
10523
10524 fn push_to_selection_history(&mut self) {
10525 self.selection_history.push(SelectionHistoryEntry {
10526 selections: self.selections.disjoint_anchors(),
10527 select_next_state: self.select_next_state.clone(),
10528 select_prev_state: self.select_prev_state.clone(),
10529 add_selections_state: self.add_selections_state.clone(),
10530 });
10531 }
10532
10533 pub fn transact(
10534 &mut self,
10535 cx: &mut ViewContext<Self>,
10536 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10537 ) -> Option<TransactionId> {
10538 self.start_transaction_at(Instant::now(), cx);
10539 update(self, cx);
10540 self.end_transaction_at(Instant::now(), cx)
10541 }
10542
10543 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10544 self.end_selection(cx);
10545 if let Some(tx_id) = self
10546 .buffer
10547 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10548 {
10549 self.selection_history
10550 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10551 cx.emit(EditorEvent::TransactionBegun {
10552 transaction_id: tx_id,
10553 })
10554 }
10555 }
10556
10557 fn end_transaction_at(
10558 &mut self,
10559 now: Instant,
10560 cx: &mut ViewContext<Self>,
10561 ) -> Option<TransactionId> {
10562 if let Some(transaction_id) = self
10563 .buffer
10564 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10565 {
10566 if let Some((_, end_selections)) =
10567 self.selection_history.transaction_mut(transaction_id)
10568 {
10569 *end_selections = Some(self.selections.disjoint_anchors());
10570 } else {
10571 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10572 }
10573
10574 cx.emit(EditorEvent::Edited { transaction_id });
10575 Some(transaction_id)
10576 } else {
10577 None
10578 }
10579 }
10580
10581 pub fn toggle_fold(&mut self, _: &actions::ToggleFold, cx: &mut ViewContext<Self>) {
10582 let selection = self.selections.newest::<Point>(cx);
10583
10584 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10585 let range = if selection.is_empty() {
10586 let point = selection.head().to_display_point(&display_map);
10587 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10588 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10589 .to_point(&display_map);
10590 start..end
10591 } else {
10592 selection.range()
10593 };
10594 if display_map.folds_in_range(range).next().is_some() {
10595 self.unfold_lines(&Default::default(), cx)
10596 } else {
10597 self.fold(&Default::default(), cx)
10598 }
10599 }
10600
10601 pub fn toggle_fold_recursive(
10602 &mut self,
10603 _: &actions::ToggleFoldRecursive,
10604 cx: &mut ViewContext<Self>,
10605 ) {
10606 let selection = self.selections.newest::<Point>(cx);
10607
10608 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10609 let range = if selection.is_empty() {
10610 let point = selection.head().to_display_point(&display_map);
10611 let start = DisplayPoint::new(point.row(), 0).to_point(&display_map);
10612 let end = DisplayPoint::new(point.row(), display_map.line_len(point.row()))
10613 .to_point(&display_map);
10614 start..end
10615 } else {
10616 selection.range()
10617 };
10618 if display_map.folds_in_range(range).next().is_some() {
10619 self.unfold_recursive(&Default::default(), cx)
10620 } else {
10621 self.fold_recursive(&Default::default(), cx)
10622 }
10623 }
10624
10625 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10626 let mut fold_ranges = Vec::new();
10627 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10628 let selections = self.selections.all_adjusted(cx);
10629
10630 for selection in selections {
10631 let range = selection.range().sorted();
10632 let buffer_start_row = range.start.row;
10633
10634 if range.start.row != range.end.row {
10635 let mut found = false;
10636 let mut row = range.start.row;
10637 while row <= range.end.row {
10638 if let Some((foldable_range, fold_text)) =
10639 { display_map.foldable_range(MultiBufferRow(row)) }
10640 {
10641 found = true;
10642 row = foldable_range.end.row + 1;
10643 fold_ranges.push((foldable_range, fold_text));
10644 } else {
10645 row += 1
10646 }
10647 }
10648 if found {
10649 continue;
10650 }
10651 }
10652
10653 for row in (0..=range.start.row).rev() {
10654 if let Some((foldable_range, fold_text)) =
10655 display_map.foldable_range(MultiBufferRow(row))
10656 {
10657 if foldable_range.end.row >= buffer_start_row {
10658 fold_ranges.push((foldable_range, fold_text));
10659 if row <= range.start.row {
10660 break;
10661 }
10662 }
10663 }
10664 }
10665 }
10666
10667 self.fold_ranges(fold_ranges, true, cx);
10668 }
10669
10670 pub fn fold_all(&mut self, _: &actions::FoldAll, cx: &mut ViewContext<Self>) {
10671 let mut fold_ranges = Vec::new();
10672 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10673
10674 for row in 0..display_map.max_buffer_row().0 {
10675 if let Some((foldable_range, fold_text)) =
10676 display_map.foldable_range(MultiBufferRow(row))
10677 {
10678 fold_ranges.push((foldable_range, fold_text));
10679 }
10680 }
10681
10682 self.fold_ranges(fold_ranges, true, cx);
10683 }
10684
10685 pub fn fold_recursive(&mut self, _: &actions::FoldRecursive, cx: &mut ViewContext<Self>) {
10686 let mut fold_ranges = Vec::new();
10687 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10688 let selections = self.selections.all_adjusted(cx);
10689
10690 for selection in selections {
10691 let range = selection.range().sorted();
10692 let buffer_start_row = range.start.row;
10693
10694 if range.start.row != range.end.row {
10695 let mut found = false;
10696 for row in range.start.row..=range.end.row {
10697 if let Some((foldable_range, fold_text)) =
10698 { display_map.foldable_range(MultiBufferRow(row)) }
10699 {
10700 found = true;
10701 fold_ranges.push((foldable_range, fold_text));
10702 }
10703 }
10704 if found {
10705 continue;
10706 }
10707 }
10708
10709 for row in (0..=range.start.row).rev() {
10710 if let Some((foldable_range, fold_text)) =
10711 display_map.foldable_range(MultiBufferRow(row))
10712 {
10713 if foldable_range.end.row >= buffer_start_row {
10714 fold_ranges.push((foldable_range, fold_text));
10715 } else {
10716 break;
10717 }
10718 }
10719 }
10720 }
10721
10722 self.fold_ranges(fold_ranges, true, cx);
10723 }
10724
10725 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10726 let buffer_row = fold_at.buffer_row;
10727 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10728
10729 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10730 let autoscroll = self
10731 .selections
10732 .all::<Point>(cx)
10733 .iter()
10734 .any(|selection| fold_range.overlaps(&selection.range()));
10735
10736 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10737 }
10738 }
10739
10740 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10741 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10742 let buffer = &display_map.buffer_snapshot;
10743 let selections = self.selections.all::<Point>(cx);
10744 let ranges = selections
10745 .iter()
10746 .map(|s| {
10747 let range = s.display_range(&display_map).sorted();
10748 let mut start = range.start.to_point(&display_map);
10749 let mut end = range.end.to_point(&display_map);
10750 start.column = 0;
10751 end.column = buffer.line_len(MultiBufferRow(end.row));
10752 start..end
10753 })
10754 .collect::<Vec<_>>();
10755
10756 self.unfold_ranges(ranges, true, true, cx);
10757 }
10758
10759 pub fn unfold_recursive(&mut self, _: &UnfoldRecursive, cx: &mut ViewContext<Self>) {
10760 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10761 let selections = self.selections.all::<Point>(cx);
10762 let ranges = selections
10763 .iter()
10764 .map(|s| {
10765 let mut range = s.display_range(&display_map).sorted();
10766 *range.start.column_mut() = 0;
10767 *range.end.column_mut() = display_map.line_len(range.end.row());
10768 let start = range.start.to_point(&display_map);
10769 let end = range.end.to_point(&display_map);
10770 start..end
10771 })
10772 .collect::<Vec<_>>();
10773
10774 self.unfold_ranges(ranges, true, true, cx);
10775 }
10776
10777 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10778 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10779
10780 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10781 ..Point::new(
10782 unfold_at.buffer_row.0,
10783 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10784 );
10785
10786 let autoscroll = self
10787 .selections
10788 .all::<Point>(cx)
10789 .iter()
10790 .any(|selection| selection.range().overlaps(&intersection_range));
10791
10792 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10793 }
10794
10795 pub fn unfold_all(&mut self, _: &actions::UnfoldAll, cx: &mut ViewContext<Self>) {
10796 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10797 self.unfold_ranges(
10798 [Point::zero()..display_map.max_point().to_point(&display_map)],
10799 true,
10800 true,
10801 cx,
10802 );
10803 }
10804
10805 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10806 let selections = self.selections.all::<Point>(cx);
10807 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10808 let line_mode = self.selections.line_mode;
10809 let ranges = selections.into_iter().map(|s| {
10810 if line_mode {
10811 let start = Point::new(s.start.row, 0);
10812 let end = Point::new(
10813 s.end.row,
10814 display_map
10815 .buffer_snapshot
10816 .line_len(MultiBufferRow(s.end.row)),
10817 );
10818 (start..end, display_map.fold_placeholder.clone())
10819 } else {
10820 (s.start..s.end, display_map.fold_placeholder.clone())
10821 }
10822 });
10823 self.fold_ranges(ranges, true, cx);
10824 }
10825
10826 pub fn fold_ranges<T: ToOffset + Clone>(
10827 &mut self,
10828 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10829 auto_scroll: bool,
10830 cx: &mut ViewContext<Self>,
10831 ) {
10832 let mut fold_ranges = Vec::new();
10833 let mut buffers_affected = HashMap::default();
10834 let multi_buffer = self.buffer().read(cx);
10835 for (fold_range, fold_text) in ranges {
10836 if let Some((_, buffer, _)) =
10837 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10838 {
10839 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10840 };
10841 fold_ranges.push((fold_range, fold_text));
10842 }
10843
10844 let mut ranges = fold_ranges.into_iter().peekable();
10845 if ranges.peek().is_some() {
10846 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10847
10848 if auto_scroll {
10849 self.request_autoscroll(Autoscroll::fit(), cx);
10850 }
10851
10852 for buffer in buffers_affected.into_values() {
10853 self.sync_expanded_diff_hunks(buffer, cx);
10854 }
10855
10856 cx.notify();
10857
10858 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10859 // Clear diagnostics block when folding a range that contains it.
10860 let snapshot = self.snapshot(cx);
10861 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10862 drop(snapshot);
10863 self.active_diagnostics = Some(active_diagnostics);
10864 self.dismiss_diagnostics(cx);
10865 } else {
10866 self.active_diagnostics = Some(active_diagnostics);
10867 }
10868 }
10869
10870 self.scrollbar_marker_state.dirty = true;
10871 }
10872 }
10873
10874 pub fn unfold_ranges<T: ToOffset + Clone>(
10875 &mut self,
10876 ranges: impl IntoIterator<Item = Range<T>>,
10877 inclusive: bool,
10878 auto_scroll: bool,
10879 cx: &mut ViewContext<Self>,
10880 ) {
10881 let mut unfold_ranges = Vec::new();
10882 let mut buffers_affected = HashMap::default();
10883 let multi_buffer = self.buffer().read(cx);
10884 for range in ranges {
10885 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10886 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10887 };
10888 unfold_ranges.push(range);
10889 }
10890
10891 let mut ranges = unfold_ranges.into_iter().peekable();
10892 if ranges.peek().is_some() {
10893 self.display_map
10894 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10895 if auto_scroll {
10896 self.request_autoscroll(Autoscroll::fit(), cx);
10897 }
10898
10899 for buffer in buffers_affected.into_values() {
10900 self.sync_expanded_diff_hunks(buffer, cx);
10901 }
10902
10903 cx.notify();
10904 self.scrollbar_marker_state.dirty = true;
10905 self.active_indent_guides_state.dirty = true;
10906 }
10907 }
10908
10909 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10910 self.display_map.read(cx).fold_placeholder.clone()
10911 }
10912
10913 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10914 if hovered != self.gutter_hovered {
10915 self.gutter_hovered = hovered;
10916 cx.notify();
10917 }
10918 }
10919
10920 pub fn insert_blocks(
10921 &mut self,
10922 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10923 autoscroll: Option<Autoscroll>,
10924 cx: &mut ViewContext<Self>,
10925 ) -> Vec<CustomBlockId> {
10926 let blocks = self
10927 .display_map
10928 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10929 if let Some(autoscroll) = autoscroll {
10930 self.request_autoscroll(autoscroll, cx);
10931 }
10932 cx.notify();
10933 blocks
10934 }
10935
10936 pub fn resize_blocks(
10937 &mut self,
10938 heights: HashMap<CustomBlockId, u32>,
10939 autoscroll: Option<Autoscroll>,
10940 cx: &mut ViewContext<Self>,
10941 ) {
10942 self.display_map
10943 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10944 if let Some(autoscroll) = autoscroll {
10945 self.request_autoscroll(autoscroll, cx);
10946 }
10947 cx.notify();
10948 }
10949
10950 pub fn replace_blocks(
10951 &mut self,
10952 renderers: HashMap<CustomBlockId, RenderBlock>,
10953 autoscroll: Option<Autoscroll>,
10954 cx: &mut ViewContext<Self>,
10955 ) {
10956 self.display_map
10957 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10958 if let Some(autoscroll) = autoscroll {
10959 self.request_autoscroll(autoscroll, cx);
10960 }
10961 cx.notify();
10962 }
10963
10964 pub fn remove_blocks(
10965 &mut self,
10966 block_ids: HashSet<CustomBlockId>,
10967 autoscroll: Option<Autoscroll>,
10968 cx: &mut ViewContext<Self>,
10969 ) {
10970 self.display_map.update(cx, |display_map, cx| {
10971 display_map.remove_blocks(block_ids, cx)
10972 });
10973 if let Some(autoscroll) = autoscroll {
10974 self.request_autoscroll(autoscroll, cx);
10975 }
10976 cx.notify();
10977 }
10978
10979 pub fn row_for_block(
10980 &self,
10981 block_id: CustomBlockId,
10982 cx: &mut ViewContext<Self>,
10983 ) -> Option<DisplayRow> {
10984 self.display_map
10985 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10986 }
10987
10988 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10989 self.focused_block = Some(focused_block);
10990 }
10991
10992 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10993 self.focused_block.take()
10994 }
10995
10996 pub fn insert_creases(
10997 &mut self,
10998 creases: impl IntoIterator<Item = Crease>,
10999 cx: &mut ViewContext<Self>,
11000 ) -> Vec<CreaseId> {
11001 self.display_map
11002 .update(cx, |map, cx| map.insert_creases(creases, cx))
11003 }
11004
11005 pub fn remove_creases(
11006 &mut self,
11007 ids: impl IntoIterator<Item = CreaseId>,
11008 cx: &mut ViewContext<Self>,
11009 ) {
11010 self.display_map
11011 .update(cx, |map, cx| map.remove_creases(ids, cx));
11012 }
11013
11014 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
11015 self.display_map
11016 .update(cx, |map, cx| map.snapshot(cx))
11017 .longest_row()
11018 }
11019
11020 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
11021 self.display_map
11022 .update(cx, |map, cx| map.snapshot(cx))
11023 .max_point()
11024 }
11025
11026 pub fn text(&self, cx: &AppContext) -> String {
11027 self.buffer.read(cx).read(cx).text()
11028 }
11029
11030 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
11031 let text = self.text(cx);
11032 let text = text.trim();
11033
11034 if text.is_empty() {
11035 return None;
11036 }
11037
11038 Some(text.to_string())
11039 }
11040
11041 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
11042 self.transact(cx, |this, cx| {
11043 this.buffer
11044 .read(cx)
11045 .as_singleton()
11046 .expect("you can only call set_text on editors for singleton buffers")
11047 .update(cx, |buffer, cx| buffer.set_text(text, cx));
11048 });
11049 }
11050
11051 pub fn display_text(&self, cx: &mut AppContext) -> String {
11052 self.display_map
11053 .update(cx, |map, cx| map.snapshot(cx))
11054 .text()
11055 }
11056
11057 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
11058 let mut wrap_guides = smallvec::smallvec![];
11059
11060 if self.show_wrap_guides == Some(false) {
11061 return wrap_guides;
11062 }
11063
11064 let settings = self.buffer.read(cx).settings_at(0, cx);
11065 if settings.show_wrap_guides {
11066 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
11067 wrap_guides.push((soft_wrap as usize, true));
11068 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
11069 wrap_guides.push((soft_wrap as usize, true));
11070 }
11071 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
11072 }
11073
11074 wrap_guides
11075 }
11076
11077 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
11078 let settings = self.buffer.read(cx).settings_at(0, cx);
11079 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
11080 match mode {
11081 language_settings::SoftWrap::PreferLine | language_settings::SoftWrap::None => {
11082 SoftWrap::None
11083 }
11084 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
11085 language_settings::SoftWrap::PreferredLineLength => {
11086 SoftWrap::Column(settings.preferred_line_length)
11087 }
11088 language_settings::SoftWrap::Bounded => {
11089 SoftWrap::Bounded(settings.preferred_line_length)
11090 }
11091 }
11092 }
11093
11094 pub fn set_soft_wrap_mode(
11095 &mut self,
11096 mode: language_settings::SoftWrap,
11097 cx: &mut ViewContext<Self>,
11098 ) {
11099 self.soft_wrap_mode_override = Some(mode);
11100 cx.notify();
11101 }
11102
11103 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
11104 let rem_size = cx.rem_size();
11105 self.display_map.update(cx, |map, cx| {
11106 map.set_font(
11107 style.text.font(),
11108 style.text.font_size.to_pixels(rem_size),
11109 cx,
11110 )
11111 });
11112 self.style = Some(style);
11113 }
11114
11115 pub fn style(&self) -> Option<&EditorStyle> {
11116 self.style.as_ref()
11117 }
11118
11119 // Called by the element. This method is not designed to be called outside of the editor
11120 // element's layout code because it does not notify when rewrapping is computed synchronously.
11121 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
11122 self.display_map
11123 .update(cx, |map, cx| map.set_wrap_width(width, cx))
11124 }
11125
11126 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
11127 if self.soft_wrap_mode_override.is_some() {
11128 self.soft_wrap_mode_override.take();
11129 } else {
11130 let soft_wrap = match self.soft_wrap_mode(cx) {
11131 SoftWrap::GitDiff => return,
11132 SoftWrap::None => language_settings::SoftWrap::EditorWidth,
11133 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
11134 language_settings::SoftWrap::None
11135 }
11136 };
11137 self.soft_wrap_mode_override = Some(soft_wrap);
11138 }
11139 cx.notify();
11140 }
11141
11142 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
11143 let Some(workspace) = self.workspace() else {
11144 return;
11145 };
11146 let fs = workspace.read(cx).app_state().fs.clone();
11147 let current_show = TabBarSettings::get_global(cx).show;
11148 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
11149 setting.show = Some(!current_show);
11150 });
11151 }
11152
11153 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
11154 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
11155 self.buffer
11156 .read(cx)
11157 .settings_at(0, cx)
11158 .indent_guides
11159 .enabled
11160 });
11161 self.show_indent_guides = Some(!currently_enabled);
11162 cx.notify();
11163 }
11164
11165 fn should_show_indent_guides(&self) -> Option<bool> {
11166 self.show_indent_guides
11167 }
11168
11169 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
11170 let mut editor_settings = EditorSettings::get_global(cx).clone();
11171 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
11172 EditorSettings::override_global(editor_settings, cx);
11173 }
11174
11175 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
11176 self.use_relative_line_numbers
11177 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
11178 }
11179
11180 pub fn toggle_relative_line_numbers(
11181 &mut self,
11182 _: &ToggleRelativeLineNumbers,
11183 cx: &mut ViewContext<Self>,
11184 ) {
11185 let is_relative = self.should_use_relative_line_numbers(cx);
11186 self.set_relative_line_number(Some(!is_relative), cx)
11187 }
11188
11189 pub fn set_relative_line_number(
11190 &mut self,
11191 is_relative: Option<bool>,
11192 cx: &mut ViewContext<Self>,
11193 ) {
11194 self.use_relative_line_numbers = is_relative;
11195 cx.notify();
11196 }
11197
11198 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
11199 self.show_gutter = show_gutter;
11200 cx.notify();
11201 }
11202
11203 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
11204 self.show_line_numbers = Some(show_line_numbers);
11205 cx.notify();
11206 }
11207
11208 pub fn set_show_git_diff_gutter(
11209 &mut self,
11210 show_git_diff_gutter: bool,
11211 cx: &mut ViewContext<Self>,
11212 ) {
11213 self.show_git_diff_gutter = Some(show_git_diff_gutter);
11214 cx.notify();
11215 }
11216
11217 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
11218 self.show_code_actions = Some(show_code_actions);
11219 cx.notify();
11220 }
11221
11222 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
11223 self.show_runnables = Some(show_runnables);
11224 cx.notify();
11225 }
11226
11227 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
11228 if self.display_map.read(cx).masked != masked {
11229 self.display_map.update(cx, |map, _| map.masked = masked);
11230 }
11231 cx.notify()
11232 }
11233
11234 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
11235 self.show_wrap_guides = Some(show_wrap_guides);
11236 cx.notify();
11237 }
11238
11239 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
11240 self.show_indent_guides = Some(show_indent_guides);
11241 cx.notify();
11242 }
11243
11244 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
11245 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11246 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11247 if let Some(dir) = file.abs_path(cx).parent() {
11248 return Some(dir.to_owned());
11249 }
11250 }
11251
11252 if let Some(project_path) = buffer.read(cx).project_path(cx) {
11253 return Some(project_path.path.to_path_buf());
11254 }
11255 }
11256
11257 None
11258 }
11259
11260 fn target_file<'a>(&self, cx: &'a AppContext) -> Option<&'a dyn language::LocalFile> {
11261 self.active_excerpt(cx)?
11262 .1
11263 .read(cx)
11264 .file()
11265 .and_then(|f| f.as_local())
11266 }
11267
11268 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
11269 if let Some(target) = self.target_file(cx) {
11270 cx.reveal_path(&target.abs_path(cx));
11271 }
11272 }
11273
11274 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11275 if let Some(file) = self.target_file(cx) {
11276 if let Some(path) = file.abs_path(cx).to_str() {
11277 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11278 }
11279 }
11280 }
11281
11282 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11283 if let Some(file) = self.target_file(cx) {
11284 if let Some(path) = file.path().to_str() {
11285 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11286 }
11287 }
11288 }
11289
11290 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11291 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11292
11293 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11294 self.start_git_blame(true, cx);
11295 }
11296
11297 cx.notify();
11298 }
11299
11300 pub fn toggle_git_blame_inline(
11301 &mut self,
11302 _: &ToggleGitBlameInline,
11303 cx: &mut ViewContext<Self>,
11304 ) {
11305 self.toggle_git_blame_inline_internal(true, cx);
11306 cx.notify();
11307 }
11308
11309 pub fn git_blame_inline_enabled(&self) -> bool {
11310 self.git_blame_inline_enabled
11311 }
11312
11313 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11314 self.show_selection_menu = self
11315 .show_selection_menu
11316 .map(|show_selections_menu| !show_selections_menu)
11317 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11318
11319 cx.notify();
11320 }
11321
11322 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11323 self.show_selection_menu
11324 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11325 }
11326
11327 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11328 if let Some(project) = self.project.as_ref() {
11329 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11330 return;
11331 };
11332
11333 if buffer.read(cx).file().is_none() {
11334 return;
11335 }
11336
11337 let focused = self.focus_handle(cx).contains_focused(cx);
11338
11339 let project = project.clone();
11340 let blame =
11341 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11342 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11343 self.blame = Some(blame);
11344 }
11345 }
11346
11347 fn toggle_git_blame_inline_internal(
11348 &mut self,
11349 user_triggered: bool,
11350 cx: &mut ViewContext<Self>,
11351 ) {
11352 if self.git_blame_inline_enabled {
11353 self.git_blame_inline_enabled = false;
11354 self.show_git_blame_inline = false;
11355 self.show_git_blame_inline_delay_task.take();
11356 } else {
11357 self.git_blame_inline_enabled = true;
11358 self.start_git_blame_inline(user_triggered, cx);
11359 }
11360
11361 cx.notify();
11362 }
11363
11364 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11365 self.start_git_blame(user_triggered, cx);
11366
11367 if ProjectSettings::get_global(cx)
11368 .git
11369 .inline_blame_delay()
11370 .is_some()
11371 {
11372 self.start_inline_blame_timer(cx);
11373 } else {
11374 self.show_git_blame_inline = true
11375 }
11376 }
11377
11378 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11379 self.blame.as_ref()
11380 }
11381
11382 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11383 self.show_git_blame_gutter && self.has_blame_entries(cx)
11384 }
11385
11386 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11387 self.show_git_blame_inline
11388 && self.focus_handle.is_focused(cx)
11389 && !self.newest_selection_head_on_empty_line(cx)
11390 && self.has_blame_entries(cx)
11391 }
11392
11393 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11394 self.blame()
11395 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11396 }
11397
11398 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11399 let cursor_anchor = self.selections.newest_anchor().head();
11400
11401 let snapshot = self.buffer.read(cx).snapshot(cx);
11402 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11403
11404 snapshot.line_len(buffer_row) == 0
11405 }
11406
11407 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11408 let (path, selection, repo) = maybe!({
11409 let project_handle = self.project.as_ref()?.clone();
11410 let project = project_handle.read(cx);
11411
11412 let selection = self.selections.newest::<Point>(cx);
11413 let selection_range = selection.range();
11414
11415 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11416 (buffer, selection_range.start.row..selection_range.end.row)
11417 } else {
11418 let buffer_ranges = self
11419 .buffer()
11420 .read(cx)
11421 .range_to_buffer_ranges(selection_range, cx);
11422
11423 let (buffer, range, _) = if selection.reversed {
11424 buffer_ranges.first()
11425 } else {
11426 buffer_ranges.last()
11427 }?;
11428
11429 let snapshot = buffer.read(cx).snapshot();
11430 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11431 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11432 (buffer.clone(), selection)
11433 };
11434
11435 let path = buffer
11436 .read(cx)
11437 .file()?
11438 .as_local()?
11439 .path()
11440 .to_str()?
11441 .to_string();
11442 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11443 Some((path, selection, repo))
11444 })
11445 .ok_or_else(|| anyhow!("unable to open git repository"))?;
11446
11447 const REMOTE_NAME: &str = "origin";
11448 let origin_url = repo
11449 .remote_url(REMOTE_NAME)
11450 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11451 let sha = repo
11452 .head_sha()
11453 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11454
11455 let (provider, remote) =
11456 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11457 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11458
11459 Ok(provider.build_permalink(
11460 remote,
11461 BuildPermalinkParams {
11462 sha: &sha,
11463 path: &path,
11464 selection: Some(selection),
11465 },
11466 ))
11467 }
11468
11469 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11470 let permalink = self.get_permalink_to_line(cx);
11471
11472 match permalink {
11473 Ok(permalink) => {
11474 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11475 }
11476 Err(err) => {
11477 let message = format!("Failed to copy permalink: {err}");
11478
11479 Err::<(), anyhow::Error>(err).log_err();
11480
11481 if let Some(workspace) = self.workspace() {
11482 workspace.update(cx, |workspace, cx| {
11483 struct CopyPermalinkToLine;
11484
11485 workspace.show_toast(
11486 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11487 cx,
11488 )
11489 })
11490 }
11491 }
11492 }
11493 }
11494
11495 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11496 if let Some(file) = self.target_file(cx) {
11497 if let Some(path) = file.path().to_str() {
11498 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11499 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11500 }
11501 }
11502 }
11503
11504 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11505 let permalink = self.get_permalink_to_line(cx);
11506
11507 match permalink {
11508 Ok(permalink) => {
11509 cx.open_url(permalink.as_ref());
11510 }
11511 Err(err) => {
11512 let message = format!("Failed to open permalink: {err}");
11513
11514 Err::<(), anyhow::Error>(err).log_err();
11515
11516 if let Some(workspace) = self.workspace() {
11517 workspace.update(cx, |workspace, cx| {
11518 struct OpenPermalinkToLine;
11519
11520 workspace.show_toast(
11521 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11522 cx,
11523 )
11524 })
11525 }
11526 }
11527 }
11528 }
11529
11530 /// Adds a row highlight for the given range. If a row has multiple highlights, the
11531 /// last highlight added will be used.
11532 ///
11533 /// If the range ends at the beginning of a line, then that line will not be highlighted.
11534 pub fn highlight_rows<T: 'static>(
11535 &mut self,
11536 range: Range<Anchor>,
11537 color: Hsla,
11538 should_autoscroll: bool,
11539 cx: &mut ViewContext<Self>,
11540 ) {
11541 let snapshot = self.buffer().read(cx).snapshot(cx);
11542 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11543 let ix = row_highlights.binary_search_by(|highlight| {
11544 Ordering::Equal
11545 .then_with(|| highlight.range.start.cmp(&range.start, &snapshot))
11546 .then_with(|| highlight.range.end.cmp(&range.end, &snapshot))
11547 });
11548
11549 if let Err(mut ix) = ix {
11550 let index = post_inc(&mut self.highlight_order);
11551
11552 // If this range intersects with the preceding highlight, then merge it with
11553 // the preceding highlight. Otherwise insert a new highlight.
11554 let mut merged = false;
11555 if ix > 0 {
11556 let prev_highlight = &mut row_highlights[ix - 1];
11557 if prev_highlight
11558 .range
11559 .end
11560 .cmp(&range.start, &snapshot)
11561 .is_ge()
11562 {
11563 ix -= 1;
11564 if prev_highlight.range.end.cmp(&range.end, &snapshot).is_lt() {
11565 prev_highlight.range.end = range.end;
11566 }
11567 merged = true;
11568 prev_highlight.index = index;
11569 prev_highlight.color = color;
11570 prev_highlight.should_autoscroll = should_autoscroll;
11571 }
11572 }
11573
11574 if !merged {
11575 row_highlights.insert(
11576 ix,
11577 RowHighlight {
11578 range: range.clone(),
11579 index,
11580 color,
11581 should_autoscroll,
11582 },
11583 );
11584 }
11585
11586 // If any of the following highlights intersect with this one, merge them.
11587 while let Some(next_highlight) = row_highlights.get(ix + 1) {
11588 let highlight = &row_highlights[ix];
11589 if next_highlight
11590 .range
11591 .start
11592 .cmp(&highlight.range.end, &snapshot)
11593 .is_le()
11594 {
11595 if next_highlight
11596 .range
11597 .end
11598 .cmp(&highlight.range.end, &snapshot)
11599 .is_gt()
11600 {
11601 row_highlights[ix].range.end = next_highlight.range.end;
11602 }
11603 row_highlights.remove(ix + 1);
11604 } else {
11605 break;
11606 }
11607 }
11608 }
11609 }
11610
11611 /// Remove any highlighted row ranges of the given type that intersect the
11612 /// given ranges.
11613 pub fn remove_highlighted_rows<T: 'static>(
11614 &mut self,
11615 ranges_to_remove: Vec<Range<Anchor>>,
11616 cx: &mut ViewContext<Self>,
11617 ) {
11618 let snapshot = self.buffer().read(cx).snapshot(cx);
11619 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11620 let mut ranges_to_remove = ranges_to_remove.iter().peekable();
11621 row_highlights.retain(|highlight| {
11622 while let Some(range_to_remove) = ranges_to_remove.peek() {
11623 match range_to_remove.end.cmp(&highlight.range.start, &snapshot) {
11624 Ordering::Less | Ordering::Equal => {
11625 ranges_to_remove.next();
11626 }
11627 Ordering::Greater => {
11628 match range_to_remove.start.cmp(&highlight.range.end, &snapshot) {
11629 Ordering::Less | Ordering::Equal => {
11630 return false;
11631 }
11632 Ordering::Greater => break,
11633 }
11634 }
11635 }
11636 }
11637
11638 true
11639 })
11640 }
11641
11642 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11643 pub fn clear_row_highlights<T: 'static>(&mut self) {
11644 self.highlighted_rows.remove(&TypeId::of::<T>());
11645 }
11646
11647 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11648 pub fn highlighted_rows<T: 'static>(&self) -> impl '_ + Iterator<Item = (Range<Anchor>, Hsla)> {
11649 self.highlighted_rows
11650 .get(&TypeId::of::<T>())
11651 .map_or(&[] as &[_], |vec| vec.as_slice())
11652 .iter()
11653 .map(|highlight| (highlight.range.clone(), highlight.color))
11654 }
11655
11656 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11657 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11658 /// Allows to ignore certain kinds of highlights.
11659 pub fn highlighted_display_rows(
11660 &mut self,
11661 cx: &mut WindowContext,
11662 ) -> BTreeMap<DisplayRow, Hsla> {
11663 let snapshot = self.snapshot(cx);
11664 let mut used_highlight_orders = HashMap::default();
11665 self.highlighted_rows
11666 .iter()
11667 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11668 .fold(
11669 BTreeMap::<DisplayRow, Hsla>::new(),
11670 |mut unique_rows, highlight| {
11671 let start = highlight.range.start.to_display_point(&snapshot);
11672 let end = highlight.range.end.to_display_point(&snapshot);
11673 let start_row = start.row().0;
11674 let end_row = if highlight.range.end.text_anchor != text::Anchor::MAX
11675 && end.column() == 0
11676 {
11677 end.row().0.saturating_sub(1)
11678 } else {
11679 end.row().0
11680 };
11681 for row in start_row..=end_row {
11682 let used_index =
11683 used_highlight_orders.entry(row).or_insert(highlight.index);
11684 if highlight.index >= *used_index {
11685 *used_index = highlight.index;
11686 unique_rows.insert(DisplayRow(row), highlight.color);
11687 }
11688 }
11689 unique_rows
11690 },
11691 )
11692 }
11693
11694 pub fn highlighted_display_row_for_autoscroll(
11695 &self,
11696 snapshot: &DisplaySnapshot,
11697 ) -> Option<DisplayRow> {
11698 self.highlighted_rows
11699 .values()
11700 .flat_map(|highlighted_rows| highlighted_rows.iter())
11701 .filter_map(|highlight| {
11702 if highlight.should_autoscroll {
11703 Some(highlight.range.start.to_display_point(snapshot).row())
11704 } else {
11705 None
11706 }
11707 })
11708 .min()
11709 }
11710
11711 pub fn set_search_within_ranges(
11712 &mut self,
11713 ranges: &[Range<Anchor>],
11714 cx: &mut ViewContext<Self>,
11715 ) {
11716 self.highlight_background::<SearchWithinRange>(
11717 ranges,
11718 |colors| colors.editor_document_highlight_read_background,
11719 cx,
11720 )
11721 }
11722
11723 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11724 self.breadcrumb_header = Some(new_header);
11725 }
11726
11727 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11728 self.clear_background_highlights::<SearchWithinRange>(cx);
11729 }
11730
11731 pub fn highlight_background<T: 'static>(
11732 &mut self,
11733 ranges: &[Range<Anchor>],
11734 color_fetcher: fn(&ThemeColors) -> Hsla,
11735 cx: &mut ViewContext<Self>,
11736 ) {
11737 self.background_highlights
11738 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11739 self.scrollbar_marker_state.dirty = true;
11740 cx.notify();
11741 }
11742
11743 pub fn clear_background_highlights<T: 'static>(
11744 &mut self,
11745 cx: &mut ViewContext<Self>,
11746 ) -> Option<BackgroundHighlight> {
11747 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11748 if !text_highlights.1.is_empty() {
11749 self.scrollbar_marker_state.dirty = true;
11750 cx.notify();
11751 }
11752 Some(text_highlights)
11753 }
11754
11755 pub fn highlight_gutter<T: 'static>(
11756 &mut self,
11757 ranges: &[Range<Anchor>],
11758 color_fetcher: fn(&AppContext) -> Hsla,
11759 cx: &mut ViewContext<Self>,
11760 ) {
11761 self.gutter_highlights
11762 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11763 cx.notify();
11764 }
11765
11766 pub fn clear_gutter_highlights<T: 'static>(
11767 &mut self,
11768 cx: &mut ViewContext<Self>,
11769 ) -> Option<GutterHighlight> {
11770 cx.notify();
11771 self.gutter_highlights.remove(&TypeId::of::<T>())
11772 }
11773
11774 #[cfg(feature = "test-support")]
11775 pub fn all_text_background_highlights(
11776 &mut self,
11777 cx: &mut ViewContext<Self>,
11778 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11779 let snapshot = self.snapshot(cx);
11780 let buffer = &snapshot.buffer_snapshot;
11781 let start = buffer.anchor_before(0);
11782 let end = buffer.anchor_after(buffer.len());
11783 let theme = cx.theme().colors();
11784 self.background_highlights_in_range(start..end, &snapshot, theme)
11785 }
11786
11787 #[cfg(feature = "test-support")]
11788 pub fn search_background_highlights(
11789 &mut self,
11790 cx: &mut ViewContext<Self>,
11791 ) -> Vec<Range<Point>> {
11792 let snapshot = self.buffer().read(cx).snapshot(cx);
11793
11794 let highlights = self
11795 .background_highlights
11796 .get(&TypeId::of::<items::BufferSearchHighlights>());
11797
11798 if let Some((_color, ranges)) = highlights {
11799 ranges
11800 .iter()
11801 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11802 .collect_vec()
11803 } else {
11804 vec![]
11805 }
11806 }
11807
11808 fn document_highlights_for_position<'a>(
11809 &'a self,
11810 position: Anchor,
11811 buffer: &'a MultiBufferSnapshot,
11812 ) -> impl 'a + Iterator<Item = &'a Range<Anchor>> {
11813 let read_highlights = self
11814 .background_highlights
11815 .get(&TypeId::of::<DocumentHighlightRead>())
11816 .map(|h| &h.1);
11817 let write_highlights = self
11818 .background_highlights
11819 .get(&TypeId::of::<DocumentHighlightWrite>())
11820 .map(|h| &h.1);
11821 let left_position = position.bias_left(buffer);
11822 let right_position = position.bias_right(buffer);
11823 read_highlights
11824 .into_iter()
11825 .chain(write_highlights)
11826 .flat_map(move |ranges| {
11827 let start_ix = match ranges.binary_search_by(|probe| {
11828 let cmp = probe.end.cmp(&left_position, buffer);
11829 if cmp.is_ge() {
11830 Ordering::Greater
11831 } else {
11832 Ordering::Less
11833 }
11834 }) {
11835 Ok(i) | Err(i) => i,
11836 };
11837
11838 ranges[start_ix..]
11839 .iter()
11840 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11841 })
11842 }
11843
11844 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11845 self.background_highlights
11846 .get(&TypeId::of::<T>())
11847 .map_or(false, |(_, highlights)| !highlights.is_empty())
11848 }
11849
11850 pub fn background_highlights_in_range(
11851 &self,
11852 search_range: Range<Anchor>,
11853 display_snapshot: &DisplaySnapshot,
11854 theme: &ThemeColors,
11855 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11856 let mut results = Vec::new();
11857 for (color_fetcher, ranges) in self.background_highlights.values() {
11858 let color = color_fetcher(theme);
11859 let start_ix = match ranges.binary_search_by(|probe| {
11860 let cmp = probe
11861 .end
11862 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11863 if cmp.is_gt() {
11864 Ordering::Greater
11865 } else {
11866 Ordering::Less
11867 }
11868 }) {
11869 Ok(i) | Err(i) => i,
11870 };
11871 for range in &ranges[start_ix..] {
11872 if range
11873 .start
11874 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11875 .is_ge()
11876 {
11877 break;
11878 }
11879
11880 let start = range.start.to_display_point(display_snapshot);
11881 let end = range.end.to_display_point(display_snapshot);
11882 results.push((start..end, color))
11883 }
11884 }
11885 results
11886 }
11887
11888 pub fn background_highlight_row_ranges<T: 'static>(
11889 &self,
11890 search_range: Range<Anchor>,
11891 display_snapshot: &DisplaySnapshot,
11892 count: usize,
11893 ) -> Vec<RangeInclusive<DisplayPoint>> {
11894 let mut results = Vec::new();
11895 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11896 return vec![];
11897 };
11898
11899 let start_ix = match ranges.binary_search_by(|probe| {
11900 let cmp = probe
11901 .end
11902 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11903 if cmp.is_gt() {
11904 Ordering::Greater
11905 } else {
11906 Ordering::Less
11907 }
11908 }) {
11909 Ok(i) | Err(i) => i,
11910 };
11911 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11912 if let (Some(start_display), Some(end_display)) = (start, end) {
11913 results.push(
11914 start_display.to_display_point(display_snapshot)
11915 ..=end_display.to_display_point(display_snapshot),
11916 );
11917 }
11918 };
11919 let mut start_row: Option<Point> = None;
11920 let mut end_row: Option<Point> = None;
11921 if ranges.len() > count {
11922 return Vec::new();
11923 }
11924 for range in &ranges[start_ix..] {
11925 if range
11926 .start
11927 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11928 .is_ge()
11929 {
11930 break;
11931 }
11932 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11933 if let Some(current_row) = &end_row {
11934 if end.row == current_row.row {
11935 continue;
11936 }
11937 }
11938 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11939 if start_row.is_none() {
11940 assert_eq!(end_row, None);
11941 start_row = Some(start);
11942 end_row = Some(end);
11943 continue;
11944 }
11945 if let Some(current_end) = end_row.as_mut() {
11946 if start.row > current_end.row + 1 {
11947 push_region(start_row, end_row);
11948 start_row = Some(start);
11949 end_row = Some(end);
11950 } else {
11951 // Merge two hunks.
11952 *current_end = end;
11953 }
11954 } else {
11955 unreachable!();
11956 }
11957 }
11958 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11959 push_region(start_row, end_row);
11960 results
11961 }
11962
11963 pub fn gutter_highlights_in_range(
11964 &self,
11965 search_range: Range<Anchor>,
11966 display_snapshot: &DisplaySnapshot,
11967 cx: &AppContext,
11968 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11969 let mut results = Vec::new();
11970 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11971 let color = color_fetcher(cx);
11972 let start_ix = match ranges.binary_search_by(|probe| {
11973 let cmp = probe
11974 .end
11975 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11976 if cmp.is_gt() {
11977 Ordering::Greater
11978 } else {
11979 Ordering::Less
11980 }
11981 }) {
11982 Ok(i) | Err(i) => i,
11983 };
11984 for range in &ranges[start_ix..] {
11985 if range
11986 .start
11987 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11988 .is_ge()
11989 {
11990 break;
11991 }
11992
11993 let start = range.start.to_display_point(display_snapshot);
11994 let end = range.end.to_display_point(display_snapshot);
11995 results.push((start..end, color))
11996 }
11997 }
11998 results
11999 }
12000
12001 /// Get the text ranges corresponding to the redaction query
12002 pub fn redacted_ranges(
12003 &self,
12004 search_range: Range<Anchor>,
12005 display_snapshot: &DisplaySnapshot,
12006 cx: &WindowContext,
12007 ) -> Vec<Range<DisplayPoint>> {
12008 display_snapshot
12009 .buffer_snapshot
12010 .redacted_ranges(search_range, |file| {
12011 if let Some(file) = file {
12012 file.is_private()
12013 && EditorSettings::get(
12014 Some(SettingsLocation {
12015 worktree_id: file.worktree_id(cx),
12016 path: file.path().as_ref(),
12017 }),
12018 cx,
12019 )
12020 .redact_private_values
12021 } else {
12022 false
12023 }
12024 })
12025 .map(|range| {
12026 range.start.to_display_point(display_snapshot)
12027 ..range.end.to_display_point(display_snapshot)
12028 })
12029 .collect()
12030 }
12031
12032 pub fn highlight_text<T: 'static>(
12033 &mut self,
12034 ranges: Vec<Range<Anchor>>,
12035 style: HighlightStyle,
12036 cx: &mut ViewContext<Self>,
12037 ) {
12038 self.display_map.update(cx, |map, _| {
12039 map.highlight_text(TypeId::of::<T>(), ranges, style)
12040 });
12041 cx.notify();
12042 }
12043
12044 pub(crate) fn highlight_inlays<T: 'static>(
12045 &mut self,
12046 highlights: Vec<InlayHighlight>,
12047 style: HighlightStyle,
12048 cx: &mut ViewContext<Self>,
12049 ) {
12050 self.display_map.update(cx, |map, _| {
12051 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
12052 });
12053 cx.notify();
12054 }
12055
12056 pub fn text_highlights<'a, T: 'static>(
12057 &'a self,
12058 cx: &'a AppContext,
12059 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
12060 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
12061 }
12062
12063 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
12064 let cleared = self
12065 .display_map
12066 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
12067 if cleared {
12068 cx.notify();
12069 }
12070 }
12071
12072 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
12073 (self.read_only(cx) || self.blink_manager.read(cx).visible())
12074 && self.focus_handle.is_focused(cx)
12075 }
12076
12077 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
12078 self.show_cursor_when_unfocused = is_enabled;
12079 cx.notify();
12080 }
12081
12082 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
12083 cx.notify();
12084 }
12085
12086 fn on_buffer_event(
12087 &mut self,
12088 multibuffer: Model<MultiBuffer>,
12089 event: &multi_buffer::Event,
12090 cx: &mut ViewContext<Self>,
12091 ) {
12092 match event {
12093 multi_buffer::Event::Edited {
12094 singleton_buffer_edited,
12095 } => {
12096 self.scrollbar_marker_state.dirty = true;
12097 self.active_indent_guides_state.dirty = true;
12098 self.refresh_active_diagnostics(cx);
12099 self.refresh_code_actions(cx);
12100 if self.has_active_inline_completion(cx) {
12101 self.update_visible_inline_completion(cx);
12102 }
12103 cx.emit(EditorEvent::BufferEdited);
12104 cx.emit(SearchEvent::MatchesInvalidated);
12105 if *singleton_buffer_edited {
12106 if let Some(project) = &self.project {
12107 let project = project.read(cx);
12108 #[allow(clippy::mutable_key_type)]
12109 let languages_affected = multibuffer
12110 .read(cx)
12111 .all_buffers()
12112 .into_iter()
12113 .filter_map(|buffer| {
12114 let buffer = buffer.read(cx);
12115 let language = buffer.language()?;
12116 if project.is_local()
12117 && project.language_servers_for_buffer(buffer, cx).count() == 0
12118 {
12119 None
12120 } else {
12121 Some(language)
12122 }
12123 })
12124 .cloned()
12125 .collect::<HashSet<_>>();
12126 if !languages_affected.is_empty() {
12127 self.refresh_inlay_hints(
12128 InlayHintRefreshReason::BufferEdited(languages_affected),
12129 cx,
12130 );
12131 }
12132 }
12133 }
12134
12135 let Some(project) = &self.project else { return };
12136 let telemetry = project.read(cx).client().telemetry().clone();
12137 refresh_linked_ranges(self, cx);
12138 telemetry.log_edit_event("editor");
12139 }
12140 multi_buffer::Event::ExcerptsAdded {
12141 buffer,
12142 predecessor,
12143 excerpts,
12144 } => {
12145 self.tasks_update_task = Some(self.refresh_runnables(cx));
12146 cx.emit(EditorEvent::ExcerptsAdded {
12147 buffer: buffer.clone(),
12148 predecessor: *predecessor,
12149 excerpts: excerpts.clone(),
12150 });
12151 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
12152 }
12153 multi_buffer::Event::ExcerptsRemoved { ids } => {
12154 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
12155 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
12156 }
12157 multi_buffer::Event::ExcerptsEdited { ids } => {
12158 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
12159 }
12160 multi_buffer::Event::ExcerptsExpanded { ids } => {
12161 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
12162 }
12163 multi_buffer::Event::Reparsed(buffer_id) => {
12164 self.tasks_update_task = Some(self.refresh_runnables(cx));
12165
12166 cx.emit(EditorEvent::Reparsed(*buffer_id));
12167 }
12168 multi_buffer::Event::LanguageChanged(buffer_id) => {
12169 linked_editing_ranges::refresh_linked_ranges(self, cx);
12170 cx.emit(EditorEvent::Reparsed(*buffer_id));
12171 cx.notify();
12172 }
12173 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
12174 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
12175 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
12176 cx.emit(EditorEvent::TitleChanged)
12177 }
12178 multi_buffer::Event::DiffBaseChanged => {
12179 self.scrollbar_marker_state.dirty = true;
12180 cx.emit(EditorEvent::DiffBaseChanged);
12181 cx.notify();
12182 }
12183 multi_buffer::Event::DiffUpdated { buffer } => {
12184 self.sync_expanded_diff_hunks(buffer.clone(), cx);
12185 cx.notify();
12186 }
12187 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
12188 multi_buffer::Event::DiagnosticsUpdated => {
12189 self.refresh_active_diagnostics(cx);
12190 self.scrollbar_marker_state.dirty = true;
12191 cx.notify();
12192 }
12193 _ => {}
12194 };
12195 }
12196
12197 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
12198 cx.notify();
12199 }
12200
12201 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
12202 self.tasks_update_task = Some(self.refresh_runnables(cx));
12203 self.refresh_inline_completion(true, false, cx);
12204 self.refresh_inlay_hints(
12205 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
12206 self.selections.newest_anchor().head(),
12207 &self.buffer.read(cx).snapshot(cx),
12208 cx,
12209 )),
12210 cx,
12211 );
12212
12213 let old_cursor_shape = self.cursor_shape;
12214
12215 {
12216 let editor_settings = EditorSettings::get_global(cx);
12217 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
12218 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
12219 self.cursor_shape = editor_settings.cursor_shape.unwrap_or_default();
12220 }
12221
12222 if old_cursor_shape != self.cursor_shape {
12223 cx.emit(EditorEvent::CursorShapeChanged);
12224 }
12225
12226 let project_settings = ProjectSettings::get_global(cx);
12227 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
12228
12229 if self.mode == EditorMode::Full {
12230 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
12231 if self.git_blame_inline_enabled != inline_blame_enabled {
12232 self.toggle_git_blame_inline_internal(false, cx);
12233 }
12234 }
12235
12236 cx.notify();
12237 }
12238
12239 pub fn set_searchable(&mut self, searchable: bool) {
12240 self.searchable = searchable;
12241 }
12242
12243 pub fn searchable(&self) -> bool {
12244 self.searchable
12245 }
12246
12247 fn open_proposed_changes_editor(
12248 &mut self,
12249 _: &OpenProposedChangesEditor,
12250 cx: &mut ViewContext<Self>,
12251 ) {
12252 let Some(workspace) = self.workspace() else {
12253 cx.propagate();
12254 return;
12255 };
12256
12257 let buffer = self.buffer.read(cx);
12258 let mut new_selections_by_buffer = HashMap::default();
12259 for selection in self.selections.all::<usize>(cx) {
12260 for (buffer, range, _) in
12261 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12262 {
12263 let mut range = range.to_point(buffer.read(cx));
12264 range.start.column = 0;
12265 range.end.column = buffer.read(cx).line_len(range.end.row);
12266 new_selections_by_buffer
12267 .entry(buffer)
12268 .or_insert(Vec::new())
12269 .push(range)
12270 }
12271 }
12272
12273 let proposed_changes_buffers = new_selections_by_buffer
12274 .into_iter()
12275 .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
12276 .collect::<Vec<_>>();
12277 let proposed_changes_editor = cx.new_view(|cx| {
12278 ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
12279 });
12280
12281 cx.window_context().defer(move |cx| {
12282 workspace.update(cx, |workspace, cx| {
12283 workspace.active_pane().update(cx, |pane, cx| {
12284 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
12285 });
12286 });
12287 });
12288 }
12289
12290 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
12291 self.open_excerpts_common(true, cx)
12292 }
12293
12294 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
12295 self.open_excerpts_common(false, cx)
12296 }
12297
12298 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
12299 let buffer = self.buffer.read(cx);
12300 if buffer.is_singleton() {
12301 cx.propagate();
12302 return;
12303 }
12304
12305 let Some(workspace) = self.workspace() else {
12306 cx.propagate();
12307 return;
12308 };
12309
12310 let mut new_selections_by_buffer = HashMap::default();
12311 for selection in self.selections.all::<usize>(cx) {
12312 for (buffer, mut range, _) in
12313 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
12314 {
12315 if selection.reversed {
12316 mem::swap(&mut range.start, &mut range.end);
12317 }
12318 new_selections_by_buffer
12319 .entry(buffer)
12320 .or_insert(Vec::new())
12321 .push(range)
12322 }
12323 }
12324
12325 // We defer the pane interaction because we ourselves are a workspace item
12326 // and activating a new item causes the pane to call a method on us reentrantly,
12327 // which panics if we're on the stack.
12328 cx.window_context().defer(move |cx| {
12329 workspace.update(cx, |workspace, cx| {
12330 let pane = if split {
12331 workspace.adjacent_pane(cx)
12332 } else {
12333 workspace.active_pane().clone()
12334 };
12335
12336 for (buffer, ranges) in new_selections_by_buffer {
12337 let editor =
12338 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
12339 editor.update(cx, |editor, cx| {
12340 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
12341 s.select_ranges(ranges);
12342 });
12343 });
12344 }
12345 })
12346 });
12347 }
12348
12349 fn jump(
12350 &mut self,
12351 path: ProjectPath,
12352 position: Point,
12353 anchor: language::Anchor,
12354 offset_from_top: u32,
12355 cx: &mut ViewContext<Self>,
12356 ) {
12357 let workspace = self.workspace();
12358 cx.spawn(|_, mut cx| async move {
12359 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12360 let editor = workspace.update(&mut cx, |workspace, cx| {
12361 // Reset the preview item id before opening the new item
12362 workspace.active_pane().update(cx, |pane, cx| {
12363 pane.set_preview_item_id(None, cx);
12364 });
12365 workspace.open_path_preview(path, None, true, true, cx)
12366 })?;
12367 let editor = editor
12368 .await?
12369 .downcast::<Editor>()
12370 .ok_or_else(|| anyhow!("opened item was not an editor"))?
12371 .downgrade();
12372 editor.update(&mut cx, |editor, cx| {
12373 let buffer = editor
12374 .buffer()
12375 .read(cx)
12376 .as_singleton()
12377 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12378 let buffer = buffer.read(cx);
12379 let cursor = if buffer.can_resolve(&anchor) {
12380 language::ToPoint::to_point(&anchor, buffer)
12381 } else {
12382 buffer.clip_point(position, Bias::Left)
12383 };
12384
12385 let nav_history = editor.nav_history.take();
12386 editor.change_selections(
12387 Some(Autoscroll::top_relative(offset_from_top as usize)),
12388 cx,
12389 |s| {
12390 s.select_ranges([cursor..cursor]);
12391 },
12392 );
12393 editor.nav_history = nav_history;
12394
12395 anyhow::Ok(())
12396 })??;
12397
12398 anyhow::Ok(())
12399 })
12400 .detach_and_log_err(cx);
12401 }
12402
12403 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12404 let snapshot = self.buffer.read(cx).read(cx);
12405 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12406 Some(
12407 ranges
12408 .iter()
12409 .map(move |range| {
12410 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12411 })
12412 .collect(),
12413 )
12414 }
12415
12416 fn selection_replacement_ranges(
12417 &self,
12418 range: Range<OffsetUtf16>,
12419 cx: &AppContext,
12420 ) -> Vec<Range<OffsetUtf16>> {
12421 let selections = self.selections.all::<OffsetUtf16>(cx);
12422 let newest_selection = selections
12423 .iter()
12424 .max_by_key(|selection| selection.id)
12425 .unwrap();
12426 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12427 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12428 let snapshot = self.buffer.read(cx).read(cx);
12429 selections
12430 .into_iter()
12431 .map(|mut selection| {
12432 selection.start.0 =
12433 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12434 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12435 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12436 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12437 })
12438 .collect()
12439 }
12440
12441 fn report_editor_event(
12442 &self,
12443 operation: &'static str,
12444 file_extension: Option<String>,
12445 cx: &AppContext,
12446 ) {
12447 if cfg!(any(test, feature = "test-support")) {
12448 return;
12449 }
12450
12451 let Some(project) = &self.project else { return };
12452
12453 // If None, we are in a file without an extension
12454 let file = self
12455 .buffer
12456 .read(cx)
12457 .as_singleton()
12458 .and_then(|b| b.read(cx).file());
12459 let file_extension = file_extension.or(file
12460 .as_ref()
12461 .and_then(|file| Path::new(file.file_name(cx)).extension())
12462 .and_then(|e| e.to_str())
12463 .map(|a| a.to_string()));
12464
12465 let vim_mode = cx
12466 .global::<SettingsStore>()
12467 .raw_user_settings()
12468 .get("vim_mode")
12469 == Some(&serde_json::Value::Bool(true));
12470
12471 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12472 == language::language_settings::InlineCompletionProvider::Copilot;
12473 let copilot_enabled_for_language = self
12474 .buffer
12475 .read(cx)
12476 .settings_at(0, cx)
12477 .show_inline_completions;
12478
12479 let telemetry = project.read(cx).client().telemetry().clone();
12480 telemetry.report_editor_event(
12481 file_extension,
12482 vim_mode,
12483 operation,
12484 copilot_enabled,
12485 copilot_enabled_for_language,
12486 )
12487 }
12488
12489 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12490 /// with each line being an array of {text, highlight} objects.
12491 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12492 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12493 return;
12494 };
12495
12496 #[derive(Serialize)]
12497 struct Chunk<'a> {
12498 text: String,
12499 highlight: Option<&'a str>,
12500 }
12501
12502 let snapshot = buffer.read(cx).snapshot();
12503 let range = self
12504 .selected_text_range(false, cx)
12505 .and_then(|selection| {
12506 if selection.range.is_empty() {
12507 None
12508 } else {
12509 Some(selection.range)
12510 }
12511 })
12512 .unwrap_or_else(|| 0..snapshot.len());
12513
12514 let chunks = snapshot.chunks(range, true);
12515 let mut lines = Vec::new();
12516 let mut line: VecDeque<Chunk> = VecDeque::new();
12517
12518 let Some(style) = self.style.as_ref() else {
12519 return;
12520 };
12521
12522 for chunk in chunks {
12523 let highlight = chunk
12524 .syntax_highlight_id
12525 .and_then(|id| id.name(&style.syntax));
12526 let mut chunk_lines = chunk.text.split('\n').peekable();
12527 while let Some(text) = chunk_lines.next() {
12528 let mut merged_with_last_token = false;
12529 if let Some(last_token) = line.back_mut() {
12530 if last_token.highlight == highlight {
12531 last_token.text.push_str(text);
12532 merged_with_last_token = true;
12533 }
12534 }
12535
12536 if !merged_with_last_token {
12537 line.push_back(Chunk {
12538 text: text.into(),
12539 highlight,
12540 });
12541 }
12542
12543 if chunk_lines.peek().is_some() {
12544 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12545 line.pop_front();
12546 }
12547 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12548 line.pop_back();
12549 }
12550
12551 lines.push(mem::take(&mut line));
12552 }
12553 }
12554 }
12555
12556 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12557 return;
12558 };
12559 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12560 }
12561
12562 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12563 &self.inlay_hint_cache
12564 }
12565
12566 pub fn replay_insert_event(
12567 &mut self,
12568 text: &str,
12569 relative_utf16_range: Option<Range<isize>>,
12570 cx: &mut ViewContext<Self>,
12571 ) {
12572 if !self.input_enabled {
12573 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12574 return;
12575 }
12576 if let Some(relative_utf16_range) = relative_utf16_range {
12577 let selections = self.selections.all::<OffsetUtf16>(cx);
12578 self.change_selections(None, cx, |s| {
12579 let new_ranges = selections.into_iter().map(|range| {
12580 let start = OffsetUtf16(
12581 range
12582 .head()
12583 .0
12584 .saturating_add_signed(relative_utf16_range.start),
12585 );
12586 let end = OffsetUtf16(
12587 range
12588 .head()
12589 .0
12590 .saturating_add_signed(relative_utf16_range.end),
12591 );
12592 start..end
12593 });
12594 s.select_ranges(new_ranges);
12595 });
12596 }
12597
12598 self.handle_input(text, cx);
12599 }
12600
12601 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12602 let Some(project) = self.project.as_ref() else {
12603 return false;
12604 };
12605 let project = project.read(cx);
12606
12607 let mut supports = false;
12608 self.buffer().read(cx).for_each_buffer(|buffer| {
12609 if !supports {
12610 supports = project
12611 .language_servers_for_buffer(buffer.read(cx), cx)
12612 .any(
12613 |(_, server)| match server.capabilities().inlay_hint_provider {
12614 Some(lsp::OneOf::Left(enabled)) => enabled,
12615 Some(lsp::OneOf::Right(_)) => true,
12616 None => false,
12617 },
12618 )
12619 }
12620 });
12621 supports
12622 }
12623
12624 pub fn focus(&self, cx: &mut WindowContext) {
12625 cx.focus(&self.focus_handle)
12626 }
12627
12628 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12629 self.focus_handle.is_focused(cx)
12630 }
12631
12632 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12633 cx.emit(EditorEvent::Focused);
12634
12635 if let Some(descendant) = self
12636 .last_focused_descendant
12637 .take()
12638 .and_then(|descendant| descendant.upgrade())
12639 {
12640 cx.focus(&descendant);
12641 } else {
12642 if let Some(blame) = self.blame.as_ref() {
12643 blame.update(cx, GitBlame::focus)
12644 }
12645
12646 self.blink_manager.update(cx, BlinkManager::enable);
12647 self.show_cursor_names(cx);
12648 self.buffer.update(cx, |buffer, cx| {
12649 buffer.finalize_last_transaction(cx);
12650 if self.leader_peer_id.is_none() {
12651 buffer.set_active_selections(
12652 &self.selections.disjoint_anchors(),
12653 self.selections.line_mode,
12654 self.cursor_shape,
12655 cx,
12656 );
12657 }
12658 });
12659 }
12660 }
12661
12662 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12663 cx.emit(EditorEvent::FocusedIn)
12664 }
12665
12666 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12667 if event.blurred != self.focus_handle {
12668 self.last_focused_descendant = Some(event.blurred);
12669 }
12670 }
12671
12672 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12673 self.blink_manager.update(cx, BlinkManager::disable);
12674 self.buffer
12675 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12676
12677 if let Some(blame) = self.blame.as_ref() {
12678 blame.update(cx, GitBlame::blur)
12679 }
12680 if !self.hover_state.focused(cx) {
12681 hide_hover(self, cx);
12682 }
12683
12684 self.hide_context_menu(cx);
12685 cx.emit(EditorEvent::Blurred);
12686 cx.notify();
12687 }
12688
12689 pub fn register_action<A: Action>(
12690 &mut self,
12691 listener: impl Fn(&A, &mut WindowContext) + 'static,
12692 ) -> Subscription {
12693 let id = self.next_editor_action_id.post_inc();
12694 let listener = Arc::new(listener);
12695 self.editor_actions.borrow_mut().insert(
12696 id,
12697 Box::new(move |cx| {
12698 let cx = cx.window_context();
12699 let listener = listener.clone();
12700 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12701 let action = action.downcast_ref().unwrap();
12702 if phase == DispatchPhase::Bubble {
12703 listener(action, cx)
12704 }
12705 })
12706 }),
12707 );
12708
12709 let editor_actions = self.editor_actions.clone();
12710 Subscription::new(move || {
12711 editor_actions.borrow_mut().remove(&id);
12712 })
12713 }
12714
12715 pub fn file_header_size(&self) -> u32 {
12716 self.file_header_size
12717 }
12718
12719 pub fn revert(
12720 &mut self,
12721 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12722 cx: &mut ViewContext<Self>,
12723 ) {
12724 self.buffer().update(cx, |multi_buffer, cx| {
12725 for (buffer_id, changes) in revert_changes {
12726 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12727 buffer.update(cx, |buffer, cx| {
12728 buffer.edit(
12729 changes.into_iter().map(|(range, text)| {
12730 (range, text.to_string().map(Arc::<str>::from))
12731 }),
12732 None,
12733 cx,
12734 );
12735 });
12736 }
12737 }
12738 });
12739 self.change_selections(None, cx, |selections| selections.refresh());
12740 }
12741
12742 pub fn to_pixel_point(
12743 &mut self,
12744 source: multi_buffer::Anchor,
12745 editor_snapshot: &EditorSnapshot,
12746 cx: &mut ViewContext<Self>,
12747 ) -> Option<gpui::Point<Pixels>> {
12748 let source_point = source.to_display_point(editor_snapshot);
12749 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12750 }
12751
12752 pub fn display_to_pixel_point(
12753 &mut self,
12754 source: DisplayPoint,
12755 editor_snapshot: &EditorSnapshot,
12756 cx: &mut ViewContext<Self>,
12757 ) -> Option<gpui::Point<Pixels>> {
12758 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12759 let text_layout_details = self.text_layout_details(cx);
12760 let scroll_top = text_layout_details
12761 .scroll_anchor
12762 .scroll_position(editor_snapshot)
12763 .y;
12764
12765 if source.row().as_f32() < scroll_top.floor() {
12766 return None;
12767 }
12768 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12769 let source_y = line_height * (source.row().as_f32() - scroll_top);
12770 Some(gpui::Point::new(source_x, source_y))
12771 }
12772
12773 pub fn has_active_completions_menu(&self) -> bool {
12774 self.context_menu.read().as_ref().map_or(false, |menu| {
12775 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12776 })
12777 }
12778
12779 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12780 self.addons
12781 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12782 }
12783
12784 pub fn unregister_addon<T: Addon>(&mut self) {
12785 self.addons.remove(&std::any::TypeId::of::<T>());
12786 }
12787
12788 pub fn addon<T: Addon>(&self) -> Option<&T> {
12789 let type_id = std::any::TypeId::of::<T>();
12790 self.addons
12791 .get(&type_id)
12792 .and_then(|item| item.to_any().downcast_ref::<T>())
12793 }
12794}
12795
12796fn hunks_for_selections(
12797 multi_buffer_snapshot: &MultiBufferSnapshot,
12798 selections: &[Selection<Anchor>],
12799) -> Vec<MultiBufferDiffHunk> {
12800 let buffer_rows_for_selections = selections.iter().map(|selection| {
12801 let head = selection.head();
12802 let tail = selection.tail();
12803 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12804 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12805 if start > end {
12806 end..start
12807 } else {
12808 start..end
12809 }
12810 });
12811
12812 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12813}
12814
12815pub fn hunks_for_rows(
12816 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12817 multi_buffer_snapshot: &MultiBufferSnapshot,
12818) -> Vec<MultiBufferDiffHunk> {
12819 let mut hunks = Vec::new();
12820 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12821 HashMap::default();
12822 for selected_multi_buffer_rows in rows {
12823 let query_rows =
12824 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12825 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12826 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12827 // when the caret is just above or just below the deleted hunk.
12828 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12829 let related_to_selection = if allow_adjacent {
12830 hunk.row_range.overlaps(&query_rows)
12831 || hunk.row_range.start == query_rows.end
12832 || hunk.row_range.end == query_rows.start
12833 } else {
12834 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12835 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12836 hunk.row_range.overlaps(&selected_multi_buffer_rows)
12837 || selected_multi_buffer_rows.end == hunk.row_range.start
12838 };
12839 if related_to_selection {
12840 if !processed_buffer_rows
12841 .entry(hunk.buffer_id)
12842 .or_default()
12843 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12844 {
12845 continue;
12846 }
12847 hunks.push(hunk);
12848 }
12849 }
12850 }
12851
12852 hunks
12853}
12854
12855pub trait CollaborationHub {
12856 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12857 fn user_participant_indices<'a>(
12858 &self,
12859 cx: &'a AppContext,
12860 ) -> &'a HashMap<u64, ParticipantIndex>;
12861 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12862}
12863
12864impl CollaborationHub for Model<Project> {
12865 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12866 self.read(cx).collaborators()
12867 }
12868
12869 fn user_participant_indices<'a>(
12870 &self,
12871 cx: &'a AppContext,
12872 ) -> &'a HashMap<u64, ParticipantIndex> {
12873 self.read(cx).user_store().read(cx).participant_indices()
12874 }
12875
12876 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12877 let this = self.read(cx);
12878 let user_ids = this.collaborators().values().map(|c| c.user_id);
12879 this.user_store().read_with(cx, |user_store, cx| {
12880 user_store.participant_names(user_ids, cx)
12881 })
12882 }
12883}
12884
12885pub trait CompletionProvider {
12886 fn completions(
12887 &self,
12888 buffer: &Model<Buffer>,
12889 buffer_position: text::Anchor,
12890 trigger: CompletionContext,
12891 cx: &mut ViewContext<Editor>,
12892 ) -> Task<Result<Vec<Completion>>>;
12893
12894 fn resolve_completions(
12895 &self,
12896 buffer: Model<Buffer>,
12897 completion_indices: Vec<usize>,
12898 completions: Arc<RwLock<Box<[Completion]>>>,
12899 cx: &mut ViewContext<Editor>,
12900 ) -> Task<Result<bool>>;
12901
12902 fn apply_additional_edits_for_completion(
12903 &self,
12904 buffer: Model<Buffer>,
12905 completion: Completion,
12906 push_to_history: bool,
12907 cx: &mut ViewContext<Editor>,
12908 ) -> Task<Result<Option<language::Transaction>>>;
12909
12910 fn is_completion_trigger(
12911 &self,
12912 buffer: &Model<Buffer>,
12913 position: language::Anchor,
12914 text: &str,
12915 trigger_in_words: bool,
12916 cx: &mut ViewContext<Editor>,
12917 ) -> bool;
12918
12919 fn sort_completions(&self) -> bool {
12920 true
12921 }
12922}
12923
12924pub trait CodeActionProvider {
12925 fn code_actions(
12926 &self,
12927 buffer: &Model<Buffer>,
12928 range: Range<text::Anchor>,
12929 cx: &mut WindowContext,
12930 ) -> Task<Result<Vec<CodeAction>>>;
12931
12932 fn apply_code_action(
12933 &self,
12934 buffer_handle: Model<Buffer>,
12935 action: CodeAction,
12936 excerpt_id: ExcerptId,
12937 push_to_history: bool,
12938 cx: &mut WindowContext,
12939 ) -> Task<Result<ProjectTransaction>>;
12940}
12941
12942impl CodeActionProvider for Model<Project> {
12943 fn code_actions(
12944 &self,
12945 buffer: &Model<Buffer>,
12946 range: Range<text::Anchor>,
12947 cx: &mut WindowContext,
12948 ) -> Task<Result<Vec<CodeAction>>> {
12949 self.update(cx, |project, cx| project.code_actions(buffer, range, cx))
12950 }
12951
12952 fn apply_code_action(
12953 &self,
12954 buffer_handle: Model<Buffer>,
12955 action: CodeAction,
12956 _excerpt_id: ExcerptId,
12957 push_to_history: bool,
12958 cx: &mut WindowContext,
12959 ) -> Task<Result<ProjectTransaction>> {
12960 self.update(cx, |project, cx| {
12961 project.apply_code_action(buffer_handle, action, push_to_history, cx)
12962 })
12963 }
12964}
12965
12966fn snippet_completions(
12967 project: &Project,
12968 buffer: &Model<Buffer>,
12969 buffer_position: text::Anchor,
12970 cx: &mut AppContext,
12971) -> Vec<Completion> {
12972 let language = buffer.read(cx).language_at(buffer_position);
12973 let language_name = language.as_ref().map(|language| language.lsp_id());
12974 let snippet_store = project.snippets().read(cx);
12975 let snippets = snippet_store.snippets_for(language_name, cx);
12976
12977 if snippets.is_empty() {
12978 return vec![];
12979 }
12980 let snapshot = buffer.read(cx).text_snapshot();
12981 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12982
12983 let mut lines = chunks.lines();
12984 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12985 return vec![];
12986 };
12987
12988 let scope = language.map(|language| language.default_scope());
12989 let classifier = CharClassifier::new(scope).for_completion(true);
12990 let mut last_word = line_at
12991 .chars()
12992 .rev()
12993 .take_while(|c| classifier.is_word(*c))
12994 .collect::<String>();
12995 last_word = last_word.chars().rev().collect();
12996 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12997 let to_lsp = |point: &text::Anchor| {
12998 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12999 point_to_lsp(end)
13000 };
13001 let lsp_end = to_lsp(&buffer_position);
13002 snippets
13003 .into_iter()
13004 .filter_map(|snippet| {
13005 let matching_prefix = snippet
13006 .prefix
13007 .iter()
13008 .find(|prefix| prefix.starts_with(&last_word))?;
13009 let start = as_offset - last_word.len();
13010 let start = snapshot.anchor_before(start);
13011 let range = start..buffer_position;
13012 let lsp_start = to_lsp(&start);
13013 let lsp_range = lsp::Range {
13014 start: lsp_start,
13015 end: lsp_end,
13016 };
13017 Some(Completion {
13018 old_range: range,
13019 new_text: snippet.body.clone(),
13020 label: CodeLabel {
13021 text: matching_prefix.clone(),
13022 runs: vec![],
13023 filter_range: 0..matching_prefix.len(),
13024 },
13025 server_id: LanguageServerId(usize::MAX),
13026 documentation: snippet.description.clone().map(Documentation::SingleLine),
13027 lsp_completion: lsp::CompletionItem {
13028 label: snippet.prefix.first().unwrap().clone(),
13029 kind: Some(CompletionItemKind::SNIPPET),
13030 label_details: snippet.description.as_ref().map(|description| {
13031 lsp::CompletionItemLabelDetails {
13032 detail: Some(description.clone()),
13033 description: None,
13034 }
13035 }),
13036 insert_text_format: Some(InsertTextFormat::SNIPPET),
13037 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
13038 lsp::InsertReplaceEdit {
13039 new_text: snippet.body.clone(),
13040 insert: lsp_range,
13041 replace: lsp_range,
13042 },
13043 )),
13044 filter_text: Some(snippet.body.clone()),
13045 sort_text: Some(char::MAX.to_string()),
13046 ..Default::default()
13047 },
13048 confirm: None,
13049 })
13050 })
13051 .collect()
13052}
13053
13054impl CompletionProvider for Model<Project> {
13055 fn completions(
13056 &self,
13057 buffer: &Model<Buffer>,
13058 buffer_position: text::Anchor,
13059 options: CompletionContext,
13060 cx: &mut ViewContext<Editor>,
13061 ) -> Task<Result<Vec<Completion>>> {
13062 self.update(cx, |project, cx| {
13063 let snippets = snippet_completions(project, buffer, buffer_position, cx);
13064 let project_completions = project.completions(buffer, buffer_position, options, cx);
13065 cx.background_executor().spawn(async move {
13066 let mut completions = project_completions.await?;
13067 //let snippets = snippets.into_iter().;
13068 completions.extend(snippets);
13069 Ok(completions)
13070 })
13071 })
13072 }
13073
13074 fn resolve_completions(
13075 &self,
13076 buffer: Model<Buffer>,
13077 completion_indices: Vec<usize>,
13078 completions: Arc<RwLock<Box<[Completion]>>>,
13079 cx: &mut ViewContext<Editor>,
13080 ) -> Task<Result<bool>> {
13081 self.update(cx, |project, cx| {
13082 project.resolve_completions(buffer, completion_indices, completions, cx)
13083 })
13084 }
13085
13086 fn apply_additional_edits_for_completion(
13087 &self,
13088 buffer: Model<Buffer>,
13089 completion: Completion,
13090 push_to_history: bool,
13091 cx: &mut ViewContext<Editor>,
13092 ) -> Task<Result<Option<language::Transaction>>> {
13093 self.update(cx, |project, cx| {
13094 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
13095 })
13096 }
13097
13098 fn is_completion_trigger(
13099 &self,
13100 buffer: &Model<Buffer>,
13101 position: language::Anchor,
13102 text: &str,
13103 trigger_in_words: bool,
13104 cx: &mut ViewContext<Editor>,
13105 ) -> bool {
13106 if !EditorSettings::get_global(cx).show_completions_on_input {
13107 return false;
13108 }
13109
13110 let mut chars = text.chars();
13111 let char = if let Some(char) = chars.next() {
13112 char
13113 } else {
13114 return false;
13115 };
13116 if chars.next().is_some() {
13117 return false;
13118 }
13119
13120 let buffer = buffer.read(cx);
13121 let classifier = buffer
13122 .snapshot()
13123 .char_classifier_at(position)
13124 .for_completion(true);
13125 if trigger_in_words && classifier.is_word(char) {
13126 return true;
13127 }
13128
13129 buffer
13130 .completion_triggers()
13131 .iter()
13132 .any(|string| string == text)
13133 }
13134}
13135
13136fn inlay_hint_settings(
13137 location: Anchor,
13138 snapshot: &MultiBufferSnapshot,
13139 cx: &mut ViewContext<'_, Editor>,
13140) -> InlayHintSettings {
13141 let file = snapshot.file_at(location);
13142 let language = snapshot.language_at(location);
13143 let settings = all_language_settings(file, cx);
13144 settings
13145 .language(language.map(|l| l.name()).as_ref())
13146 .inlay_hints
13147}
13148
13149fn consume_contiguous_rows(
13150 contiguous_row_selections: &mut Vec<Selection<Point>>,
13151 selection: &Selection<Point>,
13152 display_map: &DisplaySnapshot,
13153 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
13154) -> (MultiBufferRow, MultiBufferRow) {
13155 contiguous_row_selections.push(selection.clone());
13156 let start_row = MultiBufferRow(selection.start.row);
13157 let mut end_row = ending_row(selection, display_map);
13158
13159 while let Some(next_selection) = selections.peek() {
13160 if next_selection.start.row <= end_row.0 {
13161 end_row = ending_row(next_selection, display_map);
13162 contiguous_row_selections.push(selections.next().unwrap().clone());
13163 } else {
13164 break;
13165 }
13166 }
13167 (start_row, end_row)
13168}
13169
13170fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
13171 if next_selection.end.column > 0 || next_selection.is_empty() {
13172 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
13173 } else {
13174 MultiBufferRow(next_selection.end.row)
13175 }
13176}
13177
13178impl EditorSnapshot {
13179 pub fn remote_selections_in_range<'a>(
13180 &'a self,
13181 range: &'a Range<Anchor>,
13182 collaboration_hub: &dyn CollaborationHub,
13183 cx: &'a AppContext,
13184 ) -> impl 'a + Iterator<Item = RemoteSelection> {
13185 let participant_names = collaboration_hub.user_names(cx);
13186 let participant_indices = collaboration_hub.user_participant_indices(cx);
13187 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
13188 let collaborators_by_replica_id = collaborators_by_peer_id
13189 .iter()
13190 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
13191 .collect::<HashMap<_, _>>();
13192 self.buffer_snapshot
13193 .selections_in_range(range, false)
13194 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
13195 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
13196 let participant_index = participant_indices.get(&collaborator.user_id).copied();
13197 let user_name = participant_names.get(&collaborator.user_id).cloned();
13198 Some(RemoteSelection {
13199 replica_id,
13200 selection,
13201 cursor_shape,
13202 line_mode,
13203 participant_index,
13204 peer_id: collaborator.peer_id,
13205 user_name,
13206 })
13207 })
13208 }
13209
13210 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
13211 self.display_snapshot.buffer_snapshot.language_at(position)
13212 }
13213
13214 pub fn is_focused(&self) -> bool {
13215 self.is_focused
13216 }
13217
13218 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
13219 self.placeholder_text.as_ref()
13220 }
13221
13222 pub fn scroll_position(&self) -> gpui::Point<f32> {
13223 self.scroll_anchor.scroll_position(&self.display_snapshot)
13224 }
13225
13226 fn gutter_dimensions(
13227 &self,
13228 font_id: FontId,
13229 font_size: Pixels,
13230 em_width: Pixels,
13231 em_advance: Pixels,
13232 max_line_number_width: Pixels,
13233 cx: &AppContext,
13234 ) -> GutterDimensions {
13235 if !self.show_gutter {
13236 return GutterDimensions::default();
13237 }
13238 let descent = cx.text_system().descent(font_id, font_size);
13239
13240 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
13241 matches!(
13242 ProjectSettings::get_global(cx).git.git_gutter,
13243 Some(GitGutterSetting::TrackedFiles)
13244 )
13245 });
13246 let gutter_settings = EditorSettings::get_global(cx).gutter;
13247 let show_line_numbers = self
13248 .show_line_numbers
13249 .unwrap_or(gutter_settings.line_numbers);
13250 let line_gutter_width = if show_line_numbers {
13251 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
13252 let min_width_for_number_on_gutter = em_advance * 4.0;
13253 max_line_number_width.max(min_width_for_number_on_gutter)
13254 } else {
13255 0.0.into()
13256 };
13257
13258 let show_code_actions = self
13259 .show_code_actions
13260 .unwrap_or(gutter_settings.code_actions);
13261
13262 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
13263
13264 let git_blame_entries_width =
13265 self.git_blame_gutter_max_author_length
13266 .map(|max_author_length| {
13267 // Length of the author name, but also space for the commit hash,
13268 // the spacing and the timestamp.
13269 let max_char_count = max_author_length
13270 .min(GIT_BLAME_MAX_AUTHOR_CHARS_DISPLAYED)
13271 + 7 // length of commit sha
13272 + 14 // length of max relative timestamp ("60 minutes ago")
13273 + 4; // gaps and margins
13274
13275 em_advance * max_char_count
13276 });
13277
13278 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
13279 left_padding += if show_code_actions || show_runnables {
13280 em_width * 3.0
13281 } else if show_git_gutter && show_line_numbers {
13282 em_width * 2.0
13283 } else if show_git_gutter || show_line_numbers {
13284 em_width
13285 } else {
13286 px(0.)
13287 };
13288
13289 let right_padding = if gutter_settings.folds && show_line_numbers {
13290 em_width * 4.0
13291 } else if gutter_settings.folds {
13292 em_width * 3.0
13293 } else if show_line_numbers {
13294 em_width
13295 } else {
13296 px(0.)
13297 };
13298
13299 GutterDimensions {
13300 left_padding,
13301 right_padding,
13302 width: line_gutter_width + left_padding + right_padding,
13303 margin: -descent,
13304 git_blame_entries_width,
13305 }
13306 }
13307
13308 pub fn render_fold_toggle(
13309 &self,
13310 buffer_row: MultiBufferRow,
13311 row_contains_cursor: bool,
13312 editor: View<Editor>,
13313 cx: &mut WindowContext,
13314 ) -> Option<AnyElement> {
13315 let folded = self.is_line_folded(buffer_row);
13316
13317 if let Some(crease) = self
13318 .crease_snapshot
13319 .query_row(buffer_row, &self.buffer_snapshot)
13320 {
13321 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
13322 if folded {
13323 editor.update(cx, |editor, cx| {
13324 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
13325 });
13326 } else {
13327 editor.update(cx, |editor, cx| {
13328 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
13329 });
13330 }
13331 });
13332
13333 Some((crease.render_toggle)(
13334 buffer_row,
13335 folded,
13336 toggle_callback,
13337 cx,
13338 ))
13339 } else if folded
13340 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
13341 {
13342 Some(
13343 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
13344 .selected(folded)
13345 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
13346 if folded {
13347 this.unfold_at(&UnfoldAt { buffer_row }, cx);
13348 } else {
13349 this.fold_at(&FoldAt { buffer_row }, cx);
13350 }
13351 }))
13352 .into_any_element(),
13353 )
13354 } else {
13355 None
13356 }
13357 }
13358
13359 pub fn render_crease_trailer(
13360 &self,
13361 buffer_row: MultiBufferRow,
13362 cx: &mut WindowContext,
13363 ) -> Option<AnyElement> {
13364 let folded = self.is_line_folded(buffer_row);
13365 let crease = self
13366 .crease_snapshot
13367 .query_row(buffer_row, &self.buffer_snapshot)?;
13368 Some((crease.render_trailer)(buffer_row, folded, cx))
13369 }
13370}
13371
13372impl Deref for EditorSnapshot {
13373 type Target = DisplaySnapshot;
13374
13375 fn deref(&self) -> &Self::Target {
13376 &self.display_snapshot
13377 }
13378}
13379
13380#[derive(Clone, Debug, PartialEq, Eq)]
13381pub enum EditorEvent {
13382 InputIgnored {
13383 text: Arc<str>,
13384 },
13385 InputHandled {
13386 utf16_range_to_replace: Option<Range<isize>>,
13387 text: Arc<str>,
13388 },
13389 ExcerptsAdded {
13390 buffer: Model<Buffer>,
13391 predecessor: ExcerptId,
13392 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
13393 },
13394 ExcerptsRemoved {
13395 ids: Vec<ExcerptId>,
13396 },
13397 ExcerptsEdited {
13398 ids: Vec<ExcerptId>,
13399 },
13400 ExcerptsExpanded {
13401 ids: Vec<ExcerptId>,
13402 },
13403 BufferEdited,
13404 Edited {
13405 transaction_id: clock::Lamport,
13406 },
13407 Reparsed(BufferId),
13408 Focused,
13409 FocusedIn,
13410 Blurred,
13411 DirtyChanged,
13412 Saved,
13413 TitleChanged,
13414 DiffBaseChanged,
13415 SelectionsChanged {
13416 local: bool,
13417 },
13418 ScrollPositionChanged {
13419 local: bool,
13420 autoscroll: bool,
13421 },
13422 Closed,
13423 TransactionUndone {
13424 transaction_id: clock::Lamport,
13425 },
13426 TransactionBegun {
13427 transaction_id: clock::Lamport,
13428 },
13429 CursorShapeChanged,
13430}
13431
13432impl EventEmitter<EditorEvent> for Editor {}
13433
13434impl FocusableView for Editor {
13435 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13436 self.focus_handle.clone()
13437 }
13438}
13439
13440impl Render for Editor {
13441 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13442 let settings = ThemeSettings::get_global(cx);
13443
13444 let text_style = match self.mode {
13445 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13446 color: cx.theme().colors().editor_foreground,
13447 font_family: settings.ui_font.family.clone(),
13448 font_features: settings.ui_font.features.clone(),
13449 font_fallbacks: settings.ui_font.fallbacks.clone(),
13450 font_size: rems(0.875).into(),
13451 font_weight: settings.ui_font.weight,
13452 line_height: relative(settings.buffer_line_height.value()),
13453 ..Default::default()
13454 },
13455 EditorMode::Full => TextStyle {
13456 color: cx.theme().colors().editor_foreground,
13457 font_family: settings.buffer_font.family.clone(),
13458 font_features: settings.buffer_font.features.clone(),
13459 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13460 font_size: settings.buffer_font_size(cx).into(),
13461 font_weight: settings.buffer_font.weight,
13462 line_height: relative(settings.buffer_line_height.value()),
13463 ..Default::default()
13464 },
13465 };
13466
13467 let background = match self.mode {
13468 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13469 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13470 EditorMode::Full => cx.theme().colors().editor_background,
13471 };
13472
13473 EditorElement::new(
13474 cx.view(),
13475 EditorStyle {
13476 background,
13477 local_player: cx.theme().players().local(),
13478 text: text_style,
13479 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13480 syntax: cx.theme().syntax().clone(),
13481 status: cx.theme().status().clone(),
13482 inlay_hints_style: make_inlay_hints_style(cx),
13483 suggestions_style: HighlightStyle {
13484 color: Some(cx.theme().status().predictive),
13485 ..HighlightStyle::default()
13486 },
13487 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13488 },
13489 )
13490 }
13491}
13492
13493impl ViewInputHandler for Editor {
13494 fn text_for_range(
13495 &mut self,
13496 range_utf16: Range<usize>,
13497 cx: &mut ViewContext<Self>,
13498 ) -> Option<String> {
13499 Some(
13500 self.buffer
13501 .read(cx)
13502 .read(cx)
13503 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13504 .collect(),
13505 )
13506 }
13507
13508 fn selected_text_range(
13509 &mut self,
13510 ignore_disabled_input: bool,
13511 cx: &mut ViewContext<Self>,
13512 ) -> Option<UTF16Selection> {
13513 // Prevent the IME menu from appearing when holding down an alphabetic key
13514 // while input is disabled.
13515 if !ignore_disabled_input && !self.input_enabled {
13516 return None;
13517 }
13518
13519 let selection = self.selections.newest::<OffsetUtf16>(cx);
13520 let range = selection.range();
13521
13522 Some(UTF16Selection {
13523 range: range.start.0..range.end.0,
13524 reversed: selection.reversed,
13525 })
13526 }
13527
13528 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13529 let snapshot = self.buffer.read(cx).read(cx);
13530 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13531 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13532 }
13533
13534 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13535 self.clear_highlights::<InputComposition>(cx);
13536 self.ime_transaction.take();
13537 }
13538
13539 fn replace_text_in_range(
13540 &mut self,
13541 range_utf16: Option<Range<usize>>,
13542 text: &str,
13543 cx: &mut ViewContext<Self>,
13544 ) {
13545 if !self.input_enabled {
13546 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13547 return;
13548 }
13549
13550 self.transact(cx, |this, cx| {
13551 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13552 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13553 Some(this.selection_replacement_ranges(range_utf16, cx))
13554 } else {
13555 this.marked_text_ranges(cx)
13556 };
13557
13558 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13559 let newest_selection_id = this.selections.newest_anchor().id;
13560 this.selections
13561 .all::<OffsetUtf16>(cx)
13562 .iter()
13563 .zip(ranges_to_replace.iter())
13564 .find_map(|(selection, range)| {
13565 if selection.id == newest_selection_id {
13566 Some(
13567 (range.start.0 as isize - selection.head().0 as isize)
13568 ..(range.end.0 as isize - selection.head().0 as isize),
13569 )
13570 } else {
13571 None
13572 }
13573 })
13574 });
13575
13576 cx.emit(EditorEvent::InputHandled {
13577 utf16_range_to_replace: range_to_replace,
13578 text: text.into(),
13579 });
13580
13581 if let Some(new_selected_ranges) = new_selected_ranges {
13582 this.change_selections(None, cx, |selections| {
13583 selections.select_ranges(new_selected_ranges)
13584 });
13585 this.backspace(&Default::default(), cx);
13586 }
13587
13588 this.handle_input(text, cx);
13589 });
13590
13591 if let Some(transaction) = self.ime_transaction {
13592 self.buffer.update(cx, |buffer, cx| {
13593 buffer.group_until_transaction(transaction, cx);
13594 });
13595 }
13596
13597 self.unmark_text(cx);
13598 }
13599
13600 fn replace_and_mark_text_in_range(
13601 &mut self,
13602 range_utf16: Option<Range<usize>>,
13603 text: &str,
13604 new_selected_range_utf16: Option<Range<usize>>,
13605 cx: &mut ViewContext<Self>,
13606 ) {
13607 if !self.input_enabled {
13608 return;
13609 }
13610
13611 let transaction = self.transact(cx, |this, cx| {
13612 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13613 let snapshot = this.buffer.read(cx).read(cx);
13614 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13615 for marked_range in &mut marked_ranges {
13616 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13617 marked_range.start.0 += relative_range_utf16.start;
13618 marked_range.start =
13619 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13620 marked_range.end =
13621 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13622 }
13623 }
13624 Some(marked_ranges)
13625 } else if let Some(range_utf16) = range_utf16 {
13626 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13627 Some(this.selection_replacement_ranges(range_utf16, cx))
13628 } else {
13629 None
13630 };
13631
13632 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13633 let newest_selection_id = this.selections.newest_anchor().id;
13634 this.selections
13635 .all::<OffsetUtf16>(cx)
13636 .iter()
13637 .zip(ranges_to_replace.iter())
13638 .find_map(|(selection, range)| {
13639 if selection.id == newest_selection_id {
13640 Some(
13641 (range.start.0 as isize - selection.head().0 as isize)
13642 ..(range.end.0 as isize - selection.head().0 as isize),
13643 )
13644 } else {
13645 None
13646 }
13647 })
13648 });
13649
13650 cx.emit(EditorEvent::InputHandled {
13651 utf16_range_to_replace: range_to_replace,
13652 text: text.into(),
13653 });
13654
13655 if let Some(ranges) = ranges_to_replace {
13656 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13657 }
13658
13659 let marked_ranges = {
13660 let snapshot = this.buffer.read(cx).read(cx);
13661 this.selections
13662 .disjoint_anchors()
13663 .iter()
13664 .map(|selection| {
13665 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13666 })
13667 .collect::<Vec<_>>()
13668 };
13669
13670 if text.is_empty() {
13671 this.unmark_text(cx);
13672 } else {
13673 this.highlight_text::<InputComposition>(
13674 marked_ranges.clone(),
13675 HighlightStyle {
13676 underline: Some(UnderlineStyle {
13677 thickness: px(1.),
13678 color: None,
13679 wavy: false,
13680 }),
13681 ..Default::default()
13682 },
13683 cx,
13684 );
13685 }
13686
13687 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13688 let use_autoclose = this.use_autoclose;
13689 let use_auto_surround = this.use_auto_surround;
13690 this.set_use_autoclose(false);
13691 this.set_use_auto_surround(false);
13692 this.handle_input(text, cx);
13693 this.set_use_autoclose(use_autoclose);
13694 this.set_use_auto_surround(use_auto_surround);
13695
13696 if let Some(new_selected_range) = new_selected_range_utf16 {
13697 let snapshot = this.buffer.read(cx).read(cx);
13698 let new_selected_ranges = marked_ranges
13699 .into_iter()
13700 .map(|marked_range| {
13701 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13702 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13703 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13704 snapshot.clip_offset_utf16(new_start, Bias::Left)
13705 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13706 })
13707 .collect::<Vec<_>>();
13708
13709 drop(snapshot);
13710 this.change_selections(None, cx, |selections| {
13711 selections.select_ranges(new_selected_ranges)
13712 });
13713 }
13714 });
13715
13716 self.ime_transaction = self.ime_transaction.or(transaction);
13717 if let Some(transaction) = self.ime_transaction {
13718 self.buffer.update(cx, |buffer, cx| {
13719 buffer.group_until_transaction(transaction, cx);
13720 });
13721 }
13722
13723 if self.text_highlights::<InputComposition>(cx).is_none() {
13724 self.ime_transaction.take();
13725 }
13726 }
13727
13728 fn bounds_for_range(
13729 &mut self,
13730 range_utf16: Range<usize>,
13731 element_bounds: gpui::Bounds<Pixels>,
13732 cx: &mut ViewContext<Self>,
13733 ) -> Option<gpui::Bounds<Pixels>> {
13734 let text_layout_details = self.text_layout_details(cx);
13735 let style = &text_layout_details.editor_style;
13736 let font_id = cx.text_system().resolve_font(&style.text.font());
13737 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13738 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13739
13740 let em_width = cx
13741 .text_system()
13742 .typographic_bounds(font_id, font_size, 'm')
13743 .unwrap()
13744 .size
13745 .width;
13746
13747 let snapshot = self.snapshot(cx);
13748 let scroll_position = snapshot.scroll_position();
13749 let scroll_left = scroll_position.x * em_width;
13750
13751 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13752 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13753 + self.gutter_dimensions.width;
13754 let y = line_height * (start.row().as_f32() - scroll_position.y);
13755
13756 Some(Bounds {
13757 origin: element_bounds.origin + point(x, y),
13758 size: size(em_width, line_height),
13759 })
13760 }
13761}
13762
13763trait SelectionExt {
13764 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13765 fn spanned_rows(
13766 &self,
13767 include_end_if_at_line_start: bool,
13768 map: &DisplaySnapshot,
13769 ) -> Range<MultiBufferRow>;
13770}
13771
13772impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13773 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13774 let start = self
13775 .start
13776 .to_point(&map.buffer_snapshot)
13777 .to_display_point(map);
13778 let end = self
13779 .end
13780 .to_point(&map.buffer_snapshot)
13781 .to_display_point(map);
13782 if self.reversed {
13783 end..start
13784 } else {
13785 start..end
13786 }
13787 }
13788
13789 fn spanned_rows(
13790 &self,
13791 include_end_if_at_line_start: bool,
13792 map: &DisplaySnapshot,
13793 ) -> Range<MultiBufferRow> {
13794 let start = self.start.to_point(&map.buffer_snapshot);
13795 let mut end = self.end.to_point(&map.buffer_snapshot);
13796 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13797 end.row -= 1;
13798 }
13799
13800 let buffer_start = map.prev_line_boundary(start).0;
13801 let buffer_end = map.next_line_boundary(end).0;
13802 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13803 }
13804}
13805
13806impl<T: InvalidationRegion> InvalidationStack<T> {
13807 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13808 where
13809 S: Clone + ToOffset,
13810 {
13811 while let Some(region) = self.last() {
13812 let all_selections_inside_invalidation_ranges =
13813 if selections.len() == region.ranges().len() {
13814 selections
13815 .iter()
13816 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13817 .all(|(selection, invalidation_range)| {
13818 let head = selection.head().to_offset(buffer);
13819 invalidation_range.start <= head && invalidation_range.end >= head
13820 })
13821 } else {
13822 false
13823 };
13824
13825 if all_selections_inside_invalidation_ranges {
13826 break;
13827 } else {
13828 self.pop();
13829 }
13830 }
13831 }
13832}
13833
13834impl<T> Default for InvalidationStack<T> {
13835 fn default() -> Self {
13836 Self(Default::default())
13837 }
13838}
13839
13840impl<T> Deref for InvalidationStack<T> {
13841 type Target = Vec<T>;
13842
13843 fn deref(&self) -> &Self::Target {
13844 &self.0
13845 }
13846}
13847
13848impl<T> DerefMut for InvalidationStack<T> {
13849 fn deref_mut(&mut self) -> &mut Self::Target {
13850 &mut self.0
13851 }
13852}
13853
13854impl InvalidationRegion for SnippetState {
13855 fn ranges(&self) -> &[Range<Anchor>] {
13856 &self.ranges[self.active_index]
13857 }
13858}
13859
13860pub fn diagnostic_block_renderer(
13861 diagnostic: Diagnostic,
13862 max_message_rows: Option<u8>,
13863 allow_closing: bool,
13864 _is_valid: bool,
13865) -> RenderBlock {
13866 let (text_without_backticks, code_ranges) =
13867 highlight_diagnostic_message(&diagnostic, max_message_rows);
13868
13869 Box::new(move |cx: &mut BlockContext| {
13870 let group_id: SharedString = cx.block_id.to_string().into();
13871
13872 let mut text_style = cx.text_style().clone();
13873 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13874 let theme_settings = ThemeSettings::get_global(cx);
13875 text_style.font_family = theme_settings.buffer_font.family.clone();
13876 text_style.font_style = theme_settings.buffer_font.style;
13877 text_style.font_features = theme_settings.buffer_font.features.clone();
13878 text_style.font_weight = theme_settings.buffer_font.weight;
13879
13880 let multi_line_diagnostic = diagnostic.message.contains('\n');
13881
13882 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13883 if multi_line_diagnostic {
13884 v_flex()
13885 } else {
13886 h_flex()
13887 }
13888 .when(allow_closing, |div| {
13889 div.children(diagnostic.is_primary.then(|| {
13890 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13891 .icon_color(Color::Muted)
13892 .size(ButtonSize::Compact)
13893 .style(ButtonStyle::Transparent)
13894 .visible_on_hover(group_id.clone())
13895 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13896 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13897 }))
13898 })
13899 .child(
13900 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13901 .icon_color(Color::Muted)
13902 .size(ButtonSize::Compact)
13903 .style(ButtonStyle::Transparent)
13904 .visible_on_hover(group_id.clone())
13905 .on_click({
13906 let message = diagnostic.message.clone();
13907 move |_click, cx| {
13908 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13909 }
13910 })
13911 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13912 )
13913 };
13914
13915 let icon_size = buttons(&diagnostic, cx.block_id)
13916 .into_any_element()
13917 .layout_as_root(AvailableSpace::min_size(), cx);
13918
13919 h_flex()
13920 .id(cx.block_id)
13921 .group(group_id.clone())
13922 .relative()
13923 .size_full()
13924 .pl(cx.gutter_dimensions.width)
13925 .w(cx.max_width + cx.gutter_dimensions.width)
13926 .child(
13927 div()
13928 .flex()
13929 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13930 .flex_shrink(),
13931 )
13932 .child(buttons(&diagnostic, cx.block_id))
13933 .child(div().flex().flex_shrink_0().child(
13934 StyledText::new(text_without_backticks.clone()).with_highlights(
13935 &text_style,
13936 code_ranges.iter().map(|range| {
13937 (
13938 range.clone(),
13939 HighlightStyle {
13940 font_weight: Some(FontWeight::BOLD),
13941 ..Default::default()
13942 },
13943 )
13944 }),
13945 ),
13946 ))
13947 .into_any_element()
13948 })
13949}
13950
13951pub fn highlight_diagnostic_message(
13952 diagnostic: &Diagnostic,
13953 mut max_message_rows: Option<u8>,
13954) -> (SharedString, Vec<Range<usize>>) {
13955 let mut text_without_backticks = String::new();
13956 let mut code_ranges = Vec::new();
13957
13958 if let Some(source) = &diagnostic.source {
13959 text_without_backticks.push_str(source);
13960 code_ranges.push(0..source.len());
13961 text_without_backticks.push_str(": ");
13962 }
13963
13964 let mut prev_offset = 0;
13965 let mut in_code_block = false;
13966 let has_row_limit = max_message_rows.is_some();
13967 let mut newline_indices = diagnostic
13968 .message
13969 .match_indices('\n')
13970 .filter(|_| has_row_limit)
13971 .map(|(ix, _)| ix)
13972 .fuse()
13973 .peekable();
13974
13975 for (quote_ix, _) in diagnostic
13976 .message
13977 .match_indices('`')
13978 .chain([(diagnostic.message.len(), "")])
13979 {
13980 let mut first_newline_ix = None;
13981 let mut last_newline_ix = None;
13982 while let Some(newline_ix) = newline_indices.peek() {
13983 if *newline_ix < quote_ix {
13984 if first_newline_ix.is_none() {
13985 first_newline_ix = Some(*newline_ix);
13986 }
13987 last_newline_ix = Some(*newline_ix);
13988
13989 if let Some(rows_left) = &mut max_message_rows {
13990 if *rows_left == 0 {
13991 break;
13992 } else {
13993 *rows_left -= 1;
13994 }
13995 }
13996 let _ = newline_indices.next();
13997 } else {
13998 break;
13999 }
14000 }
14001 let prev_len = text_without_backticks.len();
14002 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
14003 text_without_backticks.push_str(new_text);
14004 if in_code_block {
14005 code_ranges.push(prev_len..text_without_backticks.len());
14006 }
14007 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
14008 in_code_block = !in_code_block;
14009 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
14010 text_without_backticks.push_str("...");
14011 break;
14012 }
14013 }
14014
14015 (text_without_backticks.into(), code_ranges)
14016}
14017
14018fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
14019 match severity {
14020 DiagnosticSeverity::ERROR => colors.error,
14021 DiagnosticSeverity::WARNING => colors.warning,
14022 DiagnosticSeverity::INFORMATION => colors.info,
14023 DiagnosticSeverity::HINT => colors.info,
14024 _ => colors.ignored,
14025 }
14026}
14027
14028pub fn styled_runs_for_code_label<'a>(
14029 label: &'a CodeLabel,
14030 syntax_theme: &'a theme::SyntaxTheme,
14031) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
14032 let fade_out = HighlightStyle {
14033 fade_out: Some(0.35),
14034 ..Default::default()
14035 };
14036
14037 let mut prev_end = label.filter_range.end;
14038 label
14039 .runs
14040 .iter()
14041 .enumerate()
14042 .flat_map(move |(ix, (range, highlight_id))| {
14043 let style = if let Some(style) = highlight_id.style(syntax_theme) {
14044 style
14045 } else {
14046 return Default::default();
14047 };
14048 let mut muted_style = style;
14049 muted_style.highlight(fade_out);
14050
14051 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
14052 if range.start >= label.filter_range.end {
14053 if range.start > prev_end {
14054 runs.push((prev_end..range.start, fade_out));
14055 }
14056 runs.push((range.clone(), muted_style));
14057 } else if range.end <= label.filter_range.end {
14058 runs.push((range.clone(), style));
14059 } else {
14060 runs.push((range.start..label.filter_range.end, style));
14061 runs.push((label.filter_range.end..range.end, muted_style));
14062 }
14063 prev_end = cmp::max(prev_end, range.end);
14064
14065 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
14066 runs.push((prev_end..label.text.len(), fade_out));
14067 }
14068
14069 runs
14070 })
14071}
14072
14073pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
14074 let mut prev_index = 0;
14075 let mut prev_codepoint: Option<char> = None;
14076 text.char_indices()
14077 .chain([(text.len(), '\0')])
14078 .filter_map(move |(index, codepoint)| {
14079 let prev_codepoint = prev_codepoint.replace(codepoint)?;
14080 let is_boundary = index == text.len()
14081 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
14082 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
14083 if is_boundary {
14084 let chunk = &text[prev_index..index];
14085 prev_index = index;
14086 Some(chunk)
14087 } else {
14088 None
14089 }
14090 })
14091}
14092
14093pub trait RangeToAnchorExt: Sized {
14094 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
14095
14096 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
14097 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
14098 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
14099 }
14100}
14101
14102impl<T: ToOffset> RangeToAnchorExt for Range<T> {
14103 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
14104 let start_offset = self.start.to_offset(snapshot);
14105 let end_offset = self.end.to_offset(snapshot);
14106 if start_offset == end_offset {
14107 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
14108 } else {
14109 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
14110 }
14111 }
14112}
14113
14114pub trait RowExt {
14115 fn as_f32(&self) -> f32;
14116
14117 fn next_row(&self) -> Self;
14118
14119 fn previous_row(&self) -> Self;
14120
14121 fn minus(&self, other: Self) -> u32;
14122}
14123
14124impl RowExt for DisplayRow {
14125 fn as_f32(&self) -> f32 {
14126 self.0 as f32
14127 }
14128
14129 fn next_row(&self) -> Self {
14130 Self(self.0 + 1)
14131 }
14132
14133 fn previous_row(&self) -> Self {
14134 Self(self.0.saturating_sub(1))
14135 }
14136
14137 fn minus(&self, other: Self) -> u32 {
14138 self.0 - other.0
14139 }
14140}
14141
14142impl RowExt for MultiBufferRow {
14143 fn as_f32(&self) -> f32 {
14144 self.0 as f32
14145 }
14146
14147 fn next_row(&self) -> Self {
14148 Self(self.0 + 1)
14149 }
14150
14151 fn previous_row(&self) -> Self {
14152 Self(self.0.saturating_sub(1))
14153 }
14154
14155 fn minus(&self, other: Self) -> u32 {
14156 self.0 - other.0
14157 }
14158}
14159
14160trait RowRangeExt {
14161 type Row;
14162
14163 fn len(&self) -> usize;
14164
14165 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
14166}
14167
14168impl RowRangeExt for Range<MultiBufferRow> {
14169 type Row = MultiBufferRow;
14170
14171 fn len(&self) -> usize {
14172 (self.end.0 - self.start.0) as usize
14173 }
14174
14175 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
14176 (self.start.0..self.end.0).map(MultiBufferRow)
14177 }
14178}
14179
14180impl RowRangeExt for Range<DisplayRow> {
14181 type Row = DisplayRow;
14182
14183 fn len(&self) -> usize {
14184 (self.end.0 - self.start.0) as usize
14185 }
14186
14187 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
14188 (self.start.0..self.end.0).map(DisplayRow)
14189 }
14190}
14191
14192fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
14193 if hunk.diff_base_byte_range.is_empty() {
14194 DiffHunkStatus::Added
14195 } else if hunk.row_range.is_empty() {
14196 DiffHunkStatus::Removed
14197 } else {
14198 DiffHunkStatus::Modified
14199 }
14200}
14201
14202/// If select range has more than one line, we
14203/// just point the cursor to range.start.
14204fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
14205 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
14206 range
14207 } else {
14208 range.start..range.start
14209 }
14210}