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 rust_analyzer_ext;
39pub mod scroll;
40mod selections_collection;
41pub mod tasks;
42
43#[cfg(test)]
44mod editor_tests;
45mod signature_help;
46#[cfg(any(test, feature = "test-support"))]
47pub mod test;
48
49use ::git::diff::{DiffHunk, DiffHunkStatus};
50use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
51pub(crate) use actions::*;
52use aho_corasick::AhoCorasick;
53use anyhow::{anyhow, Context as _, Result};
54use blink_manager::BlinkManager;
55use client::{Collaborator, ParticipantIndex};
56use clock::ReplicaId;
57use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
58use convert_case::{Case, Casing};
59use debounced_delay::DebouncedDelay;
60use display_map::*;
61pub use display_map::{DisplayPoint, FoldPlaceholder};
62pub use editor_settings::{
63 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings,
64};
65pub use editor_settings_controls::*;
66use element::LineWithInvisibles;
67pub use element::{
68 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
69};
70use futures::FutureExt;
71use fuzzy::{StringMatch, StringMatchCandidate};
72use git::blame::GitBlame;
73use git::diff_hunk_to_display;
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};
86use hunk_diff::ExpandedHunks;
87pub(crate) use hunk_diff::HoveredHunk;
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;
101use similar::{ChangeTag, TextDiff};
102use task::{ResolvedTask, TaskTemplate, TaskVariables};
103
104use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
105pub use lsp::CompletionContext;
106use lsp::{
107 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
108 LanguageServerId,
109};
110use mouse_context_menu::MouseContextMenu;
111use movement::TextLayoutDetails;
112pub use multi_buffer::{
113 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
114 ToPoint,
115};
116use multi_buffer::{ExpandExcerptDirection, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16};
117use ordered_float::OrderedFloat;
118use parking_lot::{Mutex, RwLock};
119use project::project_settings::{GitGutterSetting, ProjectSettings};
120use project::{
121 CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
122 ProjectTransaction, TaskSourceKind,
123};
124use rand::prelude::*;
125use rpc::{proto::*, ErrorExt};
126use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
127use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
128use serde::{Deserialize, Serialize};
129use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
130use smallvec::SmallVec;
131use snippet::Snippet;
132use std::{
133 any::TypeId,
134 borrow::Cow,
135 cell::RefCell,
136 cmp::{self, Ordering, Reverse},
137 mem,
138 num::NonZeroU32,
139 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
140 path::{Path, PathBuf},
141 rc::Rc,
142 sync::Arc,
143 time::{Duration, Instant},
144};
145pub use sum_tree::Bias;
146use sum_tree::TreeMap;
147use text::{BufferId, OffsetUtf16, Rope};
148use theme::{
149 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
150 ThemeColors, ThemeSettings,
151};
152use ui::{
153 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
154 ListItem, Popover, Tooltip,
155};
156use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
157use workspace::item::{ItemHandle, PreviewTabsSettings};
158use workspace::notifications::{DetachAndPromptErr, NotificationId};
159use workspace::{
160 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
161};
162use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
163
164use crate::hover_links::find_url;
165use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
166
167pub const FILE_HEADER_HEIGHT: u32 = 1;
168pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
169pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
170pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
171const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
172const MAX_LINE_LEN: usize = 1024;
173const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
174const MAX_SELECTION_HISTORY_LEN: usize = 1024;
175pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
176#[doc(hidden)]
177pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
178#[doc(hidden)]
179pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
180
181pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
182pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
183
184pub fn render_parsed_markdown(
185 element_id: impl Into<ElementId>,
186 parsed: &language::ParsedMarkdown,
187 editor_style: &EditorStyle,
188 workspace: Option<WeakView<Workspace>>,
189 cx: &mut WindowContext,
190) -> InteractiveText {
191 let code_span_background_color = cx
192 .theme()
193 .colors()
194 .editor_document_highlight_read_background;
195
196 let highlights = gpui::combine_highlights(
197 parsed.highlights.iter().filter_map(|(range, highlight)| {
198 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
199 Some((range.clone(), highlight))
200 }),
201 parsed
202 .regions
203 .iter()
204 .zip(&parsed.region_ranges)
205 .filter_map(|(region, range)| {
206 if region.code {
207 Some((
208 range.clone(),
209 HighlightStyle {
210 background_color: Some(code_span_background_color),
211 ..Default::default()
212 },
213 ))
214 } else {
215 None
216 }
217 }),
218 );
219
220 let mut links = Vec::new();
221 let mut link_ranges = Vec::new();
222 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
223 if let Some(link) = region.link.clone() {
224 links.push(link);
225 link_ranges.push(range.clone());
226 }
227 }
228
229 InteractiveText::new(
230 element_id,
231 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
232 )
233 .on_click(link_ranges, move |clicked_range_ix, cx| {
234 match &links[clicked_range_ix] {
235 markdown::Link::Web { url } => cx.open_url(url),
236 markdown::Link::Path { path } => {
237 if let Some(workspace) = &workspace {
238 _ = workspace.update(cx, |workspace, cx| {
239 workspace.open_abs_path(path.clone(), false, cx).detach();
240 });
241 }
242 }
243 }
244 })
245}
246
247#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
248pub(crate) enum InlayId {
249 Suggestion(usize),
250 Hint(usize),
251}
252
253impl InlayId {
254 fn id(&self) -> usize {
255 match self {
256 Self::Suggestion(id) => *id,
257 Self::Hint(id) => *id,
258 }
259 }
260}
261
262enum DiffRowHighlight {}
263enum DocumentHighlightRead {}
264enum DocumentHighlightWrite {}
265enum InputComposition {}
266
267#[derive(Copy, Clone, PartialEq, Eq)]
268pub enum Direction {
269 Prev,
270 Next,
271}
272
273#[derive(Debug, Copy, Clone, PartialEq, Eq)]
274pub enum Navigated {
275 Yes,
276 No,
277}
278
279impl Navigated {
280 pub fn from_bool(yes: bool) -> Navigated {
281 if yes {
282 Navigated::Yes
283 } else {
284 Navigated::No
285 }
286 }
287}
288
289pub fn init_settings(cx: &mut AppContext) {
290 EditorSettings::register(cx);
291}
292
293pub fn init(cx: &mut AppContext) {
294 init_settings(cx);
295
296 workspace::register_project_item::<Editor>(cx);
297 workspace::FollowableViewRegistry::register::<Editor>(cx);
298 workspace::register_serializable_item::<Editor>(cx);
299
300 cx.observe_new_views(
301 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
302 workspace.register_action(Editor::new_file);
303 workspace.register_action(Editor::new_file_vertical);
304 workspace.register_action(Editor::new_file_horizontal);
305 },
306 )
307 .detach();
308
309 cx.on_action(move |_: &workspace::NewFile, cx| {
310 let app_state = workspace::AppState::global(cx);
311 if let Some(app_state) = app_state.upgrade() {
312 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
313 Editor::new_file(workspace, &Default::default(), cx)
314 })
315 .detach();
316 }
317 });
318 cx.on_action(move |_: &workspace::NewWindow, cx| {
319 let app_state = workspace::AppState::global(cx);
320 if let Some(app_state) = app_state.upgrade() {
321 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
322 Editor::new_file(workspace, &Default::default(), cx)
323 })
324 .detach();
325 }
326 });
327}
328
329pub struct SearchWithinRange;
330
331trait InvalidationRegion {
332 fn ranges(&self) -> &[Range<Anchor>];
333}
334
335#[derive(Clone, Debug, PartialEq)]
336pub enum SelectPhase {
337 Begin {
338 position: DisplayPoint,
339 add: bool,
340 click_count: usize,
341 },
342 BeginColumnar {
343 position: DisplayPoint,
344 reset: bool,
345 goal_column: u32,
346 },
347 Extend {
348 position: DisplayPoint,
349 click_count: usize,
350 },
351 Update {
352 position: DisplayPoint,
353 goal_column: u32,
354 scroll_delta: gpui::Point<f32>,
355 },
356 End,
357}
358
359#[derive(Clone, Debug)]
360pub enum SelectMode {
361 Character,
362 Word(Range<Anchor>),
363 Line(Range<Anchor>),
364 All,
365}
366
367#[derive(Copy, Clone, PartialEq, Eq, Debug)]
368pub enum EditorMode {
369 SingleLine { auto_width: bool },
370 AutoHeight { max_lines: usize },
371 Full,
372}
373
374#[derive(Clone, Debug)]
375pub enum SoftWrap {
376 None,
377 PreferLine,
378 EditorWidth,
379 Column(u32),
380 Bounded(u32),
381}
382
383#[derive(Clone)]
384pub struct EditorStyle {
385 pub background: Hsla,
386 pub local_player: PlayerColor,
387 pub text: TextStyle,
388 pub scrollbar_width: Pixels,
389 pub syntax: Arc<SyntaxTheme>,
390 pub status: StatusColors,
391 pub inlay_hints_style: HighlightStyle,
392 pub suggestions_style: HighlightStyle,
393 pub unnecessary_code_fade: f32,
394}
395
396impl Default for EditorStyle {
397 fn default() -> Self {
398 Self {
399 background: Hsla::default(),
400 local_player: PlayerColor::default(),
401 text: TextStyle::default(),
402 scrollbar_width: Pixels::default(),
403 syntax: Default::default(),
404 // HACK: Status colors don't have a real default.
405 // We should look into removing the status colors from the editor
406 // style and retrieve them directly from the theme.
407 status: StatusColors::dark(),
408 inlay_hints_style: HighlightStyle::default(),
409 suggestions_style: HighlightStyle::default(),
410 unnecessary_code_fade: Default::default(),
411 }
412 }
413}
414
415pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
416 let show_background = all_language_settings(None, cx)
417 .language(None)
418 .inlay_hints
419 .show_background;
420
421 HighlightStyle {
422 color: Some(cx.theme().status().hint),
423 background_color: show_background.then(|| cx.theme().status().hint_background),
424 ..HighlightStyle::default()
425 }
426}
427
428type CompletionId = usize;
429
430#[derive(Clone, Debug)]
431struct CompletionState {
432 // render_inlay_ids represents the inlay hints that are inserted
433 // for rendering the inline completions. They may be discontinuous
434 // in the event that the completion provider returns some intersection
435 // with the existing content.
436 render_inlay_ids: Vec<InlayId>,
437 // text is the resulting rope that is inserted when the user accepts a completion.
438 text: Rope,
439 // position is the position of the cursor when the completion was triggered.
440 position: multi_buffer::Anchor,
441 // delete_range is the range of text that this completion state covers.
442 // if the completion is accepted, this range should be deleted.
443 delete_range: Option<Range<multi_buffer::Anchor>>,
444}
445
446#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
447struct EditorActionId(usize);
448
449impl EditorActionId {
450 pub fn post_inc(&mut self) -> Self {
451 let answer = self.0;
452
453 *self = Self(answer + 1);
454
455 Self(answer)
456 }
457}
458
459// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
460// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
461
462type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
463type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
464
465#[derive(Default)]
466struct ScrollbarMarkerState {
467 scrollbar_size: Size<Pixels>,
468 dirty: bool,
469 markers: Arc<[PaintQuad]>,
470 pending_refresh: Option<Task<Result<()>>>,
471}
472
473impl ScrollbarMarkerState {
474 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
475 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
476 }
477}
478
479#[derive(Clone, Debug)]
480struct RunnableTasks {
481 templates: Vec<(TaskSourceKind, TaskTemplate)>,
482 offset: MultiBufferOffset,
483 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
484 column: u32,
485 // Values of all named captures, including those starting with '_'
486 extra_variables: HashMap<String, String>,
487 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
488 context_range: Range<BufferOffset>,
489}
490
491#[derive(Clone)]
492struct ResolvedTasks {
493 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
494 position: Anchor,
495}
496#[derive(Copy, Clone, Debug)]
497struct MultiBufferOffset(usize);
498#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
499struct BufferOffset(usize);
500
501// Addons allow storing per-editor state in other crates (e.g. Vim)
502pub trait Addon: 'static {
503 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
504
505 fn to_any(&self) -> &dyn std::any::Any;
506}
507
508/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
509///
510/// See the [module level documentation](self) for more information.
511pub struct Editor {
512 focus_handle: FocusHandle,
513 last_focused_descendant: Option<WeakFocusHandle>,
514 /// The text buffer being edited
515 buffer: Model<MultiBuffer>,
516 /// Map of how text in the buffer should be displayed.
517 /// Handles soft wraps, folds, fake inlay text insertions, etc.
518 pub display_map: Model<DisplayMap>,
519 pub selections: SelectionsCollection,
520 pub scroll_manager: ScrollManager,
521 /// When inline assist editors are linked, they all render cursors because
522 /// typing enters text into each of them, even the ones that aren't focused.
523 pub(crate) show_cursor_when_unfocused: bool,
524 columnar_selection_tail: Option<Anchor>,
525 add_selections_state: Option<AddSelectionsState>,
526 select_next_state: Option<SelectNextState>,
527 select_prev_state: Option<SelectNextState>,
528 selection_history: SelectionHistory,
529 autoclose_regions: Vec<AutocloseRegion>,
530 snippet_stack: InvalidationStack<SnippetState>,
531 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
532 ime_transaction: Option<TransactionId>,
533 active_diagnostics: Option<ActiveDiagnosticGroup>,
534 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
535 project: Option<Model<Project>>,
536 completion_provider: Option<Box<dyn CompletionProvider>>,
537 collaboration_hub: Option<Box<dyn CollaborationHub>>,
538 blink_manager: Model<BlinkManager>,
539 show_cursor_names: bool,
540 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
541 pub show_local_selections: bool,
542 mode: EditorMode,
543 show_breadcrumbs: bool,
544 show_gutter: bool,
545 show_line_numbers: Option<bool>,
546 use_relative_line_numbers: Option<bool>,
547 show_git_diff_gutter: Option<bool>,
548 show_code_actions: Option<bool>,
549 show_runnables: Option<bool>,
550 show_wrap_guides: Option<bool>,
551 show_indent_guides: Option<bool>,
552 placeholder_text: Option<Arc<str>>,
553 highlight_order: usize,
554 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
555 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
556 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
557 scrollbar_marker_state: ScrollbarMarkerState,
558 active_indent_guides_state: ActiveIndentGuidesState,
559 nav_history: Option<ItemNavHistory>,
560 context_menu: RwLock<Option<ContextMenu>>,
561 mouse_context_menu: Option<MouseContextMenu>,
562 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
563 signature_help_state: SignatureHelpState,
564 auto_signature_help: Option<bool>,
565 find_all_references_task_sources: Vec<Anchor>,
566 next_completion_id: CompletionId,
567 completion_documentation_pre_resolve_debounce: DebouncedDelay,
568 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
569 code_actions_task: Option<Task<()>>,
570 document_highlights_task: Option<Task<()>>,
571 linked_editing_range_task: Option<Task<Option<()>>>,
572 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
573 pending_rename: Option<RenameState>,
574 searchable: bool,
575 cursor_shape: CursorShape,
576 current_line_highlight: Option<CurrentLineHighlight>,
577 collapse_matches: bool,
578 autoindent_mode: Option<AutoindentMode>,
579 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
580 input_enabled: bool,
581 use_modal_editing: bool,
582 read_only: bool,
583 leader_peer_id: Option<PeerId>,
584 remote_id: Option<ViewId>,
585 hover_state: HoverState,
586 gutter_hovered: bool,
587 hovered_link_state: Option<HoveredLinkState>,
588 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
589 active_inline_completion: Option<CompletionState>,
590 // enable_inline_completions is a switch that Vim can use to disable
591 // inline completions based on its mode.
592 enable_inline_completions: bool,
593 show_inline_completions_override: Option<bool>,
594 inlay_hint_cache: InlayHintCache,
595 expanded_hunks: ExpandedHunks,
596 next_inlay_id: usize,
597 _subscriptions: Vec<Subscription>,
598 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
599 gutter_dimensions: GutterDimensions,
600 style: Option<EditorStyle>,
601 next_editor_action_id: EditorActionId,
602 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
603 use_autoclose: bool,
604 use_auto_surround: bool,
605 auto_replace_emoji_shortcode: bool,
606 show_git_blame_gutter: bool,
607 show_git_blame_inline: bool,
608 show_git_blame_inline_delay_task: Option<Task<()>>,
609 git_blame_inline_enabled: bool,
610 serialize_dirty_buffers: bool,
611 show_selection_menu: Option<bool>,
612 blame: Option<Model<GitBlame>>,
613 blame_subscription: Option<Subscription>,
614 custom_context_menu: Option<
615 Box<
616 dyn 'static
617 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
618 >,
619 >,
620 last_bounds: Option<Bounds<Pixels>>,
621 expect_bounds_change: Option<Bounds<Pixels>>,
622 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
623 tasks_update_task: Option<Task<()>>,
624 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
625 file_header_size: u32,
626 breadcrumb_header: Option<String>,
627 focused_block: Option<FocusedBlock>,
628 next_scroll_position: NextScrollCursorCenterTopBottom,
629 addons: HashMap<TypeId, Box<dyn Addon>>,
630 _scroll_cursor_center_top_bottom_task: Task<()>,
631}
632
633#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
634enum NextScrollCursorCenterTopBottom {
635 #[default]
636 Center,
637 Top,
638 Bottom,
639}
640
641impl NextScrollCursorCenterTopBottom {
642 fn next(&self) -> Self {
643 match self {
644 Self::Center => Self::Top,
645 Self::Top => Self::Bottom,
646 Self::Bottom => Self::Center,
647 }
648 }
649}
650
651#[derive(Clone)]
652pub struct EditorSnapshot {
653 pub mode: EditorMode,
654 show_gutter: bool,
655 show_line_numbers: Option<bool>,
656 show_git_diff_gutter: Option<bool>,
657 show_code_actions: Option<bool>,
658 show_runnables: Option<bool>,
659 render_git_blame_gutter: bool,
660 pub display_snapshot: DisplaySnapshot,
661 pub placeholder_text: Option<Arc<str>>,
662 is_focused: bool,
663 scroll_anchor: ScrollAnchor,
664 ongoing_scroll: OngoingScroll,
665 current_line_highlight: CurrentLineHighlight,
666 gutter_hovered: bool,
667}
668
669const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
670
671#[derive(Default, Debug, Clone, Copy)]
672pub struct GutterDimensions {
673 pub left_padding: Pixels,
674 pub right_padding: Pixels,
675 pub width: Pixels,
676 pub margin: Pixels,
677 pub git_blame_entries_width: Option<Pixels>,
678}
679
680impl GutterDimensions {
681 /// The full width of the space taken up by the gutter.
682 pub fn full_width(&self) -> Pixels {
683 self.margin + self.width
684 }
685
686 /// The width of the space reserved for the fold indicators,
687 /// use alongside 'justify_end' and `gutter_width` to
688 /// right align content with the line numbers
689 pub fn fold_area_width(&self) -> Pixels {
690 self.margin + self.right_padding
691 }
692}
693
694#[derive(Debug)]
695pub struct RemoteSelection {
696 pub replica_id: ReplicaId,
697 pub selection: Selection<Anchor>,
698 pub cursor_shape: CursorShape,
699 pub peer_id: PeerId,
700 pub line_mode: bool,
701 pub participant_index: Option<ParticipantIndex>,
702 pub user_name: Option<SharedString>,
703}
704
705#[derive(Clone, Debug)]
706struct SelectionHistoryEntry {
707 selections: Arc<[Selection<Anchor>]>,
708 select_next_state: Option<SelectNextState>,
709 select_prev_state: Option<SelectNextState>,
710 add_selections_state: Option<AddSelectionsState>,
711}
712
713enum SelectionHistoryMode {
714 Normal,
715 Undoing,
716 Redoing,
717}
718
719#[derive(Clone, PartialEq, Eq, Hash)]
720struct HoveredCursor {
721 replica_id: u16,
722 selection_id: usize,
723}
724
725impl Default for SelectionHistoryMode {
726 fn default() -> Self {
727 Self::Normal
728 }
729}
730
731#[derive(Default)]
732struct SelectionHistory {
733 #[allow(clippy::type_complexity)]
734 selections_by_transaction:
735 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
736 mode: SelectionHistoryMode,
737 undo_stack: VecDeque<SelectionHistoryEntry>,
738 redo_stack: VecDeque<SelectionHistoryEntry>,
739}
740
741impl SelectionHistory {
742 fn insert_transaction(
743 &mut self,
744 transaction_id: TransactionId,
745 selections: Arc<[Selection<Anchor>]>,
746 ) {
747 self.selections_by_transaction
748 .insert(transaction_id, (selections, None));
749 }
750
751 #[allow(clippy::type_complexity)]
752 fn transaction(
753 &self,
754 transaction_id: TransactionId,
755 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
756 self.selections_by_transaction.get(&transaction_id)
757 }
758
759 #[allow(clippy::type_complexity)]
760 fn transaction_mut(
761 &mut self,
762 transaction_id: TransactionId,
763 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
764 self.selections_by_transaction.get_mut(&transaction_id)
765 }
766
767 fn push(&mut self, entry: SelectionHistoryEntry) {
768 if !entry.selections.is_empty() {
769 match self.mode {
770 SelectionHistoryMode::Normal => {
771 self.push_undo(entry);
772 self.redo_stack.clear();
773 }
774 SelectionHistoryMode::Undoing => self.push_redo(entry),
775 SelectionHistoryMode::Redoing => self.push_undo(entry),
776 }
777 }
778 }
779
780 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
781 if self
782 .undo_stack
783 .back()
784 .map_or(true, |e| e.selections != entry.selections)
785 {
786 self.undo_stack.push_back(entry);
787 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
788 self.undo_stack.pop_front();
789 }
790 }
791 }
792
793 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
794 if self
795 .redo_stack
796 .back()
797 .map_or(true, |e| e.selections != entry.selections)
798 {
799 self.redo_stack.push_back(entry);
800 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
801 self.redo_stack.pop_front();
802 }
803 }
804 }
805}
806
807struct RowHighlight {
808 index: usize,
809 range: RangeInclusive<Anchor>,
810 color: Option<Hsla>,
811 should_autoscroll: bool,
812}
813
814#[derive(Clone, Debug)]
815struct AddSelectionsState {
816 above: bool,
817 stack: Vec<usize>,
818}
819
820#[derive(Clone)]
821struct SelectNextState {
822 query: AhoCorasick,
823 wordwise: bool,
824 done: bool,
825}
826
827impl std::fmt::Debug for SelectNextState {
828 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
829 f.debug_struct(std::any::type_name::<Self>())
830 .field("wordwise", &self.wordwise)
831 .field("done", &self.done)
832 .finish()
833 }
834}
835
836#[derive(Debug)]
837struct AutocloseRegion {
838 selection_id: usize,
839 range: Range<Anchor>,
840 pair: BracketPair,
841}
842
843#[derive(Debug)]
844struct SnippetState {
845 ranges: Vec<Vec<Range<Anchor>>>,
846 active_index: usize,
847}
848
849#[doc(hidden)]
850pub struct RenameState {
851 pub range: Range<Anchor>,
852 pub old_name: Arc<str>,
853 pub editor: View<Editor>,
854 block_id: CustomBlockId,
855}
856
857struct InvalidationStack<T>(Vec<T>);
858
859struct RegisteredInlineCompletionProvider {
860 provider: Arc<dyn InlineCompletionProviderHandle>,
861 _subscription: Subscription,
862}
863
864enum ContextMenu {
865 Completions(CompletionsMenu),
866 CodeActions(CodeActionsMenu),
867}
868
869impl ContextMenu {
870 fn select_first(
871 &mut self,
872 project: Option<&Model<Project>>,
873 cx: &mut ViewContext<Editor>,
874 ) -> bool {
875 if self.visible() {
876 match self {
877 ContextMenu::Completions(menu) => menu.select_first(project, cx),
878 ContextMenu::CodeActions(menu) => menu.select_first(cx),
879 }
880 true
881 } else {
882 false
883 }
884 }
885
886 fn select_prev(
887 &mut self,
888 project: Option<&Model<Project>>,
889 cx: &mut ViewContext<Editor>,
890 ) -> bool {
891 if self.visible() {
892 match self {
893 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
894 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
895 }
896 true
897 } else {
898 false
899 }
900 }
901
902 fn select_next(
903 &mut self,
904 project: Option<&Model<Project>>,
905 cx: &mut ViewContext<Editor>,
906 ) -> bool {
907 if self.visible() {
908 match self {
909 ContextMenu::Completions(menu) => menu.select_next(project, cx),
910 ContextMenu::CodeActions(menu) => menu.select_next(cx),
911 }
912 true
913 } else {
914 false
915 }
916 }
917
918 fn select_last(
919 &mut self,
920 project: Option<&Model<Project>>,
921 cx: &mut ViewContext<Editor>,
922 ) -> bool {
923 if self.visible() {
924 match self {
925 ContextMenu::Completions(menu) => menu.select_last(project, cx),
926 ContextMenu::CodeActions(menu) => menu.select_last(cx),
927 }
928 true
929 } else {
930 false
931 }
932 }
933
934 fn visible(&self) -> bool {
935 match self {
936 ContextMenu::Completions(menu) => menu.visible(),
937 ContextMenu::CodeActions(menu) => menu.visible(),
938 }
939 }
940
941 fn render(
942 &self,
943 cursor_position: DisplayPoint,
944 style: &EditorStyle,
945 max_height: Pixels,
946 workspace: Option<WeakView<Workspace>>,
947 cx: &mut ViewContext<Editor>,
948 ) -> (ContextMenuOrigin, AnyElement) {
949 match self {
950 ContextMenu::Completions(menu) => (
951 ContextMenuOrigin::EditorPoint(cursor_position),
952 menu.render(style, max_height, workspace, cx),
953 ),
954 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
955 }
956 }
957}
958
959enum ContextMenuOrigin {
960 EditorPoint(DisplayPoint),
961 GutterIndicator(DisplayRow),
962}
963
964#[derive(Clone)]
965struct CompletionsMenu {
966 id: CompletionId,
967 sort_completions: bool,
968 initial_position: Anchor,
969 buffer: Model<Buffer>,
970 completions: Arc<RwLock<Box<[Completion]>>>,
971 match_candidates: Arc<[StringMatchCandidate]>,
972 matches: Arc<[StringMatch]>,
973 selected_item: usize,
974 scroll_handle: UniformListScrollHandle,
975 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
976}
977
978impl CompletionsMenu {
979 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
980 self.selected_item = 0;
981 self.scroll_handle.scroll_to_item(self.selected_item);
982 self.attempt_resolve_selected_completion_documentation(project, cx);
983 cx.notify();
984 }
985
986 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
987 if self.selected_item > 0 {
988 self.selected_item -= 1;
989 } else {
990 self.selected_item = self.matches.len() - 1;
991 }
992 self.scroll_handle.scroll_to_item(self.selected_item);
993 self.attempt_resolve_selected_completion_documentation(project, cx);
994 cx.notify();
995 }
996
997 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
998 if self.selected_item + 1 < self.matches.len() {
999 self.selected_item += 1;
1000 } else {
1001 self.selected_item = 0;
1002 }
1003 self.scroll_handle.scroll_to_item(self.selected_item);
1004 self.attempt_resolve_selected_completion_documentation(project, cx);
1005 cx.notify();
1006 }
1007
1008 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
1009 self.selected_item = self.matches.len() - 1;
1010 self.scroll_handle.scroll_to_item(self.selected_item);
1011 self.attempt_resolve_selected_completion_documentation(project, cx);
1012 cx.notify();
1013 }
1014
1015 fn pre_resolve_completion_documentation(
1016 buffer: Model<Buffer>,
1017 completions: Arc<RwLock<Box<[Completion]>>>,
1018 matches: Arc<[StringMatch]>,
1019 editor: &Editor,
1020 cx: &mut ViewContext<Editor>,
1021 ) -> Task<()> {
1022 let settings = EditorSettings::get_global(cx);
1023 if !settings.show_completion_documentation {
1024 return Task::ready(());
1025 }
1026
1027 let Some(provider) = editor.completion_provider.as_ref() else {
1028 return Task::ready(());
1029 };
1030
1031 let resolve_task = provider.resolve_completions(
1032 buffer,
1033 matches.iter().map(|m| m.candidate_id).collect(),
1034 completions.clone(),
1035 cx,
1036 );
1037
1038 cx.spawn(move |this, mut cx| async move {
1039 if let Some(true) = resolve_task.await.log_err() {
1040 this.update(&mut cx, |_, cx| cx.notify()).ok();
1041 }
1042 })
1043 }
1044
1045 fn attempt_resolve_selected_completion_documentation(
1046 &mut self,
1047 project: Option<&Model<Project>>,
1048 cx: &mut ViewContext<Editor>,
1049 ) {
1050 let settings = EditorSettings::get_global(cx);
1051 if !settings.show_completion_documentation {
1052 return;
1053 }
1054
1055 let completion_index = self.matches[self.selected_item].candidate_id;
1056 let Some(project) = project else {
1057 return;
1058 };
1059
1060 let resolve_task = project.update(cx, |project, cx| {
1061 project.resolve_completions(
1062 self.buffer.clone(),
1063 vec![completion_index],
1064 self.completions.clone(),
1065 cx,
1066 )
1067 });
1068
1069 let delay_ms =
1070 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1071 let delay = Duration::from_millis(delay_ms);
1072
1073 self.selected_completion_documentation_resolve_debounce
1074 .lock()
1075 .fire_new(delay, cx, |_, cx| {
1076 cx.spawn(move |this, mut cx| async move {
1077 if let Some(true) = resolve_task.await.log_err() {
1078 this.update(&mut cx, |_, cx| cx.notify()).ok();
1079 }
1080 })
1081 });
1082 }
1083
1084 fn visible(&self) -> bool {
1085 !self.matches.is_empty()
1086 }
1087
1088 fn render(
1089 &self,
1090 style: &EditorStyle,
1091 max_height: Pixels,
1092 workspace: Option<WeakView<Workspace>>,
1093 cx: &mut ViewContext<Editor>,
1094 ) -> AnyElement {
1095 let settings = EditorSettings::get_global(cx);
1096 let show_completion_documentation = settings.show_completion_documentation;
1097
1098 let widest_completion_ix = self
1099 .matches
1100 .iter()
1101 .enumerate()
1102 .max_by_key(|(_, mat)| {
1103 let completions = self.completions.read();
1104 let completion = &completions[mat.candidate_id];
1105 let documentation = &completion.documentation;
1106
1107 let mut len = completion.label.text.chars().count();
1108 if let Some(Documentation::SingleLine(text)) = documentation {
1109 if show_completion_documentation {
1110 len += text.chars().count();
1111 }
1112 }
1113
1114 len
1115 })
1116 .map(|(ix, _)| ix);
1117
1118 let completions = self.completions.clone();
1119 let matches = self.matches.clone();
1120 let selected_item = self.selected_item;
1121 let style = style.clone();
1122
1123 let multiline_docs = if show_completion_documentation {
1124 let mat = &self.matches[selected_item];
1125 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1126 Some(Documentation::MultiLinePlainText(text)) => {
1127 Some(div().child(SharedString::from(text.clone())))
1128 }
1129 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1130 Some(div().child(render_parsed_markdown(
1131 "completions_markdown",
1132 parsed,
1133 &style,
1134 workspace,
1135 cx,
1136 )))
1137 }
1138 _ => None,
1139 };
1140 multiline_docs.map(|div| {
1141 div.id("multiline_docs")
1142 .max_h(max_height)
1143 .flex_1()
1144 .px_1p5()
1145 .py_1()
1146 .min_w(px(260.))
1147 .max_w(px(640.))
1148 .w(px(500.))
1149 .overflow_y_scroll()
1150 .occlude()
1151 })
1152 } else {
1153 None
1154 };
1155
1156 let list = uniform_list(
1157 cx.view().clone(),
1158 "completions",
1159 matches.len(),
1160 move |_editor, range, cx| {
1161 let start_ix = range.start;
1162 let completions_guard = completions.read();
1163
1164 matches[range]
1165 .iter()
1166 .enumerate()
1167 .map(|(ix, mat)| {
1168 let item_ix = start_ix + ix;
1169 let candidate_id = mat.candidate_id;
1170 let completion = &completions_guard[candidate_id];
1171
1172 let documentation = if show_completion_documentation {
1173 &completion.documentation
1174 } else {
1175 &None
1176 };
1177
1178 let highlights = gpui::combine_highlights(
1179 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1180 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1181 |(range, mut highlight)| {
1182 // Ignore font weight for syntax highlighting, as we'll use it
1183 // for fuzzy matches.
1184 highlight.font_weight = None;
1185
1186 if completion.lsp_completion.deprecated.unwrap_or(false) {
1187 highlight.strikethrough = Some(StrikethroughStyle {
1188 thickness: 1.0.into(),
1189 ..Default::default()
1190 });
1191 highlight.color = Some(cx.theme().colors().text_muted);
1192 }
1193
1194 (range, highlight)
1195 },
1196 ),
1197 );
1198 let completion_label = StyledText::new(completion.label.text.clone())
1199 .with_highlights(&style.text, highlights);
1200 let documentation_label =
1201 if let Some(Documentation::SingleLine(text)) = documentation {
1202 if text.trim().is_empty() {
1203 None
1204 } else {
1205 Some(
1206 Label::new(text.clone())
1207 .ml_4()
1208 .size(LabelSize::Small)
1209 .color(Color::Muted),
1210 )
1211 }
1212 } else {
1213 None
1214 };
1215
1216 div().min_w(px(220.)).max_w(px(540.)).child(
1217 ListItem::new(mat.candidate_id)
1218 .inset(true)
1219 .selected(item_ix == selected_item)
1220 .on_click(cx.listener(move |editor, _event, cx| {
1221 cx.stop_propagation();
1222 if let Some(task) = editor.confirm_completion(
1223 &ConfirmCompletion {
1224 item_ix: Some(item_ix),
1225 },
1226 cx,
1227 ) {
1228 task.detach_and_log_err(cx)
1229 }
1230 }))
1231 .child(h_flex().overflow_hidden().child(completion_label))
1232 .end_slot::<Label>(documentation_label),
1233 )
1234 })
1235 .collect()
1236 },
1237 )
1238 .occlude()
1239 .max_h(max_height)
1240 .track_scroll(self.scroll_handle.clone())
1241 .with_width_from_item(widest_completion_ix)
1242 .with_sizing_behavior(ListSizingBehavior::Infer);
1243
1244 Popover::new()
1245 .child(list)
1246 .when_some(multiline_docs, |popover, multiline_docs| {
1247 popover.aside(multiline_docs)
1248 })
1249 .into_any_element()
1250 }
1251
1252 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1253 let mut matches = if let Some(query) = query {
1254 fuzzy::match_strings(
1255 &self.match_candidates,
1256 query,
1257 query.chars().any(|c| c.is_uppercase()),
1258 100,
1259 &Default::default(),
1260 executor,
1261 )
1262 .await
1263 } else {
1264 self.match_candidates
1265 .iter()
1266 .enumerate()
1267 .map(|(candidate_id, candidate)| StringMatch {
1268 candidate_id,
1269 score: Default::default(),
1270 positions: Default::default(),
1271 string: candidate.string.clone(),
1272 })
1273 .collect()
1274 };
1275
1276 // Remove all candidates where the query's start does not match the start of any word in the candidate
1277 if let Some(query) = query {
1278 if let Some(query_start) = query.chars().next() {
1279 matches.retain(|string_match| {
1280 split_words(&string_match.string).any(|word| {
1281 // Check that the first codepoint of the word as lowercase matches the first
1282 // codepoint of the query as lowercase
1283 word.chars()
1284 .flat_map(|codepoint| codepoint.to_lowercase())
1285 .zip(query_start.to_lowercase())
1286 .all(|(word_cp, query_cp)| word_cp == query_cp)
1287 })
1288 });
1289 }
1290 }
1291
1292 let completions = self.completions.read();
1293 if self.sort_completions {
1294 matches.sort_unstable_by_key(|mat| {
1295 // We do want to strike a balance here between what the language server tells us
1296 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1297 // `Creat` and there is a local variable called `CreateComponent`).
1298 // So what we do is: we bucket all matches into two buckets
1299 // - Strong matches
1300 // - Weak matches
1301 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1302 // and the Weak matches are the rest.
1303 //
1304 // For the strong matches, we sort by the language-servers score first and for the weak
1305 // matches, we prefer our fuzzy finder first.
1306 //
1307 // The thinking behind that: it's useless to take the sort_text the language-server gives
1308 // us into account when it's obviously a bad match.
1309
1310 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1311 enum MatchScore<'a> {
1312 Strong {
1313 sort_text: Option<&'a str>,
1314 score: Reverse<OrderedFloat<f64>>,
1315 sort_key: (usize, &'a str),
1316 },
1317 Weak {
1318 score: Reverse<OrderedFloat<f64>>,
1319 sort_text: Option<&'a str>,
1320 sort_key: (usize, &'a str),
1321 },
1322 }
1323
1324 let completion = &completions[mat.candidate_id];
1325 let sort_key = completion.sort_key();
1326 let sort_text = completion.lsp_completion.sort_text.as_deref();
1327 let score = Reverse(OrderedFloat(mat.score));
1328
1329 if mat.score >= 0.2 {
1330 MatchScore::Strong {
1331 sort_text,
1332 score,
1333 sort_key,
1334 }
1335 } else {
1336 MatchScore::Weak {
1337 score,
1338 sort_text,
1339 sort_key,
1340 }
1341 }
1342 });
1343 }
1344
1345 for mat in &mut matches {
1346 let completion = &completions[mat.candidate_id];
1347 mat.string.clone_from(&completion.label.text);
1348 for position in &mut mat.positions {
1349 *position += completion.label.filter_range.start;
1350 }
1351 }
1352 drop(completions);
1353
1354 self.matches = matches.into();
1355 self.selected_item = 0;
1356 }
1357}
1358
1359#[derive(Clone)]
1360struct CodeActionContents {
1361 tasks: Option<Arc<ResolvedTasks>>,
1362 actions: Option<Arc<[CodeAction]>>,
1363}
1364
1365impl CodeActionContents {
1366 fn len(&self) -> usize {
1367 match (&self.tasks, &self.actions) {
1368 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1369 (Some(tasks), None) => tasks.templates.len(),
1370 (None, Some(actions)) => actions.len(),
1371 (None, None) => 0,
1372 }
1373 }
1374
1375 fn is_empty(&self) -> bool {
1376 match (&self.tasks, &self.actions) {
1377 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1378 (Some(tasks), None) => tasks.templates.is_empty(),
1379 (None, Some(actions)) => actions.is_empty(),
1380 (None, None) => true,
1381 }
1382 }
1383
1384 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1385 self.tasks
1386 .iter()
1387 .flat_map(|tasks| {
1388 tasks
1389 .templates
1390 .iter()
1391 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1392 })
1393 .chain(self.actions.iter().flat_map(|actions| {
1394 actions
1395 .iter()
1396 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1397 }))
1398 }
1399 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1400 match (&self.tasks, &self.actions) {
1401 (Some(tasks), Some(actions)) => {
1402 if index < tasks.templates.len() {
1403 tasks
1404 .templates
1405 .get(index)
1406 .cloned()
1407 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1408 } else {
1409 actions
1410 .get(index - tasks.templates.len())
1411 .cloned()
1412 .map(CodeActionsItem::CodeAction)
1413 }
1414 }
1415 (Some(tasks), None) => tasks
1416 .templates
1417 .get(index)
1418 .cloned()
1419 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1420 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1421 (None, None) => None,
1422 }
1423 }
1424}
1425
1426#[allow(clippy::large_enum_variant)]
1427#[derive(Clone)]
1428enum CodeActionsItem {
1429 Task(TaskSourceKind, ResolvedTask),
1430 CodeAction(CodeAction),
1431}
1432
1433impl CodeActionsItem {
1434 fn as_task(&self) -> Option<&ResolvedTask> {
1435 let Self::Task(_, task) = self else {
1436 return None;
1437 };
1438 Some(task)
1439 }
1440 fn as_code_action(&self) -> Option<&CodeAction> {
1441 let Self::CodeAction(action) = self else {
1442 return None;
1443 };
1444 Some(action)
1445 }
1446 fn label(&self) -> String {
1447 match self {
1448 Self::CodeAction(action) => action.lsp_action.title.clone(),
1449 Self::Task(_, task) => task.resolved_label.clone(),
1450 }
1451 }
1452}
1453
1454struct CodeActionsMenu {
1455 actions: CodeActionContents,
1456 buffer: Model<Buffer>,
1457 selected_item: usize,
1458 scroll_handle: UniformListScrollHandle,
1459 deployed_from_indicator: Option<DisplayRow>,
1460}
1461
1462impl CodeActionsMenu {
1463 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1464 self.selected_item = 0;
1465 self.scroll_handle.scroll_to_item(self.selected_item);
1466 cx.notify()
1467 }
1468
1469 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1470 if self.selected_item > 0 {
1471 self.selected_item -= 1;
1472 } else {
1473 self.selected_item = self.actions.len() - 1;
1474 }
1475 self.scroll_handle.scroll_to_item(self.selected_item);
1476 cx.notify();
1477 }
1478
1479 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1480 if self.selected_item + 1 < self.actions.len() {
1481 self.selected_item += 1;
1482 } else {
1483 self.selected_item = 0;
1484 }
1485 self.scroll_handle.scroll_to_item(self.selected_item);
1486 cx.notify();
1487 }
1488
1489 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1490 self.selected_item = self.actions.len() - 1;
1491 self.scroll_handle.scroll_to_item(self.selected_item);
1492 cx.notify()
1493 }
1494
1495 fn visible(&self) -> bool {
1496 !self.actions.is_empty()
1497 }
1498
1499 fn render(
1500 &self,
1501 cursor_position: DisplayPoint,
1502 _style: &EditorStyle,
1503 max_height: Pixels,
1504 cx: &mut ViewContext<Editor>,
1505 ) -> (ContextMenuOrigin, AnyElement) {
1506 let actions = self.actions.clone();
1507 let selected_item = self.selected_item;
1508 let element = uniform_list(
1509 cx.view().clone(),
1510 "code_actions_menu",
1511 self.actions.len(),
1512 move |_this, range, cx| {
1513 actions
1514 .iter()
1515 .skip(range.start)
1516 .take(range.end - range.start)
1517 .enumerate()
1518 .map(|(ix, action)| {
1519 let item_ix = range.start + ix;
1520 let selected = selected_item == item_ix;
1521 let colors = cx.theme().colors();
1522 div()
1523 .px_1()
1524 .rounded_md()
1525 .text_color(colors.text)
1526 .when(selected, |style| {
1527 style
1528 .bg(colors.element_active)
1529 .text_color(colors.text_accent)
1530 })
1531 .hover(|style| {
1532 style
1533 .bg(colors.element_hover)
1534 .text_color(colors.text_accent)
1535 })
1536 .whitespace_nowrap()
1537 .when_some(action.as_code_action(), |this, action| {
1538 this.on_mouse_down(
1539 MouseButton::Left,
1540 cx.listener(move |editor, _, cx| {
1541 cx.stop_propagation();
1542 if let Some(task) = editor.confirm_code_action(
1543 &ConfirmCodeAction {
1544 item_ix: Some(item_ix),
1545 },
1546 cx,
1547 ) {
1548 task.detach_and_log_err(cx)
1549 }
1550 }),
1551 )
1552 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1553 .child(SharedString::from(action.lsp_action.title.clone()))
1554 })
1555 .when_some(action.as_task(), |this, task| {
1556 this.on_mouse_down(
1557 MouseButton::Left,
1558 cx.listener(move |editor, _, cx| {
1559 cx.stop_propagation();
1560 if let Some(task) = editor.confirm_code_action(
1561 &ConfirmCodeAction {
1562 item_ix: Some(item_ix),
1563 },
1564 cx,
1565 ) {
1566 task.detach_and_log_err(cx)
1567 }
1568 }),
1569 )
1570 .child(SharedString::from(task.resolved_label.clone()))
1571 })
1572 })
1573 .collect()
1574 },
1575 )
1576 .elevation_1(cx)
1577 .p_1()
1578 .max_h(max_height)
1579 .occlude()
1580 .track_scroll(self.scroll_handle.clone())
1581 .with_width_from_item(
1582 self.actions
1583 .iter()
1584 .enumerate()
1585 .max_by_key(|(_, action)| match action {
1586 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1587 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1588 })
1589 .map(|(ix, _)| ix),
1590 )
1591 .with_sizing_behavior(ListSizingBehavior::Infer)
1592 .into_any_element();
1593
1594 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1595 ContextMenuOrigin::GutterIndicator(row)
1596 } else {
1597 ContextMenuOrigin::EditorPoint(cursor_position)
1598 };
1599
1600 (cursor_position, element)
1601 }
1602}
1603
1604#[derive(Debug)]
1605struct ActiveDiagnosticGroup {
1606 primary_range: Range<Anchor>,
1607 primary_message: String,
1608 group_id: usize,
1609 blocks: HashMap<CustomBlockId, Diagnostic>,
1610 is_valid: bool,
1611}
1612
1613#[derive(Serialize, Deserialize, Clone, Debug)]
1614pub struct ClipboardSelection {
1615 pub len: usize,
1616 pub is_entire_line: bool,
1617 pub first_line_indent: u32,
1618}
1619
1620#[derive(Debug)]
1621pub(crate) struct NavigationData {
1622 cursor_anchor: Anchor,
1623 cursor_position: Point,
1624 scroll_anchor: ScrollAnchor,
1625 scroll_top_row: u32,
1626}
1627
1628#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1629enum GotoDefinitionKind {
1630 Symbol,
1631 Declaration,
1632 Type,
1633 Implementation,
1634}
1635
1636#[derive(Debug, Clone)]
1637enum InlayHintRefreshReason {
1638 Toggle(bool),
1639 SettingsChange(InlayHintSettings),
1640 NewLinesShown,
1641 BufferEdited(HashSet<Arc<Language>>),
1642 RefreshRequested,
1643 ExcerptsRemoved(Vec<ExcerptId>),
1644}
1645
1646impl InlayHintRefreshReason {
1647 fn description(&self) -> &'static str {
1648 match self {
1649 Self::Toggle(_) => "toggle",
1650 Self::SettingsChange(_) => "settings change",
1651 Self::NewLinesShown => "new lines shown",
1652 Self::BufferEdited(_) => "buffer edited",
1653 Self::RefreshRequested => "refresh requested",
1654 Self::ExcerptsRemoved(_) => "excerpts removed",
1655 }
1656 }
1657}
1658
1659pub(crate) struct FocusedBlock {
1660 id: BlockId,
1661 focus_handle: WeakFocusHandle,
1662}
1663
1664impl Editor {
1665 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1666 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1667 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1668 Self::new(
1669 EditorMode::SingleLine { auto_width: false },
1670 buffer,
1671 None,
1672 false,
1673 cx,
1674 )
1675 }
1676
1677 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1678 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1679 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1680 Self::new(EditorMode::Full, buffer, None, false, cx)
1681 }
1682
1683 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1684 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1685 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1686 Self::new(
1687 EditorMode::SingleLine { auto_width: true },
1688 buffer,
1689 None,
1690 false,
1691 cx,
1692 )
1693 }
1694
1695 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1696 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1697 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1698 Self::new(
1699 EditorMode::AutoHeight { max_lines },
1700 buffer,
1701 None,
1702 false,
1703 cx,
1704 )
1705 }
1706
1707 pub fn for_buffer(
1708 buffer: Model<Buffer>,
1709 project: Option<Model<Project>>,
1710 cx: &mut ViewContext<Self>,
1711 ) -> Self {
1712 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1713 Self::new(EditorMode::Full, buffer, project, false, cx)
1714 }
1715
1716 pub fn for_multibuffer(
1717 buffer: Model<MultiBuffer>,
1718 project: Option<Model<Project>>,
1719 show_excerpt_controls: bool,
1720 cx: &mut ViewContext<Self>,
1721 ) -> Self {
1722 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1723 }
1724
1725 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1726 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1727 let mut clone = Self::new(
1728 self.mode,
1729 self.buffer.clone(),
1730 self.project.clone(),
1731 show_excerpt_controls,
1732 cx,
1733 );
1734 self.display_map.update(cx, |display_map, cx| {
1735 let snapshot = display_map.snapshot(cx);
1736 clone.display_map.update(cx, |display_map, cx| {
1737 display_map.set_state(&snapshot, cx);
1738 });
1739 });
1740 clone.selections.clone_state(&self.selections);
1741 clone.scroll_manager.clone_state(&self.scroll_manager);
1742 clone.searchable = self.searchable;
1743 clone
1744 }
1745
1746 pub fn new(
1747 mode: EditorMode,
1748 buffer: Model<MultiBuffer>,
1749 project: Option<Model<Project>>,
1750 show_excerpt_controls: bool,
1751 cx: &mut ViewContext<Self>,
1752 ) -> Self {
1753 let style = cx.text_style();
1754 let font_size = style.font_size.to_pixels(cx.rem_size());
1755 let editor = cx.view().downgrade();
1756 let fold_placeholder = FoldPlaceholder {
1757 constrain_width: true,
1758 render: Arc::new(move |fold_id, fold_range, cx| {
1759 let editor = editor.clone();
1760 div()
1761 .id(fold_id)
1762 .bg(cx.theme().colors().ghost_element_background)
1763 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1764 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1765 .rounded_sm()
1766 .size_full()
1767 .cursor_pointer()
1768 .child("⋯")
1769 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1770 .on_click(move |_, cx| {
1771 editor
1772 .update(cx, |editor, cx| {
1773 editor.unfold_ranges(
1774 [fold_range.start..fold_range.end],
1775 true,
1776 false,
1777 cx,
1778 );
1779 cx.stop_propagation();
1780 })
1781 .ok();
1782 })
1783 .into_any()
1784 }),
1785 merge_adjacent: true,
1786 };
1787 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1788 let display_map = cx.new_model(|cx| {
1789 DisplayMap::new(
1790 buffer.clone(),
1791 style.font(),
1792 font_size,
1793 None,
1794 show_excerpt_controls,
1795 file_header_size,
1796 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1797 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1798 fold_placeholder,
1799 cx,
1800 )
1801 });
1802
1803 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1804
1805 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1806
1807 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1808 .then(|| language_settings::SoftWrap::PreferLine);
1809
1810 let mut project_subscriptions = Vec::new();
1811 if mode == EditorMode::Full {
1812 if let Some(project) = project.as_ref() {
1813 if buffer.read(cx).is_singleton() {
1814 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1815 cx.emit(EditorEvent::TitleChanged);
1816 }));
1817 }
1818 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1819 if let project::Event::RefreshInlayHints = event {
1820 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1821 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1822 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1823 let focus_handle = editor.focus_handle(cx);
1824 if focus_handle.is_focused(cx) {
1825 let snapshot = buffer.read(cx).snapshot();
1826 for (range, snippet) in snippet_edits {
1827 let editor_range =
1828 language::range_from_lsp(*range).to_offset(&snapshot);
1829 editor
1830 .insert_snippet(&[editor_range], snippet.clone(), cx)
1831 .ok();
1832 }
1833 }
1834 }
1835 }
1836 }));
1837 let task_inventory = project.read(cx).task_inventory().clone();
1838 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1839 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1840 }));
1841 }
1842 }
1843
1844 let inlay_hint_settings = inlay_hint_settings(
1845 selections.newest_anchor().head(),
1846 &buffer.read(cx).snapshot(cx),
1847 cx,
1848 );
1849 let focus_handle = cx.focus_handle();
1850 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1851 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1852 .detach();
1853 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1854 .detach();
1855 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1856
1857 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1858 Some(false)
1859 } else {
1860 None
1861 };
1862
1863 let mut this = Self {
1864 focus_handle,
1865 show_cursor_when_unfocused: false,
1866 last_focused_descendant: None,
1867 buffer: buffer.clone(),
1868 display_map: display_map.clone(),
1869 selections,
1870 scroll_manager: ScrollManager::new(cx),
1871 columnar_selection_tail: None,
1872 add_selections_state: None,
1873 select_next_state: None,
1874 select_prev_state: None,
1875 selection_history: Default::default(),
1876 autoclose_regions: Default::default(),
1877 snippet_stack: Default::default(),
1878 select_larger_syntax_node_stack: Vec::new(),
1879 ime_transaction: Default::default(),
1880 active_diagnostics: None,
1881 soft_wrap_mode_override,
1882 completion_provider: project.clone().map(|project| Box::new(project) as _),
1883 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1884 project,
1885 blink_manager: blink_manager.clone(),
1886 show_local_selections: true,
1887 mode,
1888 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1889 show_gutter: mode == EditorMode::Full,
1890 show_line_numbers: None,
1891 use_relative_line_numbers: None,
1892 show_git_diff_gutter: None,
1893 show_code_actions: None,
1894 show_runnables: None,
1895 show_wrap_guides: None,
1896 show_indent_guides,
1897 placeholder_text: None,
1898 highlight_order: 0,
1899 highlighted_rows: HashMap::default(),
1900 background_highlights: Default::default(),
1901 gutter_highlights: TreeMap::default(),
1902 scrollbar_marker_state: ScrollbarMarkerState::default(),
1903 active_indent_guides_state: ActiveIndentGuidesState::default(),
1904 nav_history: None,
1905 context_menu: RwLock::new(None),
1906 mouse_context_menu: None,
1907 completion_tasks: Default::default(),
1908 signature_help_state: SignatureHelpState::default(),
1909 auto_signature_help: None,
1910 find_all_references_task_sources: Vec::new(),
1911 next_completion_id: 0,
1912 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1913 next_inlay_id: 0,
1914 available_code_actions: Default::default(),
1915 code_actions_task: Default::default(),
1916 document_highlights_task: Default::default(),
1917 linked_editing_range_task: Default::default(),
1918 pending_rename: Default::default(),
1919 searchable: true,
1920 cursor_shape: EditorSettings::get_global(cx)
1921 .cursor_shape
1922 .unwrap_or_default(),
1923 current_line_highlight: None,
1924 autoindent_mode: Some(AutoindentMode::EachLine),
1925 collapse_matches: false,
1926 workspace: None,
1927 input_enabled: true,
1928 use_modal_editing: mode == EditorMode::Full,
1929 read_only: false,
1930 use_autoclose: true,
1931 use_auto_surround: true,
1932 auto_replace_emoji_shortcode: false,
1933 leader_peer_id: None,
1934 remote_id: None,
1935 hover_state: Default::default(),
1936 hovered_link_state: Default::default(),
1937 inline_completion_provider: None,
1938 active_inline_completion: None,
1939 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1940 expanded_hunks: ExpandedHunks::default(),
1941 gutter_hovered: false,
1942 pixel_position_of_newest_cursor: None,
1943 last_bounds: None,
1944 expect_bounds_change: None,
1945 gutter_dimensions: GutterDimensions::default(),
1946 style: None,
1947 show_cursor_names: false,
1948 hovered_cursors: Default::default(),
1949 next_editor_action_id: EditorActionId::default(),
1950 editor_actions: Rc::default(),
1951 show_inline_completions_override: None,
1952 enable_inline_completions: true,
1953 custom_context_menu: None,
1954 show_git_blame_gutter: false,
1955 show_git_blame_inline: false,
1956 show_selection_menu: None,
1957 show_git_blame_inline_delay_task: None,
1958 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1959 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1960 .session
1961 .restore_unsaved_buffers,
1962 blame: None,
1963 blame_subscription: None,
1964 file_header_size,
1965 tasks: Default::default(),
1966 _subscriptions: vec![
1967 cx.observe(&buffer, Self::on_buffer_changed),
1968 cx.subscribe(&buffer, Self::on_buffer_event),
1969 cx.observe(&display_map, Self::on_display_map_changed),
1970 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1971 cx.observe_global::<SettingsStore>(Self::settings_changed),
1972 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1973 cx.observe_window_activation(|editor, cx| {
1974 let active = cx.is_window_active();
1975 editor.blink_manager.update(cx, |blink_manager, cx| {
1976 if active {
1977 blink_manager.enable(cx);
1978 } else {
1979 blink_manager.disable(cx);
1980 }
1981 });
1982 }),
1983 ],
1984 tasks_update_task: None,
1985 linked_edit_ranges: Default::default(),
1986 previous_search_ranges: None,
1987 breadcrumb_header: None,
1988 focused_block: None,
1989 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1990 addons: HashMap::default(),
1991 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1992 };
1993 this.tasks_update_task = Some(this.refresh_runnables(cx));
1994 this._subscriptions.extend(project_subscriptions);
1995
1996 this.end_selection(cx);
1997 this.scroll_manager.show_scrollbar(cx);
1998
1999 if mode == EditorMode::Full {
2000 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2001 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2002
2003 if this.git_blame_inline_enabled {
2004 this.git_blame_inline_enabled = true;
2005 this.start_git_blame_inline(false, cx);
2006 }
2007 }
2008
2009 this.report_editor_event("open", None, cx);
2010 this
2011 }
2012
2013 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2014 self.mouse_context_menu
2015 .as_ref()
2016 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2017 }
2018
2019 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2020 let mut key_context = KeyContext::new_with_defaults();
2021 key_context.add("Editor");
2022 let mode = match self.mode {
2023 EditorMode::SingleLine { .. } => "single_line",
2024 EditorMode::AutoHeight { .. } => "auto_height",
2025 EditorMode::Full => "full",
2026 };
2027
2028 if EditorSettings::jupyter_enabled(cx) {
2029 key_context.add("jupyter");
2030 }
2031
2032 key_context.set("mode", mode);
2033 if self.pending_rename.is_some() {
2034 key_context.add("renaming");
2035 }
2036 if self.context_menu_visible() {
2037 match self.context_menu.read().as_ref() {
2038 Some(ContextMenu::Completions(_)) => {
2039 key_context.add("menu");
2040 key_context.add("showing_completions")
2041 }
2042 Some(ContextMenu::CodeActions(_)) => {
2043 key_context.add("menu");
2044 key_context.add("showing_code_actions")
2045 }
2046 None => {}
2047 }
2048 }
2049
2050 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2051 if !self.focus_handle(cx).contains_focused(cx)
2052 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2053 {
2054 for addon in self.addons.values() {
2055 addon.extend_key_context(&mut key_context, cx)
2056 }
2057 }
2058
2059 if let Some(extension) = self
2060 .buffer
2061 .read(cx)
2062 .as_singleton()
2063 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2064 {
2065 key_context.set("extension", extension.to_string());
2066 }
2067
2068 if self.has_active_inline_completion(cx) {
2069 key_context.add("copilot_suggestion");
2070 key_context.add("inline_completion");
2071 }
2072
2073 key_context
2074 }
2075
2076 pub fn new_file(
2077 workspace: &mut Workspace,
2078 _: &workspace::NewFile,
2079 cx: &mut ViewContext<Workspace>,
2080 ) {
2081 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2082 "Failed to create buffer",
2083 cx,
2084 |e, _| match e.error_code() {
2085 ErrorCode::RemoteUpgradeRequired => Some(format!(
2086 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2087 e.error_tag("required").unwrap_or("the latest version")
2088 )),
2089 _ => None,
2090 },
2091 );
2092 }
2093
2094 pub fn new_in_workspace(
2095 workspace: &mut Workspace,
2096 cx: &mut ViewContext<Workspace>,
2097 ) -> Task<Result<View<Editor>>> {
2098 let project = workspace.project().clone();
2099 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2100
2101 cx.spawn(|workspace, mut cx| async move {
2102 let buffer = create.await?;
2103 workspace.update(&mut cx, |workspace, cx| {
2104 let editor =
2105 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2106 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2107 editor
2108 })
2109 })
2110 }
2111
2112 fn new_file_vertical(
2113 workspace: &mut Workspace,
2114 _: &workspace::NewFileSplitVertical,
2115 cx: &mut ViewContext<Workspace>,
2116 ) {
2117 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2118 }
2119
2120 fn new_file_horizontal(
2121 workspace: &mut Workspace,
2122 _: &workspace::NewFileSplitHorizontal,
2123 cx: &mut ViewContext<Workspace>,
2124 ) {
2125 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2126 }
2127
2128 fn new_file_in_direction(
2129 workspace: &mut Workspace,
2130 direction: SplitDirection,
2131 cx: &mut ViewContext<Workspace>,
2132 ) {
2133 let project = workspace.project().clone();
2134 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2135
2136 cx.spawn(|workspace, mut cx| async move {
2137 let buffer = create.await?;
2138 workspace.update(&mut cx, move |workspace, cx| {
2139 workspace.split_item(
2140 direction,
2141 Box::new(
2142 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2143 ),
2144 cx,
2145 )
2146 })?;
2147 anyhow::Ok(())
2148 })
2149 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2150 ErrorCode::RemoteUpgradeRequired => Some(format!(
2151 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2152 e.error_tag("required").unwrap_or("the latest version")
2153 )),
2154 _ => None,
2155 });
2156 }
2157
2158 pub fn leader_peer_id(&self) -> Option<PeerId> {
2159 self.leader_peer_id
2160 }
2161
2162 pub fn buffer(&self) -> &Model<MultiBuffer> {
2163 &self.buffer
2164 }
2165
2166 pub fn workspace(&self) -> Option<View<Workspace>> {
2167 self.workspace.as_ref()?.0.upgrade()
2168 }
2169
2170 pub fn title<'a>(&self, cx: &'a AppContext) -> Cow<'a, str> {
2171 self.buffer().read(cx).title(cx)
2172 }
2173
2174 pub fn snapshot(&mut self, cx: &mut WindowContext) -> EditorSnapshot {
2175 EditorSnapshot {
2176 mode: self.mode,
2177 show_gutter: self.show_gutter,
2178 show_line_numbers: self.show_line_numbers,
2179 show_git_diff_gutter: self.show_git_diff_gutter,
2180 show_code_actions: self.show_code_actions,
2181 show_runnables: self.show_runnables,
2182 render_git_blame_gutter: self.render_git_blame_gutter(cx),
2183 display_snapshot: self.display_map.update(cx, |map, cx| map.snapshot(cx)),
2184 scroll_anchor: self.scroll_manager.anchor(),
2185 ongoing_scroll: self.scroll_manager.ongoing_scroll(),
2186 placeholder_text: self.placeholder_text.clone(),
2187 is_focused: self.focus_handle.is_focused(cx),
2188 current_line_highlight: self
2189 .current_line_highlight
2190 .unwrap_or_else(|| EditorSettings::get_global(cx).current_line_highlight),
2191 gutter_hovered: self.gutter_hovered,
2192 }
2193 }
2194
2195 pub fn language_at<T: ToOffset>(&self, point: T, cx: &AppContext) -> Option<Arc<Language>> {
2196 self.buffer.read(cx).language_at(point, cx)
2197 }
2198
2199 pub fn file_at<T: ToOffset>(
2200 &self,
2201 point: T,
2202 cx: &AppContext,
2203 ) -> Option<Arc<dyn language::File>> {
2204 self.buffer.read(cx).read(cx).file_at(point).cloned()
2205 }
2206
2207 pub fn active_excerpt(
2208 &self,
2209 cx: &AppContext,
2210 ) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
2211 self.buffer
2212 .read(cx)
2213 .excerpt_containing(self.selections.newest_anchor().head(), cx)
2214 }
2215
2216 pub fn mode(&self) -> EditorMode {
2217 self.mode
2218 }
2219
2220 pub fn collaboration_hub(&self) -> Option<&dyn CollaborationHub> {
2221 self.collaboration_hub.as_deref()
2222 }
2223
2224 pub fn set_collaboration_hub(&mut self, hub: Box<dyn CollaborationHub>) {
2225 self.collaboration_hub = Some(hub);
2226 }
2227
2228 pub fn set_custom_context_menu(
2229 &mut self,
2230 f: impl 'static
2231 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
2232 ) {
2233 self.custom_context_menu = Some(Box::new(f))
2234 }
2235
2236 pub fn set_completion_provider(&mut self, provider: Box<dyn CompletionProvider>) {
2237 self.completion_provider = Some(provider);
2238 }
2239
2240 pub fn set_inline_completion_provider<T>(
2241 &mut self,
2242 provider: Option<Model<T>>,
2243 cx: &mut ViewContext<Self>,
2244 ) where
2245 T: InlineCompletionProvider,
2246 {
2247 self.inline_completion_provider =
2248 provider.map(|provider| RegisteredInlineCompletionProvider {
2249 _subscription: cx.observe(&provider, |this, _, cx| {
2250 if this.focus_handle.is_focused(cx) {
2251 this.update_visible_inline_completion(cx);
2252 }
2253 }),
2254 provider: Arc::new(provider),
2255 });
2256 self.refresh_inline_completion(false, false, cx);
2257 }
2258
2259 pub fn placeholder_text(&self, _cx: &WindowContext) -> Option<&str> {
2260 self.placeholder_text.as_deref()
2261 }
2262
2263 pub fn set_placeholder_text(
2264 &mut self,
2265 placeholder_text: impl Into<Arc<str>>,
2266 cx: &mut ViewContext<Self>,
2267 ) {
2268 let placeholder_text = Some(placeholder_text.into());
2269 if self.placeholder_text != placeholder_text {
2270 self.placeholder_text = placeholder_text;
2271 cx.notify();
2272 }
2273 }
2274
2275 pub fn set_cursor_shape(&mut self, cursor_shape: CursorShape, cx: &mut ViewContext<Self>) {
2276 self.cursor_shape = cursor_shape;
2277
2278 // Disrupt blink for immediate user feedback that the cursor shape has changed
2279 self.blink_manager.update(cx, BlinkManager::show_cursor);
2280
2281 cx.notify();
2282 }
2283
2284 pub fn set_current_line_highlight(
2285 &mut self,
2286 current_line_highlight: Option<CurrentLineHighlight>,
2287 ) {
2288 self.current_line_highlight = current_line_highlight;
2289 }
2290
2291 pub fn set_collapse_matches(&mut self, collapse_matches: bool) {
2292 self.collapse_matches = collapse_matches;
2293 }
2294
2295 pub fn range_for_match<T: std::marker::Copy>(&self, range: &Range<T>) -> Range<T> {
2296 if self.collapse_matches {
2297 return range.start..range.start;
2298 }
2299 range.clone()
2300 }
2301
2302 pub fn set_clip_at_line_ends(&mut self, clip: bool, cx: &mut ViewContext<Self>) {
2303 if self.display_map.read(cx).clip_at_line_ends != clip {
2304 self.display_map
2305 .update(cx, |map, _| map.clip_at_line_ends = clip);
2306 }
2307 }
2308
2309 pub fn set_input_enabled(&mut self, input_enabled: bool) {
2310 self.input_enabled = input_enabled;
2311 }
2312
2313 pub fn set_inline_completions_enabled(&mut self, enabled: bool) {
2314 self.enable_inline_completions = enabled;
2315 }
2316
2317 pub fn set_autoindent(&mut self, autoindent: bool) {
2318 if autoindent {
2319 self.autoindent_mode = Some(AutoindentMode::EachLine);
2320 } else {
2321 self.autoindent_mode = None;
2322 }
2323 }
2324
2325 pub fn read_only(&self, cx: &AppContext) -> bool {
2326 self.read_only || self.buffer.read(cx).read_only()
2327 }
2328
2329 pub fn set_read_only(&mut self, read_only: bool) {
2330 self.read_only = read_only;
2331 }
2332
2333 pub fn set_use_autoclose(&mut self, autoclose: bool) {
2334 self.use_autoclose = autoclose;
2335 }
2336
2337 pub fn set_use_auto_surround(&mut self, auto_surround: bool) {
2338 self.use_auto_surround = auto_surround;
2339 }
2340
2341 pub fn set_auto_replace_emoji_shortcode(&mut self, auto_replace: bool) {
2342 self.auto_replace_emoji_shortcode = auto_replace;
2343 }
2344
2345 pub fn toggle_inline_completions(
2346 &mut self,
2347 _: &ToggleInlineCompletions,
2348 cx: &mut ViewContext<Self>,
2349 ) {
2350 if self.show_inline_completions_override.is_some() {
2351 self.set_show_inline_completions(None, cx);
2352 } else {
2353 let cursor = self.selections.newest_anchor().head();
2354 if let Some((buffer, cursor_buffer_position)) =
2355 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
2356 {
2357 let show_inline_completions =
2358 !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx);
2359 self.set_show_inline_completions(Some(show_inline_completions), cx);
2360 }
2361 }
2362 }
2363
2364 pub fn set_show_inline_completions(
2365 &mut self,
2366 show_inline_completions: Option<bool>,
2367 cx: &mut ViewContext<Self>,
2368 ) {
2369 self.show_inline_completions_override = show_inline_completions;
2370 self.refresh_inline_completion(false, true, cx);
2371 }
2372
2373 fn should_show_inline_completions(
2374 &self,
2375 buffer: &Model<Buffer>,
2376 buffer_position: language::Anchor,
2377 cx: &AppContext,
2378 ) -> bool {
2379 if let Some(provider) = self.inline_completion_provider() {
2380 if let Some(show_inline_completions) = self.show_inline_completions_override {
2381 show_inline_completions
2382 } else {
2383 self.mode == EditorMode::Full && provider.is_enabled(buffer, buffer_position, cx)
2384 }
2385 } else {
2386 false
2387 }
2388 }
2389
2390 pub fn set_use_modal_editing(&mut self, to: bool) {
2391 self.use_modal_editing = to;
2392 }
2393
2394 pub fn use_modal_editing(&self) -> bool {
2395 self.use_modal_editing
2396 }
2397
2398 fn selections_did_change(
2399 &mut self,
2400 local: bool,
2401 old_cursor_position: &Anchor,
2402 show_completions: bool,
2403 cx: &mut ViewContext<Self>,
2404 ) {
2405 cx.invalidate_character_coordinates();
2406
2407 // Copy selections to primary selection buffer
2408 #[cfg(target_os = "linux")]
2409 if local {
2410 let selections = self.selections.all::<usize>(cx);
2411 let buffer_handle = self.buffer.read(cx).read(cx);
2412
2413 let mut text = String::new();
2414 for (index, selection) in selections.iter().enumerate() {
2415 let text_for_selection = buffer_handle
2416 .text_for_range(selection.start..selection.end)
2417 .collect::<String>();
2418
2419 text.push_str(&text_for_selection);
2420 if index != selections.len() - 1 {
2421 text.push('\n');
2422 }
2423 }
2424
2425 if !text.is_empty() {
2426 cx.write_to_primary(ClipboardItem::new_string(text));
2427 }
2428 }
2429
2430 if self.focus_handle.is_focused(cx) && self.leader_peer_id.is_none() {
2431 self.buffer.update(cx, |buffer, cx| {
2432 buffer.set_active_selections(
2433 &self.selections.disjoint_anchors(),
2434 self.selections.line_mode,
2435 self.cursor_shape,
2436 cx,
2437 )
2438 });
2439 }
2440 let display_map = self
2441 .display_map
2442 .update(cx, |display_map, cx| display_map.snapshot(cx));
2443 let buffer = &display_map.buffer_snapshot;
2444 self.add_selections_state = None;
2445 self.select_next_state = None;
2446 self.select_prev_state = None;
2447 self.select_larger_syntax_node_stack.clear();
2448 self.invalidate_autoclose_regions(&self.selections.disjoint_anchors(), buffer);
2449 self.snippet_stack
2450 .invalidate(&self.selections.disjoint_anchors(), buffer);
2451 self.take_rename(false, cx);
2452
2453 let new_cursor_position = self.selections.newest_anchor().head();
2454
2455 self.push_to_nav_history(
2456 *old_cursor_position,
2457 Some(new_cursor_position.to_point(buffer)),
2458 cx,
2459 );
2460
2461 if local {
2462 let new_cursor_position = self.selections.newest_anchor().head();
2463 let mut context_menu = self.context_menu.write();
2464 let completion_menu = match context_menu.as_ref() {
2465 Some(ContextMenu::Completions(menu)) => Some(menu),
2466
2467 _ => {
2468 *context_menu = None;
2469 None
2470 }
2471 };
2472
2473 if let Some(completion_menu) = completion_menu {
2474 let cursor_position = new_cursor_position.to_offset(buffer);
2475 let (word_range, kind) =
2476 buffer.surrounding_word(completion_menu.initial_position, true);
2477 if kind == Some(CharKind::Word)
2478 && word_range.to_inclusive().contains(&cursor_position)
2479 {
2480 let mut completion_menu = completion_menu.clone();
2481 drop(context_menu);
2482
2483 let query = Self::completion_query(buffer, cursor_position);
2484 cx.spawn(move |this, mut cx| async move {
2485 completion_menu
2486 .filter(query.as_deref(), cx.background_executor().clone())
2487 .await;
2488
2489 this.update(&mut cx, |this, cx| {
2490 let mut context_menu = this.context_menu.write();
2491 let Some(ContextMenu::Completions(menu)) = context_menu.as_ref() else {
2492 return;
2493 };
2494
2495 if menu.id > completion_menu.id {
2496 return;
2497 }
2498
2499 *context_menu = Some(ContextMenu::Completions(completion_menu));
2500 drop(context_menu);
2501 cx.notify();
2502 })
2503 })
2504 .detach();
2505
2506 if show_completions {
2507 self.show_completions(&ShowCompletions { trigger: None }, cx);
2508 }
2509 } else {
2510 drop(context_menu);
2511 self.hide_context_menu(cx);
2512 }
2513 } else {
2514 drop(context_menu);
2515 }
2516
2517 hide_hover(self, cx);
2518
2519 if old_cursor_position.to_display_point(&display_map).row()
2520 != new_cursor_position.to_display_point(&display_map).row()
2521 {
2522 self.available_code_actions.take();
2523 }
2524 self.refresh_code_actions(cx);
2525 self.refresh_document_highlights(cx);
2526 refresh_matching_bracket_highlights(self, cx);
2527 self.discard_inline_completion(false, cx);
2528 linked_editing_ranges::refresh_linked_ranges(self, cx);
2529 if self.git_blame_inline_enabled {
2530 self.start_inline_blame_timer(cx);
2531 }
2532 }
2533
2534 self.blink_manager.update(cx, BlinkManager::pause_blinking);
2535 cx.emit(EditorEvent::SelectionsChanged { local });
2536
2537 if self.selections.disjoint_anchors().len() == 1 {
2538 cx.emit(SearchEvent::ActiveMatchChanged)
2539 }
2540 cx.notify();
2541 }
2542
2543 pub fn change_selections<R>(
2544 &mut self,
2545 autoscroll: Option<Autoscroll>,
2546 cx: &mut ViewContext<Self>,
2547 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2548 ) -> R {
2549 self.change_selections_inner(autoscroll, true, cx, change)
2550 }
2551
2552 pub fn change_selections_inner<R>(
2553 &mut self,
2554 autoscroll: Option<Autoscroll>,
2555 request_completions: bool,
2556 cx: &mut ViewContext<Self>,
2557 change: impl FnOnce(&mut MutableSelectionsCollection<'_>) -> R,
2558 ) -> R {
2559 let old_cursor_position = self.selections.newest_anchor().head();
2560 self.push_to_selection_history();
2561
2562 let (changed, result) = self.selections.change_with(cx, change);
2563
2564 if changed {
2565 if let Some(autoscroll) = autoscroll {
2566 self.request_autoscroll(autoscroll, cx);
2567 }
2568 self.selections_did_change(true, &old_cursor_position, request_completions, cx);
2569
2570 if self.should_open_signature_help_automatically(
2571 &old_cursor_position,
2572 self.signature_help_state.backspace_pressed(),
2573 cx,
2574 ) {
2575 self.show_signature_help(&ShowSignatureHelp, cx);
2576 }
2577 self.signature_help_state.set_backspace_pressed(false);
2578 }
2579
2580 result
2581 }
2582
2583 pub fn edit<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2584 where
2585 I: IntoIterator<Item = (Range<S>, T)>,
2586 S: ToOffset,
2587 T: Into<Arc<str>>,
2588 {
2589 if self.read_only(cx) {
2590 return;
2591 }
2592
2593 self.buffer
2594 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
2595 }
2596
2597 pub fn edit_with_autoindent<I, S, T>(&mut self, edits: I, cx: &mut ViewContext<Self>)
2598 where
2599 I: IntoIterator<Item = (Range<S>, T)>,
2600 S: ToOffset,
2601 T: Into<Arc<str>>,
2602 {
2603 if self.read_only(cx) {
2604 return;
2605 }
2606
2607 self.buffer.update(cx, |buffer, cx| {
2608 buffer.edit(edits, self.autoindent_mode.clone(), cx)
2609 });
2610 }
2611
2612 pub fn edit_with_block_indent<I, S, T>(
2613 &mut self,
2614 edits: I,
2615 original_indent_columns: Vec<u32>,
2616 cx: &mut ViewContext<Self>,
2617 ) where
2618 I: IntoIterator<Item = (Range<S>, T)>,
2619 S: ToOffset,
2620 T: Into<Arc<str>>,
2621 {
2622 if self.read_only(cx) {
2623 return;
2624 }
2625
2626 self.buffer.update(cx, |buffer, cx| {
2627 buffer.edit(
2628 edits,
2629 Some(AutoindentMode::Block {
2630 original_indent_columns,
2631 }),
2632 cx,
2633 )
2634 });
2635 }
2636
2637 fn select(&mut self, phase: SelectPhase, cx: &mut ViewContext<Self>) {
2638 self.hide_context_menu(cx);
2639
2640 match phase {
2641 SelectPhase::Begin {
2642 position,
2643 add,
2644 click_count,
2645 } => self.begin_selection(position, add, click_count, cx),
2646 SelectPhase::BeginColumnar {
2647 position,
2648 goal_column,
2649 reset,
2650 } => self.begin_columnar_selection(position, goal_column, reset, cx),
2651 SelectPhase::Extend {
2652 position,
2653 click_count,
2654 } => self.extend_selection(position, click_count, cx),
2655 SelectPhase::Update {
2656 position,
2657 goal_column,
2658 scroll_delta,
2659 } => self.update_selection(position, goal_column, scroll_delta, cx),
2660 SelectPhase::End => self.end_selection(cx),
2661 }
2662 }
2663
2664 fn extend_selection(
2665 &mut self,
2666 position: DisplayPoint,
2667 click_count: usize,
2668 cx: &mut ViewContext<Self>,
2669 ) {
2670 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2671 let tail = self.selections.newest::<usize>(cx).tail();
2672 self.begin_selection(position, false, click_count, cx);
2673
2674 let position = position.to_offset(&display_map, Bias::Left);
2675 let tail_anchor = display_map.buffer_snapshot.anchor_before(tail);
2676
2677 let mut pending_selection = self
2678 .selections
2679 .pending_anchor()
2680 .expect("extend_selection not called with pending selection");
2681 if position >= tail {
2682 pending_selection.start = tail_anchor;
2683 } else {
2684 pending_selection.end = tail_anchor;
2685 pending_selection.reversed = true;
2686 }
2687
2688 let mut pending_mode = self.selections.pending_mode().unwrap();
2689 match &mut pending_mode {
2690 SelectMode::Word(range) | SelectMode::Line(range) => *range = tail_anchor..tail_anchor,
2691 _ => {}
2692 }
2693
2694 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
2695 s.set_pending(pending_selection, pending_mode)
2696 });
2697 }
2698
2699 fn begin_selection(
2700 &mut self,
2701 position: DisplayPoint,
2702 add: bool,
2703 click_count: usize,
2704 cx: &mut ViewContext<Self>,
2705 ) {
2706 if !self.focus_handle.is_focused(cx) {
2707 self.last_focused_descendant = None;
2708 cx.focus(&self.focus_handle);
2709 }
2710
2711 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2712 let buffer = &display_map.buffer_snapshot;
2713 let newest_selection = self.selections.newest_anchor().clone();
2714 let position = display_map.clip_point(position, Bias::Left);
2715
2716 let start;
2717 let end;
2718 let mode;
2719 let auto_scroll;
2720 match click_count {
2721 1 => {
2722 start = buffer.anchor_before(position.to_point(&display_map));
2723 end = start;
2724 mode = SelectMode::Character;
2725 auto_scroll = true;
2726 }
2727 2 => {
2728 let range = movement::surrounding_word(&display_map, position);
2729 start = buffer.anchor_before(range.start.to_point(&display_map));
2730 end = buffer.anchor_before(range.end.to_point(&display_map));
2731 mode = SelectMode::Word(start..end);
2732 auto_scroll = true;
2733 }
2734 3 => {
2735 let position = display_map
2736 .clip_point(position, Bias::Left)
2737 .to_point(&display_map);
2738 let line_start = display_map.prev_line_boundary(position).0;
2739 let next_line_start = buffer.clip_point(
2740 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2741 Bias::Left,
2742 );
2743 start = buffer.anchor_before(line_start);
2744 end = buffer.anchor_before(next_line_start);
2745 mode = SelectMode::Line(start..end);
2746 auto_scroll = true;
2747 }
2748 _ => {
2749 start = buffer.anchor_before(0);
2750 end = buffer.anchor_before(buffer.len());
2751 mode = SelectMode::All;
2752 auto_scroll = false;
2753 }
2754 }
2755
2756 let point_to_delete: Option<usize> = {
2757 let selected_points: Vec<Selection<Point>> =
2758 self.selections.disjoint_in_range(start..end, cx);
2759
2760 if !add || click_count > 1 {
2761 None
2762 } else if !selected_points.is_empty() {
2763 Some(selected_points[0].id)
2764 } else {
2765 let clicked_point_already_selected =
2766 self.selections.disjoint.iter().find(|selection| {
2767 selection.start.to_point(buffer) == start.to_point(buffer)
2768 || selection.end.to_point(buffer) == end.to_point(buffer)
2769 });
2770
2771 clicked_point_already_selected.map(|selection| selection.id)
2772 }
2773 };
2774
2775 let selections_count = self.selections.count();
2776
2777 self.change_selections(auto_scroll.then(Autoscroll::newest), cx, |s| {
2778 if let Some(point_to_delete) = point_to_delete {
2779 s.delete(point_to_delete);
2780
2781 if selections_count == 1 {
2782 s.set_pending_anchor_range(start..end, mode);
2783 }
2784 } else {
2785 if !add {
2786 s.clear_disjoint();
2787 } else if click_count > 1 {
2788 s.delete(newest_selection.id)
2789 }
2790
2791 s.set_pending_anchor_range(start..end, mode);
2792 }
2793 });
2794 }
2795
2796 fn begin_columnar_selection(
2797 &mut self,
2798 position: DisplayPoint,
2799 goal_column: u32,
2800 reset: bool,
2801 cx: &mut ViewContext<Self>,
2802 ) {
2803 if !self.focus_handle.is_focused(cx) {
2804 self.last_focused_descendant = None;
2805 cx.focus(&self.focus_handle);
2806 }
2807
2808 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2809
2810 if reset {
2811 let pointer_position = display_map
2812 .buffer_snapshot
2813 .anchor_before(position.to_point(&display_map));
2814
2815 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
2816 s.clear_disjoint();
2817 s.set_pending_anchor_range(
2818 pointer_position..pointer_position,
2819 SelectMode::Character,
2820 );
2821 });
2822 }
2823
2824 let tail = self.selections.newest::<Point>(cx).tail();
2825 self.columnar_selection_tail = Some(display_map.buffer_snapshot.anchor_before(tail));
2826
2827 if !reset {
2828 self.select_columns(
2829 tail.to_display_point(&display_map),
2830 position,
2831 goal_column,
2832 &display_map,
2833 cx,
2834 );
2835 }
2836 }
2837
2838 fn update_selection(
2839 &mut self,
2840 position: DisplayPoint,
2841 goal_column: u32,
2842 scroll_delta: gpui::Point<f32>,
2843 cx: &mut ViewContext<Self>,
2844 ) {
2845 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
2846
2847 if let Some(tail) = self.columnar_selection_tail.as_ref() {
2848 let tail = tail.to_display_point(&display_map);
2849 self.select_columns(tail, position, goal_column, &display_map, cx);
2850 } else if let Some(mut pending) = self.selections.pending_anchor() {
2851 let buffer = self.buffer.read(cx).snapshot(cx);
2852 let head;
2853 let tail;
2854 let mode = self.selections.pending_mode().unwrap();
2855 match &mode {
2856 SelectMode::Character => {
2857 head = position.to_point(&display_map);
2858 tail = pending.tail().to_point(&buffer);
2859 }
2860 SelectMode::Word(original_range) => {
2861 let original_display_range = original_range.start.to_display_point(&display_map)
2862 ..original_range.end.to_display_point(&display_map);
2863 let original_buffer_range = original_display_range.start.to_point(&display_map)
2864 ..original_display_range.end.to_point(&display_map);
2865 if movement::is_inside_word(&display_map, position)
2866 || original_display_range.contains(&position)
2867 {
2868 let word_range = movement::surrounding_word(&display_map, position);
2869 if word_range.start < original_display_range.start {
2870 head = word_range.start.to_point(&display_map);
2871 } else {
2872 head = word_range.end.to_point(&display_map);
2873 }
2874 } else {
2875 head = position.to_point(&display_map);
2876 }
2877
2878 if head <= original_buffer_range.start {
2879 tail = original_buffer_range.end;
2880 } else {
2881 tail = original_buffer_range.start;
2882 }
2883 }
2884 SelectMode::Line(original_range) => {
2885 let original_range = original_range.to_point(&display_map.buffer_snapshot);
2886
2887 let position = display_map
2888 .clip_point(position, Bias::Left)
2889 .to_point(&display_map);
2890 let line_start = display_map.prev_line_boundary(position).0;
2891 let next_line_start = buffer.clip_point(
2892 display_map.next_line_boundary(position).0 + Point::new(1, 0),
2893 Bias::Left,
2894 );
2895
2896 if line_start < original_range.start {
2897 head = line_start
2898 } else {
2899 head = next_line_start
2900 }
2901
2902 if head <= original_range.start {
2903 tail = original_range.end;
2904 } else {
2905 tail = original_range.start;
2906 }
2907 }
2908 SelectMode::All => {
2909 return;
2910 }
2911 };
2912
2913 if head < tail {
2914 pending.start = buffer.anchor_before(head);
2915 pending.end = buffer.anchor_before(tail);
2916 pending.reversed = true;
2917 } else {
2918 pending.start = buffer.anchor_before(tail);
2919 pending.end = buffer.anchor_before(head);
2920 pending.reversed = false;
2921 }
2922
2923 self.change_selections(None, cx, |s| {
2924 s.set_pending(pending, mode);
2925 });
2926 } else {
2927 log::error!("update_selection dispatched with no pending selection");
2928 return;
2929 }
2930
2931 self.apply_scroll_delta(scroll_delta, cx);
2932 cx.notify();
2933 }
2934
2935 fn end_selection(&mut self, cx: &mut ViewContext<Self>) {
2936 self.columnar_selection_tail.take();
2937 if self.selections.pending_anchor().is_some() {
2938 let selections = self.selections.all::<usize>(cx);
2939 self.change_selections(None, cx, |s| {
2940 s.select(selections);
2941 s.clear_pending();
2942 });
2943 }
2944 }
2945
2946 fn select_columns(
2947 &mut self,
2948 tail: DisplayPoint,
2949 head: DisplayPoint,
2950 goal_column: u32,
2951 display_map: &DisplaySnapshot,
2952 cx: &mut ViewContext<Self>,
2953 ) {
2954 let start_row = cmp::min(tail.row(), head.row());
2955 let end_row = cmp::max(tail.row(), head.row());
2956 let start_column = cmp::min(tail.column(), goal_column);
2957 let end_column = cmp::max(tail.column(), goal_column);
2958 let reversed = start_column < tail.column();
2959
2960 let selection_ranges = (start_row.0..=end_row.0)
2961 .map(DisplayRow)
2962 .filter_map(|row| {
2963 if start_column <= display_map.line_len(row) && !display_map.is_block_line(row) {
2964 let start = display_map
2965 .clip_point(DisplayPoint::new(row, start_column), Bias::Left)
2966 .to_point(display_map);
2967 let end = display_map
2968 .clip_point(DisplayPoint::new(row, end_column), Bias::Right)
2969 .to_point(display_map);
2970 if reversed {
2971 Some(end..start)
2972 } else {
2973 Some(start..end)
2974 }
2975 } else {
2976 None
2977 }
2978 })
2979 .collect::<Vec<_>>();
2980
2981 self.change_selections(None, cx, |s| {
2982 s.select_ranges(selection_ranges);
2983 });
2984 cx.notify();
2985 }
2986
2987 pub fn has_pending_nonempty_selection(&self) -> bool {
2988 let pending_nonempty_selection = match self.selections.pending_anchor() {
2989 Some(Selection { start, end, .. }) => start != end,
2990 None => false,
2991 };
2992
2993 pending_nonempty_selection
2994 || (self.columnar_selection_tail.is_some() && self.selections.disjoint.len() > 1)
2995 }
2996
2997 pub fn has_pending_selection(&self) -> bool {
2998 self.selections.pending_anchor().is_some() || self.columnar_selection_tail.is_some()
2999 }
3000
3001 pub fn cancel(&mut self, _: &Cancel, cx: &mut ViewContext<Self>) {
3002 if self.clear_clicked_diff_hunks(cx) {
3003 cx.notify();
3004 return;
3005 }
3006 if self.dismiss_menus_and_popups(true, cx) {
3007 return;
3008 }
3009
3010 if self.mode == EditorMode::Full
3011 && self.change_selections(Some(Autoscroll::fit()), cx, |s| s.try_cancel())
3012 {
3013 return;
3014 }
3015
3016 cx.propagate();
3017 }
3018
3019 pub fn dismiss_menus_and_popups(
3020 &mut self,
3021 should_report_inline_completion_event: bool,
3022 cx: &mut ViewContext<Self>,
3023 ) -> bool {
3024 if self.take_rename(false, cx).is_some() {
3025 return true;
3026 }
3027
3028 if hide_hover(self, cx) {
3029 return true;
3030 }
3031
3032 if self.hide_signature_help(cx, SignatureHelpHiddenBy::Escape) {
3033 return true;
3034 }
3035
3036 if self.hide_context_menu(cx).is_some() {
3037 return true;
3038 }
3039
3040 if self.mouse_context_menu.take().is_some() {
3041 return true;
3042 }
3043
3044 if self.discard_inline_completion(should_report_inline_completion_event, cx) {
3045 return true;
3046 }
3047
3048 if self.snippet_stack.pop().is_some() {
3049 return true;
3050 }
3051
3052 if self.mode == EditorMode::Full && self.active_diagnostics.is_some() {
3053 self.dismiss_diagnostics(cx);
3054 return true;
3055 }
3056
3057 false
3058 }
3059
3060 fn linked_editing_ranges_for(
3061 &self,
3062 selection: Range<text::Anchor>,
3063 cx: &AppContext,
3064 ) -> Option<HashMap<Model<Buffer>, Vec<Range<text::Anchor>>>> {
3065 if self.linked_edit_ranges.is_empty() {
3066 return None;
3067 }
3068 let ((base_range, linked_ranges), buffer_snapshot, buffer) =
3069 selection.end.buffer_id.and_then(|end_buffer_id| {
3070 if selection.start.buffer_id != Some(end_buffer_id) {
3071 return None;
3072 }
3073 let buffer = self.buffer.read(cx).buffer(end_buffer_id)?;
3074 let snapshot = buffer.read(cx).snapshot();
3075 self.linked_edit_ranges
3076 .get(end_buffer_id, selection.start..selection.end, &snapshot)
3077 .map(|ranges| (ranges, snapshot, buffer))
3078 })?;
3079 use text::ToOffset as TO;
3080 // find offset from the start of current range to current cursor position
3081 let start_byte_offset = TO::to_offset(&base_range.start, &buffer_snapshot);
3082
3083 let start_offset = TO::to_offset(&selection.start, &buffer_snapshot);
3084 let start_difference = start_offset - start_byte_offset;
3085 let end_offset = TO::to_offset(&selection.end, &buffer_snapshot);
3086 let end_difference = end_offset - start_byte_offset;
3087 // Current range has associated linked ranges.
3088 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3089 for range in linked_ranges.iter() {
3090 let start_offset = TO::to_offset(&range.start, &buffer_snapshot);
3091 let end_offset = start_offset + end_difference;
3092 let start_offset = start_offset + start_difference;
3093 if start_offset > buffer_snapshot.len() || end_offset > buffer_snapshot.len() {
3094 continue;
3095 }
3096 if self.selections.disjoint_anchor_ranges().iter().any(|s| {
3097 if s.start.buffer_id != selection.start.buffer_id
3098 || s.end.buffer_id != selection.end.buffer_id
3099 {
3100 return false;
3101 }
3102 TO::to_offset(&s.start.text_anchor, &buffer_snapshot) <= end_offset
3103 && TO::to_offset(&s.end.text_anchor, &buffer_snapshot) >= start_offset
3104 }) {
3105 continue;
3106 }
3107 let start = buffer_snapshot.anchor_after(start_offset);
3108 let end = buffer_snapshot.anchor_after(end_offset);
3109 linked_edits
3110 .entry(buffer.clone())
3111 .or_default()
3112 .push(start..end);
3113 }
3114 Some(linked_edits)
3115 }
3116
3117 pub fn handle_input(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3118 let text: Arc<str> = text.into();
3119
3120 if self.read_only(cx) {
3121 return;
3122 }
3123
3124 let selections = self.selections.all_adjusted(cx);
3125 let mut bracket_inserted = false;
3126 let mut edits = Vec::new();
3127 let mut linked_edits = HashMap::<_, Vec<_>>::default();
3128 let mut new_selections = Vec::with_capacity(selections.len());
3129 let mut new_autoclose_regions = Vec::new();
3130 let snapshot = self.buffer.read(cx).read(cx);
3131
3132 for (selection, autoclose_region) in
3133 self.selections_with_autoclose_regions(selections, &snapshot)
3134 {
3135 if let Some(scope) = snapshot.language_scope_at(selection.head()) {
3136 // Determine if the inserted text matches the opening or closing
3137 // bracket of any of this language's bracket pairs.
3138 let mut bracket_pair = None;
3139 let mut is_bracket_pair_start = false;
3140 let mut is_bracket_pair_end = false;
3141 if !text.is_empty() {
3142 // `text` can be empty when a user is using IME (e.g. Chinese Wubi Simplified)
3143 // and they are removing the character that triggered IME popup.
3144 for (pair, enabled) in scope.brackets() {
3145 if !pair.close && !pair.surround {
3146 continue;
3147 }
3148
3149 if enabled && pair.start.ends_with(text.as_ref()) {
3150 bracket_pair = Some(pair.clone());
3151 is_bracket_pair_start = true;
3152 break;
3153 }
3154 if pair.end.as_str() == text.as_ref() {
3155 bracket_pair = Some(pair.clone());
3156 is_bracket_pair_end = true;
3157 break;
3158 }
3159 }
3160 }
3161
3162 if let Some(bracket_pair) = bracket_pair {
3163 let snapshot_settings = snapshot.settings_at(selection.start, cx);
3164 let autoclose = self.use_autoclose && snapshot_settings.use_autoclose;
3165 let auto_surround =
3166 self.use_auto_surround && snapshot_settings.use_auto_surround;
3167 if selection.is_empty() {
3168 if is_bracket_pair_start {
3169 let prefix_len = bracket_pair.start.len() - text.len();
3170
3171 // If the inserted text is a suffix of an opening bracket and the
3172 // selection is preceded by the rest of the opening bracket, then
3173 // insert the closing bracket.
3174 let following_text_allows_autoclose = snapshot
3175 .chars_at(selection.start)
3176 .next()
3177 .map_or(true, |c| scope.should_autoclose_before(c));
3178 let preceding_text_matches_prefix = prefix_len == 0
3179 || (selection.start.column >= (prefix_len as u32)
3180 && snapshot.contains_str_at(
3181 Point::new(
3182 selection.start.row,
3183 selection.start.column - (prefix_len as u32),
3184 ),
3185 &bracket_pair.start[..prefix_len],
3186 ));
3187
3188 if autoclose
3189 && bracket_pair.close
3190 && following_text_allows_autoclose
3191 && preceding_text_matches_prefix
3192 {
3193 let anchor = snapshot.anchor_before(selection.end);
3194 new_selections.push((selection.map(|_| anchor), text.len()));
3195 new_autoclose_regions.push((
3196 anchor,
3197 text.len(),
3198 selection.id,
3199 bracket_pair.clone(),
3200 ));
3201 edits.push((
3202 selection.range(),
3203 format!("{}{}", text, bracket_pair.end).into(),
3204 ));
3205 bracket_inserted = true;
3206 continue;
3207 }
3208 }
3209
3210 if let Some(region) = autoclose_region {
3211 // If the selection is followed by an auto-inserted closing bracket,
3212 // then don't insert that closing bracket again; just move the selection
3213 // past the closing bracket.
3214 let should_skip = selection.end == region.range.end.to_point(&snapshot)
3215 && text.as_ref() == region.pair.end.as_str();
3216 if should_skip {
3217 let anchor = snapshot.anchor_after(selection.end);
3218 new_selections
3219 .push((selection.map(|_| anchor), region.pair.end.len()));
3220 continue;
3221 }
3222 }
3223
3224 let always_treat_brackets_as_autoclosed = snapshot
3225 .settings_at(selection.start, cx)
3226 .always_treat_brackets_as_autoclosed;
3227 if always_treat_brackets_as_autoclosed
3228 && is_bracket_pair_end
3229 && snapshot.contains_str_at(selection.end, text.as_ref())
3230 {
3231 // Otherwise, when `always_treat_brackets_as_autoclosed` is set to `true
3232 // and the inserted text is a closing bracket and the selection is followed
3233 // by the closing bracket then move the selection past the closing bracket.
3234 let anchor = snapshot.anchor_after(selection.end);
3235 new_selections.push((selection.map(|_| anchor), text.len()));
3236 continue;
3237 }
3238 }
3239 // If an opening bracket is 1 character long and is typed while
3240 // text is selected, then surround that text with the bracket pair.
3241 else if auto_surround
3242 && bracket_pair.surround
3243 && is_bracket_pair_start
3244 && bracket_pair.start.chars().count() == 1
3245 {
3246 edits.push((selection.start..selection.start, text.clone()));
3247 edits.push((
3248 selection.end..selection.end,
3249 bracket_pair.end.as_str().into(),
3250 ));
3251 bracket_inserted = true;
3252 new_selections.push((
3253 Selection {
3254 id: selection.id,
3255 start: snapshot.anchor_after(selection.start),
3256 end: snapshot.anchor_before(selection.end),
3257 reversed: selection.reversed,
3258 goal: selection.goal,
3259 },
3260 0,
3261 ));
3262 continue;
3263 }
3264 }
3265 }
3266
3267 if self.auto_replace_emoji_shortcode
3268 && selection.is_empty()
3269 && text.as_ref().ends_with(':')
3270 {
3271 if let Some(possible_emoji_short_code) =
3272 Self::find_possible_emoji_shortcode_at_position(&snapshot, selection.start)
3273 {
3274 if !possible_emoji_short_code.is_empty() {
3275 if let Some(emoji) = emojis::get_by_shortcode(&possible_emoji_short_code) {
3276 let emoji_shortcode_start = Point::new(
3277 selection.start.row,
3278 selection.start.column - possible_emoji_short_code.len() as u32 - 1,
3279 );
3280
3281 // Remove shortcode from buffer
3282 edits.push((
3283 emoji_shortcode_start..selection.start,
3284 "".to_string().into(),
3285 ));
3286 new_selections.push((
3287 Selection {
3288 id: selection.id,
3289 start: snapshot.anchor_after(emoji_shortcode_start),
3290 end: snapshot.anchor_before(selection.start),
3291 reversed: selection.reversed,
3292 goal: selection.goal,
3293 },
3294 0,
3295 ));
3296
3297 // Insert emoji
3298 let selection_start_anchor = snapshot.anchor_after(selection.start);
3299 new_selections.push((selection.map(|_| selection_start_anchor), 0));
3300 edits.push((selection.start..selection.end, emoji.to_string().into()));
3301
3302 continue;
3303 }
3304 }
3305 }
3306 }
3307
3308 // If not handling any auto-close operation, then just replace the selected
3309 // text with the given input and move the selection to the end of the
3310 // newly inserted text.
3311 let anchor = snapshot.anchor_after(selection.end);
3312 if !self.linked_edit_ranges.is_empty() {
3313 let start_anchor = snapshot.anchor_before(selection.start);
3314
3315 let is_word_char = text.chars().next().map_or(true, |char| {
3316 let classifier = snapshot.char_classifier_at(start_anchor.to_offset(&snapshot));
3317 classifier.is_word(char)
3318 });
3319
3320 if is_word_char {
3321 if let Some(ranges) = self
3322 .linked_editing_ranges_for(start_anchor.text_anchor..anchor.text_anchor, cx)
3323 {
3324 for (buffer, edits) in ranges {
3325 linked_edits
3326 .entry(buffer.clone())
3327 .or_default()
3328 .extend(edits.into_iter().map(|range| (range, text.clone())));
3329 }
3330 }
3331 }
3332 }
3333
3334 new_selections.push((selection.map(|_| anchor), 0));
3335 edits.push((selection.start..selection.end, text.clone()));
3336 }
3337
3338 drop(snapshot);
3339
3340 self.transact(cx, |this, cx| {
3341 this.buffer.update(cx, |buffer, cx| {
3342 buffer.edit(edits, this.autoindent_mode.clone(), cx);
3343 });
3344 for (buffer, edits) in linked_edits {
3345 buffer.update(cx, |buffer, cx| {
3346 let snapshot = buffer.snapshot();
3347 let edits = edits
3348 .into_iter()
3349 .map(|(range, text)| {
3350 use text::ToPoint as TP;
3351 let end_point = TP::to_point(&range.end, &snapshot);
3352 let start_point = TP::to_point(&range.start, &snapshot);
3353 (start_point..end_point, text)
3354 })
3355 .sorted_by_key(|(range, _)| range.start)
3356 .collect::<Vec<_>>();
3357 buffer.edit(edits, None, cx);
3358 })
3359 }
3360 let new_anchor_selections = new_selections.iter().map(|e| &e.0);
3361 let new_selection_deltas = new_selections.iter().map(|e| e.1);
3362 let snapshot = this.buffer.read(cx).read(cx);
3363 let new_selections = resolve_multiple::<usize, _>(new_anchor_selections, &snapshot)
3364 .zip(new_selection_deltas)
3365 .map(|(selection, delta)| Selection {
3366 id: selection.id,
3367 start: selection.start + delta,
3368 end: selection.end + delta,
3369 reversed: selection.reversed,
3370 goal: SelectionGoal::None,
3371 })
3372 .collect::<Vec<_>>();
3373
3374 let mut i = 0;
3375 for (position, delta, selection_id, pair) in new_autoclose_regions {
3376 let position = position.to_offset(&snapshot) + delta;
3377 let start = snapshot.anchor_before(position);
3378 let end = snapshot.anchor_after(position);
3379 while let Some(existing_state) = this.autoclose_regions.get(i) {
3380 match existing_state.range.start.cmp(&start, &snapshot) {
3381 Ordering::Less => i += 1,
3382 Ordering::Greater => break,
3383 Ordering::Equal => match end.cmp(&existing_state.range.end, &snapshot) {
3384 Ordering::Less => i += 1,
3385 Ordering::Equal => break,
3386 Ordering::Greater => break,
3387 },
3388 }
3389 }
3390 this.autoclose_regions.insert(
3391 i,
3392 AutocloseRegion {
3393 selection_id,
3394 range: start..end,
3395 pair,
3396 },
3397 );
3398 }
3399
3400 drop(snapshot);
3401 let had_active_inline_completion = this.has_active_inline_completion(cx);
3402 this.change_selections_inner(Some(Autoscroll::fit()), false, cx, |s| {
3403 s.select(new_selections)
3404 });
3405
3406 if !bracket_inserted && EditorSettings::get_global(cx).use_on_type_format {
3407 if let Some(on_type_format_task) =
3408 this.trigger_on_type_formatting(text.to_string(), cx)
3409 {
3410 on_type_format_task.detach_and_log_err(cx);
3411 }
3412 }
3413
3414 let editor_settings = EditorSettings::get_global(cx);
3415 if bracket_inserted
3416 && (editor_settings.auto_signature_help
3417 || editor_settings.show_signature_help_after_edits)
3418 {
3419 this.show_signature_help(&ShowSignatureHelp, cx);
3420 }
3421
3422 let trigger_in_words = !had_active_inline_completion;
3423 this.trigger_completion_on_input(&text, trigger_in_words, cx);
3424 linked_editing_ranges::refresh_linked_ranges(this, cx);
3425 this.refresh_inline_completion(true, false, cx);
3426 });
3427 }
3428
3429 fn find_possible_emoji_shortcode_at_position(
3430 snapshot: &MultiBufferSnapshot,
3431 position: Point,
3432 ) -> Option<String> {
3433 let mut chars = Vec::new();
3434 let mut found_colon = false;
3435 for char in snapshot.reversed_chars_at(position).take(100) {
3436 // Found a possible emoji shortcode in the middle of the buffer
3437 if found_colon {
3438 if char.is_whitespace() {
3439 chars.reverse();
3440 return Some(chars.iter().collect());
3441 }
3442 // If the previous character is not a whitespace, we are in the middle of a word
3443 // and we only want to complete the shortcode if the word is made up of other emojis
3444 let mut containing_word = String::new();
3445 for ch in snapshot
3446 .reversed_chars_at(position)
3447 .skip(chars.len() + 1)
3448 .take(100)
3449 {
3450 if ch.is_whitespace() {
3451 break;
3452 }
3453 containing_word.push(ch);
3454 }
3455 let containing_word = containing_word.chars().rev().collect::<String>();
3456 if util::word_consists_of_emojis(containing_word.as_str()) {
3457 chars.reverse();
3458 return Some(chars.iter().collect());
3459 }
3460 }
3461
3462 if char.is_whitespace() || !char.is_ascii() {
3463 return None;
3464 }
3465 if char == ':' {
3466 found_colon = true;
3467 } else {
3468 chars.push(char);
3469 }
3470 }
3471 // Found a possible emoji shortcode at the beginning of the buffer
3472 chars.reverse();
3473 Some(chars.iter().collect())
3474 }
3475
3476 pub fn newline(&mut self, _: &Newline, cx: &mut ViewContext<Self>) {
3477 self.transact(cx, |this, cx| {
3478 let (edits, selection_fixup_info): (Vec<_>, Vec<_>) = {
3479 let selections = this.selections.all::<usize>(cx);
3480 let multi_buffer = this.buffer.read(cx);
3481 let buffer = multi_buffer.snapshot(cx);
3482 selections
3483 .iter()
3484 .map(|selection| {
3485 let start_point = selection.start.to_point(&buffer);
3486 let mut indent =
3487 buffer.indent_size_for_line(MultiBufferRow(start_point.row));
3488 indent.len = cmp::min(indent.len, start_point.column);
3489 let start = selection.start;
3490 let end = selection.end;
3491 let selection_is_empty = start == end;
3492 let language_scope = buffer.language_scope_at(start);
3493 let (comment_delimiter, insert_extra_newline) = if let Some(language) =
3494 &language_scope
3495 {
3496 let leading_whitespace_len = buffer
3497 .reversed_chars_at(start)
3498 .take_while(|c| c.is_whitespace() && *c != '\n')
3499 .map(|c| c.len_utf8())
3500 .sum::<usize>();
3501
3502 let trailing_whitespace_len = buffer
3503 .chars_at(end)
3504 .take_while(|c| c.is_whitespace() && *c != '\n')
3505 .map(|c| c.len_utf8())
3506 .sum::<usize>();
3507
3508 let insert_extra_newline =
3509 language.brackets().any(|(pair, enabled)| {
3510 let pair_start = pair.start.trim_end();
3511 let pair_end = pair.end.trim_start();
3512
3513 enabled
3514 && pair.newline
3515 && buffer.contains_str_at(
3516 end + trailing_whitespace_len,
3517 pair_end,
3518 )
3519 && buffer.contains_str_at(
3520 (start - leading_whitespace_len)
3521 .saturating_sub(pair_start.len()),
3522 pair_start,
3523 )
3524 });
3525
3526 // Comment extension on newline is allowed only for cursor selections
3527 let comment_delimiter = maybe!({
3528 if !selection_is_empty {
3529 return None;
3530 }
3531
3532 if !multi_buffer.settings_at(0, cx).extend_comment_on_newline {
3533 return None;
3534 }
3535
3536 let delimiters = language.line_comment_prefixes();
3537 let max_len_of_delimiter =
3538 delimiters.iter().map(|delimiter| delimiter.len()).max()?;
3539 let (snapshot, range) =
3540 buffer.buffer_line_for_row(MultiBufferRow(start_point.row))?;
3541
3542 let mut index_of_first_non_whitespace = 0;
3543 let comment_candidate = snapshot
3544 .chars_for_range(range)
3545 .skip_while(|c| {
3546 let should_skip = c.is_whitespace();
3547 if should_skip {
3548 index_of_first_non_whitespace += 1;
3549 }
3550 should_skip
3551 })
3552 .take(max_len_of_delimiter)
3553 .collect::<String>();
3554 let comment_prefix = delimiters.iter().find(|comment_prefix| {
3555 comment_candidate.starts_with(comment_prefix.as_ref())
3556 })?;
3557 let cursor_is_placed_after_comment_marker =
3558 index_of_first_non_whitespace + comment_prefix.len()
3559 <= start_point.column as usize;
3560 if cursor_is_placed_after_comment_marker {
3561 Some(comment_prefix.clone())
3562 } else {
3563 None
3564 }
3565 });
3566 (comment_delimiter, insert_extra_newline)
3567 } else {
3568 (None, false)
3569 };
3570
3571 let capacity_for_delimiter = comment_delimiter
3572 .as_deref()
3573 .map(str::len)
3574 .unwrap_or_default();
3575 let mut new_text =
3576 String::with_capacity(1 + capacity_for_delimiter + indent.len as usize);
3577 new_text.push('\n');
3578 new_text.extend(indent.chars());
3579 if let Some(delimiter) = &comment_delimiter {
3580 new_text.push_str(delimiter);
3581 }
3582 if insert_extra_newline {
3583 new_text = new_text.repeat(2);
3584 }
3585
3586 let anchor = buffer.anchor_after(end);
3587 let new_selection = selection.map(|_| anchor);
3588 (
3589 (start..end, new_text),
3590 (insert_extra_newline, new_selection),
3591 )
3592 })
3593 .unzip()
3594 };
3595
3596 this.edit_with_autoindent(edits, cx);
3597 let buffer = this.buffer.read(cx).snapshot(cx);
3598 let new_selections = selection_fixup_info
3599 .into_iter()
3600 .map(|(extra_newline_inserted, new_selection)| {
3601 let mut cursor = new_selection.end.to_point(&buffer);
3602 if extra_newline_inserted {
3603 cursor.row -= 1;
3604 cursor.column = buffer.line_len(MultiBufferRow(cursor.row));
3605 }
3606 new_selection.map(|_| cursor)
3607 })
3608 .collect();
3609
3610 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
3611 this.refresh_inline_completion(true, false, cx);
3612 });
3613 }
3614
3615 pub fn newline_above(&mut self, _: &NewlineAbove, cx: &mut ViewContext<Self>) {
3616 let buffer = self.buffer.read(cx);
3617 let snapshot = buffer.snapshot(cx);
3618
3619 let mut edits = Vec::new();
3620 let mut rows = Vec::new();
3621
3622 for (rows_inserted, selection) in self.selections.all_adjusted(cx).into_iter().enumerate() {
3623 let cursor = selection.head();
3624 let row = cursor.row;
3625
3626 let start_of_line = snapshot.clip_point(Point::new(row, 0), Bias::Left);
3627
3628 let newline = "\n".to_string();
3629 edits.push((start_of_line..start_of_line, newline));
3630
3631 rows.push(row + rows_inserted as u32);
3632 }
3633
3634 self.transact(cx, |editor, cx| {
3635 editor.edit(edits, cx);
3636
3637 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
3638 let mut index = 0;
3639 s.move_cursors_with(|map, _, _| {
3640 let row = rows[index];
3641 index += 1;
3642
3643 let point = Point::new(row, 0);
3644 let boundary = map.next_line_boundary(point).1;
3645 let clipped = map.clip_point(boundary, Bias::Left);
3646
3647 (clipped, SelectionGoal::None)
3648 });
3649 });
3650
3651 let mut indent_edits = Vec::new();
3652 let multibuffer_snapshot = editor.buffer.read(cx).snapshot(cx);
3653 for row in rows {
3654 let indents = multibuffer_snapshot.suggested_indents(row..row + 1, cx);
3655 for (row, indent) in indents {
3656 if indent.len == 0 {
3657 continue;
3658 }
3659
3660 let text = match indent.kind {
3661 IndentKind::Space => " ".repeat(indent.len as usize),
3662 IndentKind::Tab => "\t".repeat(indent.len as usize),
3663 };
3664 let point = Point::new(row.0, 0);
3665 indent_edits.push((point..point, text));
3666 }
3667 }
3668 editor.edit(indent_edits, cx);
3669 });
3670 }
3671
3672 pub fn newline_below(&mut self, _: &NewlineBelow, cx: &mut ViewContext<Self>) {
3673 let buffer = self.buffer.read(cx);
3674 let snapshot = buffer.snapshot(cx);
3675
3676 let mut edits = Vec::new();
3677 let mut rows = Vec::new();
3678 let mut rows_inserted = 0;
3679
3680 for selection in self.selections.all_adjusted(cx) {
3681 let cursor = selection.head();
3682 let row = cursor.row;
3683
3684 let point = Point::new(row + 1, 0);
3685 let start_of_line = snapshot.clip_point(point, Bias::Left);
3686
3687 let newline = "\n".to_string();
3688 edits.push((start_of_line..start_of_line, newline));
3689
3690 rows_inserted += 1;
3691 rows.push(row + rows_inserted);
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 insert(&mut self, text: &str, cx: &mut ViewContext<Self>) {
3733 let autoindent = text.is_empty().not().then(|| AutoindentMode::Block {
3734 original_indent_columns: Vec::new(),
3735 });
3736 self.insert_with_autoindent_mode(text, autoindent, cx);
3737 }
3738
3739 fn insert_with_autoindent_mode(
3740 &mut self,
3741 text: &str,
3742 autoindent_mode: Option<AutoindentMode>,
3743 cx: &mut ViewContext<Self>,
3744 ) {
3745 if self.read_only(cx) {
3746 return;
3747 }
3748
3749 let text: Arc<str> = text.into();
3750 self.transact(cx, |this, cx| {
3751 let old_selections = this.selections.all_adjusted(cx);
3752 let selection_anchors = this.buffer.update(cx, |buffer, cx| {
3753 let anchors = {
3754 let snapshot = buffer.read(cx);
3755 old_selections
3756 .iter()
3757 .map(|s| {
3758 let anchor = snapshot.anchor_after(s.head());
3759 s.map(|_| anchor)
3760 })
3761 .collect::<Vec<_>>()
3762 };
3763 buffer.edit(
3764 old_selections
3765 .iter()
3766 .map(|s| (s.start..s.end, text.clone())),
3767 autoindent_mode,
3768 cx,
3769 );
3770 anchors
3771 });
3772
3773 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
3774 s.select_anchors(selection_anchors);
3775 })
3776 });
3777 }
3778
3779 fn trigger_completion_on_input(
3780 &mut self,
3781 text: &str,
3782 trigger_in_words: bool,
3783 cx: &mut ViewContext<Self>,
3784 ) {
3785 if self.is_completion_trigger(text, trigger_in_words, cx) {
3786 self.show_completions(
3787 &ShowCompletions {
3788 trigger: Some(text.to_owned()).filter(|x| !x.is_empty()),
3789 },
3790 cx,
3791 );
3792 } else {
3793 self.hide_context_menu(cx);
3794 }
3795 }
3796
3797 fn is_completion_trigger(
3798 &self,
3799 text: &str,
3800 trigger_in_words: bool,
3801 cx: &mut ViewContext<Self>,
3802 ) -> bool {
3803 let position = self.selections.newest_anchor().head();
3804 let multibuffer = self.buffer.read(cx);
3805 let Some(buffer) = position
3806 .buffer_id
3807 .and_then(|buffer_id| multibuffer.buffer(buffer_id).clone())
3808 else {
3809 return false;
3810 };
3811
3812 if let Some(completion_provider) = &self.completion_provider {
3813 completion_provider.is_completion_trigger(
3814 &buffer,
3815 position.text_anchor,
3816 text,
3817 trigger_in_words,
3818 cx,
3819 )
3820 } else {
3821 false
3822 }
3823 }
3824
3825 /// If any empty selections is touching the start of its innermost containing autoclose
3826 /// region, expand it to select the brackets.
3827 fn select_autoclose_pair(&mut self, cx: &mut ViewContext<Self>) {
3828 let selections = self.selections.all::<usize>(cx);
3829 let buffer = self.buffer.read(cx).read(cx);
3830 let new_selections = self
3831 .selections_with_autoclose_regions(selections, &buffer)
3832 .map(|(mut selection, region)| {
3833 if !selection.is_empty() {
3834 return selection;
3835 }
3836
3837 if let Some(region) = region {
3838 let mut range = region.range.to_offset(&buffer);
3839 if selection.start == range.start && range.start >= region.pair.start.len() {
3840 range.start -= region.pair.start.len();
3841 if buffer.contains_str_at(range.start, ®ion.pair.start)
3842 && buffer.contains_str_at(range.end, ®ion.pair.end)
3843 {
3844 range.end += region.pair.end.len();
3845 selection.start = range.start;
3846 selection.end = range.end;
3847
3848 return selection;
3849 }
3850 }
3851 }
3852
3853 let always_treat_brackets_as_autoclosed = buffer
3854 .settings_at(selection.start, cx)
3855 .always_treat_brackets_as_autoclosed;
3856
3857 if !always_treat_brackets_as_autoclosed {
3858 return selection;
3859 }
3860
3861 if let Some(scope) = buffer.language_scope_at(selection.start) {
3862 for (pair, enabled) in scope.brackets() {
3863 if !enabled || !pair.close {
3864 continue;
3865 }
3866
3867 if buffer.contains_str_at(selection.start, &pair.end) {
3868 let pair_start_len = pair.start.len();
3869 if buffer.contains_str_at(selection.start - pair_start_len, &pair.start)
3870 {
3871 selection.start -= pair_start_len;
3872 selection.end += pair.end.len();
3873
3874 return selection;
3875 }
3876 }
3877 }
3878 }
3879
3880 selection
3881 })
3882 .collect();
3883
3884 drop(buffer);
3885 self.change_selections(None, cx, |selections| selections.select(new_selections));
3886 }
3887
3888 /// Iterate the given selections, and for each one, find the smallest surrounding
3889 /// autoclose region. This uses the ordering of the selections and the autoclose
3890 /// regions to avoid repeated comparisons.
3891 fn selections_with_autoclose_regions<'a, D: ToOffset + Clone>(
3892 &'a self,
3893 selections: impl IntoIterator<Item = Selection<D>>,
3894 buffer: &'a MultiBufferSnapshot,
3895 ) -> impl Iterator<Item = (Selection<D>, Option<&'a AutocloseRegion>)> {
3896 let mut i = 0;
3897 let mut regions = self.autoclose_regions.as_slice();
3898 selections.into_iter().map(move |selection| {
3899 let range = selection.start.to_offset(buffer)..selection.end.to_offset(buffer);
3900
3901 let mut enclosing = None;
3902 while let Some(pair_state) = regions.get(i) {
3903 if pair_state.range.end.to_offset(buffer) < range.start {
3904 regions = ®ions[i + 1..];
3905 i = 0;
3906 } else if pair_state.range.start.to_offset(buffer) > range.end {
3907 break;
3908 } else {
3909 if pair_state.selection_id == selection.id {
3910 enclosing = Some(pair_state);
3911 }
3912 i += 1;
3913 }
3914 }
3915
3916 (selection.clone(), enclosing)
3917 })
3918 }
3919
3920 /// Remove any autoclose regions that no longer contain their selection.
3921 fn invalidate_autoclose_regions(
3922 &mut self,
3923 mut selections: &[Selection<Anchor>],
3924 buffer: &MultiBufferSnapshot,
3925 ) {
3926 self.autoclose_regions.retain(|state| {
3927 let mut i = 0;
3928 while let Some(selection) = selections.get(i) {
3929 if selection.end.cmp(&state.range.start, buffer).is_lt() {
3930 selections = &selections[1..];
3931 continue;
3932 }
3933 if selection.start.cmp(&state.range.end, buffer).is_gt() {
3934 break;
3935 }
3936 if selection.id == state.selection_id {
3937 return true;
3938 } else {
3939 i += 1;
3940 }
3941 }
3942 false
3943 });
3944 }
3945
3946 fn completion_query(buffer: &MultiBufferSnapshot, position: impl ToOffset) -> Option<String> {
3947 let offset = position.to_offset(buffer);
3948 let (word_range, kind) = buffer.surrounding_word(offset, true);
3949 if offset > word_range.start && kind == Some(CharKind::Word) {
3950 Some(
3951 buffer
3952 .text_for_range(word_range.start..offset)
3953 .collect::<String>(),
3954 )
3955 } else {
3956 None
3957 }
3958 }
3959
3960 pub fn toggle_inlay_hints(&mut self, _: &ToggleInlayHints, cx: &mut ViewContext<Self>) {
3961 self.refresh_inlay_hints(
3962 InlayHintRefreshReason::Toggle(!self.inlay_hint_cache.enabled),
3963 cx,
3964 );
3965 }
3966
3967 pub fn inlay_hints_enabled(&self) -> bool {
3968 self.inlay_hint_cache.enabled
3969 }
3970
3971 fn refresh_inlay_hints(&mut self, reason: InlayHintRefreshReason, cx: &mut ViewContext<Self>) {
3972 if self.project.is_none() || self.mode != EditorMode::Full {
3973 return;
3974 }
3975
3976 let reason_description = reason.description();
3977 let ignore_debounce = matches!(
3978 reason,
3979 InlayHintRefreshReason::SettingsChange(_)
3980 | InlayHintRefreshReason::Toggle(_)
3981 | InlayHintRefreshReason::ExcerptsRemoved(_)
3982 );
3983 let (invalidate_cache, required_languages) = match reason {
3984 InlayHintRefreshReason::Toggle(enabled) => {
3985 self.inlay_hint_cache.enabled = enabled;
3986 if enabled {
3987 (InvalidationStrategy::RefreshRequested, None)
3988 } else {
3989 self.inlay_hint_cache.clear();
3990 self.splice_inlays(
3991 self.visible_inlay_hints(cx)
3992 .iter()
3993 .map(|inlay| inlay.id)
3994 .collect(),
3995 Vec::new(),
3996 cx,
3997 );
3998 return;
3999 }
4000 }
4001 InlayHintRefreshReason::SettingsChange(new_settings) => {
4002 match self.inlay_hint_cache.update_settings(
4003 &self.buffer,
4004 new_settings,
4005 self.visible_inlay_hints(cx),
4006 cx,
4007 ) {
4008 ControlFlow::Break(Some(InlaySplice {
4009 to_remove,
4010 to_insert,
4011 })) => {
4012 self.splice_inlays(to_remove, to_insert, cx);
4013 return;
4014 }
4015 ControlFlow::Break(None) => return,
4016 ControlFlow::Continue(()) => (InvalidationStrategy::RefreshRequested, None),
4017 }
4018 }
4019 InlayHintRefreshReason::ExcerptsRemoved(excerpts_removed) => {
4020 if let Some(InlaySplice {
4021 to_remove,
4022 to_insert,
4023 }) = self.inlay_hint_cache.remove_excerpts(excerpts_removed)
4024 {
4025 self.splice_inlays(to_remove, to_insert, cx);
4026 }
4027 return;
4028 }
4029 InlayHintRefreshReason::NewLinesShown => (InvalidationStrategy::None, None),
4030 InlayHintRefreshReason::BufferEdited(buffer_languages) => {
4031 (InvalidationStrategy::BufferEdited, Some(buffer_languages))
4032 }
4033 InlayHintRefreshReason::RefreshRequested => {
4034 (InvalidationStrategy::RefreshRequested, None)
4035 }
4036 };
4037
4038 if let Some(InlaySplice {
4039 to_remove,
4040 to_insert,
4041 }) = self.inlay_hint_cache.spawn_hint_refresh(
4042 reason_description,
4043 self.excerpts_for_inlay_hints_query(required_languages.as_ref(), cx),
4044 invalidate_cache,
4045 ignore_debounce,
4046 cx,
4047 ) {
4048 self.splice_inlays(to_remove, to_insert, cx);
4049 }
4050 }
4051
4052 fn visible_inlay_hints(&self, cx: &ViewContext<'_, Editor>) -> Vec<Inlay> {
4053 self.display_map
4054 .read(cx)
4055 .current_inlays()
4056 .filter(move |inlay| matches!(inlay.id, InlayId::Hint(_)))
4057 .cloned()
4058 .collect()
4059 }
4060
4061 pub fn excerpts_for_inlay_hints_query(
4062 &self,
4063 restrict_to_languages: Option<&HashSet<Arc<Language>>>,
4064 cx: &mut ViewContext<Editor>,
4065 ) -> HashMap<ExcerptId, (Model<Buffer>, clock::Global, Range<usize>)> {
4066 let Some(project) = self.project.as_ref() else {
4067 return HashMap::default();
4068 };
4069 let project = project.read(cx);
4070 let multi_buffer = self.buffer().read(cx);
4071 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
4072 let multi_buffer_visible_start = self
4073 .scroll_manager
4074 .anchor()
4075 .anchor
4076 .to_point(&multi_buffer_snapshot);
4077 let multi_buffer_visible_end = multi_buffer_snapshot.clip_point(
4078 multi_buffer_visible_start
4079 + Point::new(self.visible_line_count().unwrap_or(0.).ceil() as u32, 0),
4080 Bias::Left,
4081 );
4082 let multi_buffer_visible_range = multi_buffer_visible_start..multi_buffer_visible_end;
4083 multi_buffer
4084 .range_to_buffer_ranges(multi_buffer_visible_range, cx)
4085 .into_iter()
4086 .filter(|(_, excerpt_visible_range, _)| !excerpt_visible_range.is_empty())
4087 .filter_map(|(buffer_handle, excerpt_visible_range, excerpt_id)| {
4088 let buffer = buffer_handle.read(cx);
4089 let buffer_file = project::File::from_dyn(buffer.file())?;
4090 let buffer_worktree = project.worktree_for_id(buffer_file.worktree_id(cx), cx)?;
4091 let worktree_entry = buffer_worktree
4092 .read(cx)
4093 .entry_for_id(buffer_file.project_entry_id(cx)?)?;
4094 if worktree_entry.is_ignored {
4095 return None;
4096 }
4097
4098 let language = buffer.language()?;
4099 if let Some(restrict_to_languages) = restrict_to_languages {
4100 if !restrict_to_languages.contains(language) {
4101 return None;
4102 }
4103 }
4104 Some((
4105 excerpt_id,
4106 (
4107 buffer_handle,
4108 buffer.version().clone(),
4109 excerpt_visible_range,
4110 ),
4111 ))
4112 })
4113 .collect()
4114 }
4115
4116 pub fn text_layout_details(&self, cx: &WindowContext) -> TextLayoutDetails {
4117 TextLayoutDetails {
4118 text_system: cx.text_system().clone(),
4119 editor_style: self.style.clone().unwrap(),
4120 rem_size: cx.rem_size(),
4121 scroll_anchor: self.scroll_manager.anchor(),
4122 visible_rows: self.visible_line_count(),
4123 vertical_scroll_margin: self.scroll_manager.vertical_scroll_margin,
4124 }
4125 }
4126
4127 fn splice_inlays(
4128 &self,
4129 to_remove: Vec<InlayId>,
4130 to_insert: Vec<Inlay>,
4131 cx: &mut ViewContext<Self>,
4132 ) {
4133 self.display_map.update(cx, |display_map, cx| {
4134 display_map.splice_inlays(to_remove, to_insert, cx);
4135 });
4136 cx.notify();
4137 }
4138
4139 fn trigger_on_type_formatting(
4140 &self,
4141 input: String,
4142 cx: &mut ViewContext<Self>,
4143 ) -> Option<Task<Result<()>>> {
4144 if input.len() != 1 {
4145 return None;
4146 }
4147
4148 let project = self.project.as_ref()?;
4149 let position = self.selections.newest_anchor().head();
4150 let (buffer, buffer_position) = self
4151 .buffer
4152 .read(cx)
4153 .text_anchor_for_position(position, cx)?;
4154
4155 // OnTypeFormatting returns a list of edits, no need to pass them between Zed instances,
4156 // hence we do LSP request & edit on host side only — add formats to host's history.
4157 let push_to_lsp_host_history = true;
4158 // If this is not the host, append its history with new edits.
4159 let push_to_client_history = project.read(cx).is_via_collab();
4160
4161 let on_type_formatting = project.update(cx, |project, cx| {
4162 project.on_type_format(
4163 buffer.clone(),
4164 buffer_position,
4165 input,
4166 push_to_lsp_host_history,
4167 cx,
4168 )
4169 });
4170 Some(cx.spawn(|editor, mut cx| async move {
4171 if let Some(transaction) = on_type_formatting.await? {
4172 if push_to_client_history {
4173 buffer
4174 .update(&mut cx, |buffer, _| {
4175 buffer.push_transaction(transaction, Instant::now());
4176 })
4177 .ok();
4178 }
4179 editor.update(&mut cx, |editor, cx| {
4180 editor.refresh_document_highlights(cx);
4181 })?;
4182 }
4183 Ok(())
4184 }))
4185 }
4186
4187 pub fn show_completions(&mut self, options: &ShowCompletions, cx: &mut ViewContext<Self>) {
4188 if self.pending_rename.is_some() {
4189 return;
4190 }
4191
4192 let Some(provider) = self.completion_provider.as_ref() else {
4193 return;
4194 };
4195
4196 let position = self.selections.newest_anchor().head();
4197 let (buffer, buffer_position) =
4198 if let Some(output) = self.buffer.read(cx).text_anchor_for_position(position, cx) {
4199 output
4200 } else {
4201 return;
4202 };
4203
4204 let query = Self::completion_query(&self.buffer.read(cx).read(cx), position);
4205 let is_followup_invoke = {
4206 let context_menu_state = self.context_menu.read();
4207 matches!(
4208 context_menu_state.deref(),
4209 Some(ContextMenu::Completions(_))
4210 )
4211 };
4212 let trigger_kind = match (&options.trigger, is_followup_invoke) {
4213 (_, true) => CompletionTriggerKind::TRIGGER_FOR_INCOMPLETE_COMPLETIONS,
4214 (Some(trigger), _) if buffer.read(cx).completion_triggers().contains(trigger) => {
4215 CompletionTriggerKind::TRIGGER_CHARACTER
4216 }
4217
4218 _ => CompletionTriggerKind::INVOKED,
4219 };
4220 let completion_context = CompletionContext {
4221 trigger_character: options.trigger.as_ref().and_then(|trigger| {
4222 if trigger_kind == CompletionTriggerKind::TRIGGER_CHARACTER {
4223 Some(String::from(trigger))
4224 } else {
4225 None
4226 }
4227 }),
4228 trigger_kind,
4229 };
4230 let completions = provider.completions(&buffer, buffer_position, completion_context, cx);
4231 let sort_completions = provider.sort_completions();
4232
4233 let id = post_inc(&mut self.next_completion_id);
4234 let task = cx.spawn(|this, mut cx| {
4235 async move {
4236 this.update(&mut cx, |this, _| {
4237 this.completion_tasks.retain(|(task_id, _)| *task_id >= id);
4238 })?;
4239 let completions = completions.await.log_err();
4240 let menu = if let Some(completions) = completions {
4241 let mut menu = CompletionsMenu {
4242 id,
4243 sort_completions,
4244 initial_position: position,
4245 match_candidates: completions
4246 .iter()
4247 .enumerate()
4248 .map(|(id, completion)| {
4249 StringMatchCandidate::new(
4250 id,
4251 completion.label.text[completion.label.filter_range.clone()]
4252 .into(),
4253 )
4254 })
4255 .collect(),
4256 buffer: buffer.clone(),
4257 completions: Arc::new(RwLock::new(completions.into())),
4258 matches: Vec::new().into(),
4259 selected_item: 0,
4260 scroll_handle: UniformListScrollHandle::new(),
4261 selected_completion_documentation_resolve_debounce: Arc::new(Mutex::new(
4262 DebouncedDelay::new(),
4263 )),
4264 };
4265 menu.filter(query.as_deref(), cx.background_executor().clone())
4266 .await;
4267
4268 if menu.matches.is_empty() {
4269 None
4270 } else {
4271 this.update(&mut cx, |editor, cx| {
4272 let completions = menu.completions.clone();
4273 let matches = menu.matches.clone();
4274
4275 let delay_ms = EditorSettings::get_global(cx)
4276 .completion_documentation_secondary_query_debounce;
4277 let delay = Duration::from_millis(delay_ms);
4278 editor
4279 .completion_documentation_pre_resolve_debounce
4280 .fire_new(delay, cx, |editor, cx| {
4281 CompletionsMenu::pre_resolve_completion_documentation(
4282 buffer,
4283 completions,
4284 matches,
4285 editor,
4286 cx,
4287 )
4288 });
4289 })
4290 .ok();
4291 Some(menu)
4292 }
4293 } else {
4294 None
4295 };
4296
4297 this.update(&mut cx, |this, cx| {
4298 let mut context_menu = this.context_menu.write();
4299 match context_menu.as_ref() {
4300 None => {}
4301
4302 Some(ContextMenu::Completions(prev_menu)) => {
4303 if prev_menu.id > id {
4304 return;
4305 }
4306 }
4307
4308 _ => return,
4309 }
4310
4311 if this.focus_handle.is_focused(cx) && menu.is_some() {
4312 let menu = menu.unwrap();
4313 *context_menu = Some(ContextMenu::Completions(menu));
4314 drop(context_menu);
4315 this.discard_inline_completion(false, cx);
4316 cx.notify();
4317 } else if this.completion_tasks.len() <= 1 {
4318 // If there are no more completion tasks and the last menu was
4319 // empty, we should hide it. If it was already hidden, we should
4320 // also show the copilot completion when available.
4321 drop(context_menu);
4322 if this.hide_context_menu(cx).is_none() {
4323 this.update_visible_inline_completion(cx);
4324 }
4325 }
4326 })?;
4327
4328 Ok::<_, anyhow::Error>(())
4329 }
4330 .log_err()
4331 });
4332
4333 self.completion_tasks.push((id, task));
4334 }
4335
4336 pub fn confirm_completion(
4337 &mut self,
4338 action: &ConfirmCompletion,
4339 cx: &mut ViewContext<Self>,
4340 ) -> Option<Task<Result<()>>> {
4341 self.do_completion(action.item_ix, CompletionIntent::Complete, cx)
4342 }
4343
4344 pub fn compose_completion(
4345 &mut self,
4346 action: &ComposeCompletion,
4347 cx: &mut ViewContext<Self>,
4348 ) -> Option<Task<Result<()>>> {
4349 self.do_completion(action.item_ix, CompletionIntent::Compose, cx)
4350 }
4351
4352 fn do_completion(
4353 &mut self,
4354 item_ix: Option<usize>,
4355 intent: CompletionIntent,
4356 cx: &mut ViewContext<Editor>,
4357 ) -> Option<Task<std::result::Result<(), anyhow::Error>>> {
4358 use language::ToOffset as _;
4359
4360 let completions_menu = if let ContextMenu::Completions(menu) = self.hide_context_menu(cx)? {
4361 menu
4362 } else {
4363 return None;
4364 };
4365
4366 let mat = completions_menu
4367 .matches
4368 .get(item_ix.unwrap_or(completions_menu.selected_item))?;
4369 let buffer_handle = completions_menu.buffer;
4370 let completions = completions_menu.completions.read();
4371 let completion = completions.get(mat.candidate_id)?;
4372 cx.stop_propagation();
4373
4374 let snippet;
4375 let text;
4376
4377 if completion.is_snippet() {
4378 snippet = Some(Snippet::parse(&completion.new_text).log_err()?);
4379 text = snippet.as_ref().unwrap().text.clone();
4380 } else {
4381 snippet = None;
4382 text = completion.new_text.clone();
4383 };
4384 let selections = self.selections.all::<usize>(cx);
4385 let buffer = buffer_handle.read(cx);
4386 let old_range = completion.old_range.to_offset(buffer);
4387 let old_text = buffer.text_for_range(old_range.clone()).collect::<String>();
4388
4389 let newest_selection = self.selections.newest_anchor();
4390 if newest_selection.start.buffer_id != Some(buffer_handle.read(cx).remote_id()) {
4391 return None;
4392 }
4393
4394 let lookbehind = newest_selection
4395 .start
4396 .text_anchor
4397 .to_offset(buffer)
4398 .saturating_sub(old_range.start);
4399 let lookahead = old_range
4400 .end
4401 .saturating_sub(newest_selection.end.text_anchor.to_offset(buffer));
4402 let mut common_prefix_len = old_text
4403 .bytes()
4404 .zip(text.bytes())
4405 .take_while(|(a, b)| a == b)
4406 .count();
4407
4408 let snapshot = self.buffer.read(cx).snapshot(cx);
4409 let mut range_to_replace: Option<Range<isize>> = None;
4410 let mut ranges = Vec::new();
4411 let mut linked_edits = HashMap::<_, Vec<_>>::default();
4412 for selection in &selections {
4413 if snapshot.contains_str_at(selection.start.saturating_sub(lookbehind), &old_text) {
4414 let start = selection.start.saturating_sub(lookbehind);
4415 let end = selection.end + lookahead;
4416 if selection.id == newest_selection.id {
4417 range_to_replace = Some(
4418 ((start + common_prefix_len) as isize - selection.start as isize)
4419 ..(end as isize - selection.start as isize),
4420 );
4421 }
4422 ranges.push(start + common_prefix_len..end);
4423 } else {
4424 common_prefix_len = 0;
4425 ranges.clear();
4426 ranges.extend(selections.iter().map(|s| {
4427 if s.id == newest_selection.id {
4428 range_to_replace = Some(
4429 old_range.start.to_offset_utf16(&snapshot).0 as isize
4430 - selection.start as isize
4431 ..old_range.end.to_offset_utf16(&snapshot).0 as isize
4432 - selection.start as isize,
4433 );
4434 old_range.clone()
4435 } else {
4436 s.start..s.end
4437 }
4438 }));
4439 break;
4440 }
4441 if !self.linked_edit_ranges.is_empty() {
4442 let start_anchor = snapshot.anchor_before(selection.head());
4443 let end_anchor = snapshot.anchor_after(selection.tail());
4444 if let Some(ranges) = self
4445 .linked_editing_ranges_for(start_anchor.text_anchor..end_anchor.text_anchor, cx)
4446 {
4447 for (buffer, edits) in ranges {
4448 linked_edits.entry(buffer.clone()).or_default().extend(
4449 edits
4450 .into_iter()
4451 .map(|range| (range, text[common_prefix_len..].to_owned())),
4452 );
4453 }
4454 }
4455 }
4456 }
4457 let text = &text[common_prefix_len..];
4458
4459 cx.emit(EditorEvent::InputHandled {
4460 utf16_range_to_replace: range_to_replace,
4461 text: text.into(),
4462 });
4463
4464 self.transact(cx, |this, cx| {
4465 if let Some(mut snippet) = snippet {
4466 snippet.text = text.to_string();
4467 for tabstop in snippet.tabstops.iter_mut().flatten() {
4468 tabstop.start -= common_prefix_len as isize;
4469 tabstop.end -= common_prefix_len as isize;
4470 }
4471
4472 this.insert_snippet(&ranges, snippet, cx).log_err();
4473 } else {
4474 this.buffer.update(cx, |buffer, cx| {
4475 buffer.edit(
4476 ranges.iter().map(|range| (range.clone(), text)),
4477 this.autoindent_mode.clone(),
4478 cx,
4479 );
4480 });
4481 }
4482 for (buffer, edits) in linked_edits {
4483 buffer.update(cx, |buffer, cx| {
4484 let snapshot = buffer.snapshot();
4485 let edits = edits
4486 .into_iter()
4487 .map(|(range, text)| {
4488 use text::ToPoint as TP;
4489 let end_point = TP::to_point(&range.end, &snapshot);
4490 let start_point = TP::to_point(&range.start, &snapshot);
4491 (start_point..end_point, text)
4492 })
4493 .sorted_by_key(|(range, _)| range.start)
4494 .collect::<Vec<_>>();
4495 buffer.edit(edits, None, cx);
4496 })
4497 }
4498
4499 this.refresh_inline_completion(true, false, cx);
4500 });
4501
4502 let show_new_completions_on_confirm = completion
4503 .confirm
4504 .as_ref()
4505 .map_or(false, |confirm| confirm(intent, cx));
4506 if show_new_completions_on_confirm {
4507 self.show_completions(&ShowCompletions { trigger: None }, cx);
4508 }
4509
4510 let provider = self.completion_provider.as_ref()?;
4511 let apply_edits = provider.apply_additional_edits_for_completion(
4512 buffer_handle,
4513 completion.clone(),
4514 true,
4515 cx,
4516 );
4517
4518 let editor_settings = EditorSettings::get_global(cx);
4519 if editor_settings.show_signature_help_after_edits || editor_settings.auto_signature_help {
4520 // After the code completion is finished, users often want to know what signatures are needed.
4521 // so we should automatically call signature_help
4522 self.show_signature_help(&ShowSignatureHelp, cx);
4523 }
4524
4525 Some(cx.foreground_executor().spawn(async move {
4526 apply_edits.await?;
4527 Ok(())
4528 }))
4529 }
4530
4531 pub fn toggle_code_actions(&mut self, action: &ToggleCodeActions, cx: &mut ViewContext<Self>) {
4532 let mut context_menu = self.context_menu.write();
4533 if let Some(ContextMenu::CodeActions(code_actions)) = context_menu.as_ref() {
4534 if code_actions.deployed_from_indicator == action.deployed_from_indicator {
4535 // Toggle if we're selecting the same one
4536 *context_menu = None;
4537 cx.notify();
4538 return;
4539 } else {
4540 // Otherwise, clear it and start a new one
4541 *context_menu = None;
4542 cx.notify();
4543 }
4544 }
4545 drop(context_menu);
4546 let snapshot = self.snapshot(cx);
4547 let deployed_from_indicator = action.deployed_from_indicator;
4548 let mut task = self.code_actions_task.take();
4549 let action = action.clone();
4550 cx.spawn(|editor, mut cx| async move {
4551 while let Some(prev_task) = task {
4552 prev_task.await;
4553 task = editor.update(&mut cx, |this, _| this.code_actions_task.take())?;
4554 }
4555
4556 let spawned_test_task = editor.update(&mut cx, |editor, cx| {
4557 if editor.focus_handle.is_focused(cx) {
4558 let multibuffer_point = action
4559 .deployed_from_indicator
4560 .map(|row| DisplayPoint::new(row, 0).to_point(&snapshot))
4561 .unwrap_or_else(|| editor.selections.newest::<Point>(cx).head());
4562 let (buffer, buffer_row) = snapshot
4563 .buffer_snapshot
4564 .buffer_line_for_row(MultiBufferRow(multibuffer_point.row))
4565 .and_then(|(buffer_snapshot, range)| {
4566 editor
4567 .buffer
4568 .read(cx)
4569 .buffer(buffer_snapshot.remote_id())
4570 .map(|buffer| (buffer, range.start.row))
4571 })?;
4572 let (_, code_actions) = editor
4573 .available_code_actions
4574 .clone()
4575 .and_then(|(location, code_actions)| {
4576 let snapshot = location.buffer.read(cx).snapshot();
4577 let point_range = location.range.to_point(&snapshot);
4578 let point_range = point_range.start.row..=point_range.end.row;
4579 if point_range.contains(&buffer_row) {
4580 Some((location, code_actions))
4581 } else {
4582 None
4583 }
4584 })
4585 .unzip();
4586 let buffer_id = buffer.read(cx).remote_id();
4587 let tasks = editor
4588 .tasks
4589 .get(&(buffer_id, buffer_row))
4590 .map(|t| Arc::new(t.to_owned()));
4591 if tasks.is_none() && code_actions.is_none() {
4592 return None;
4593 }
4594
4595 editor.completion_tasks.clear();
4596 editor.discard_inline_completion(false, cx);
4597 let task_context =
4598 tasks
4599 .as_ref()
4600 .zip(editor.project.clone())
4601 .map(|(tasks, project)| {
4602 let position = Point::new(buffer_row, tasks.column);
4603 let range_start = buffer.read(cx).anchor_at(position, Bias::Right);
4604 let location = Location {
4605 buffer: buffer.clone(),
4606 range: range_start..range_start,
4607 };
4608 // Fill in the environmental variables from the tree-sitter captures
4609 let mut captured_task_variables = TaskVariables::default();
4610 for (capture_name, value) in tasks.extra_variables.clone() {
4611 captured_task_variables.insert(
4612 task::VariableName::Custom(capture_name.into()),
4613 value.clone(),
4614 );
4615 }
4616 project.update(cx, |project, cx| {
4617 project.task_context_for_location(
4618 captured_task_variables,
4619 location,
4620 cx,
4621 )
4622 })
4623 });
4624
4625 Some(cx.spawn(|editor, mut cx| async move {
4626 let task_context = match task_context {
4627 Some(task_context) => task_context.await,
4628 None => None,
4629 };
4630 let resolved_tasks =
4631 tasks.zip(task_context).map(|(tasks, task_context)| {
4632 Arc::new(ResolvedTasks {
4633 templates: tasks
4634 .templates
4635 .iter()
4636 .filter_map(|(kind, template)| {
4637 template
4638 .resolve_task(&kind.to_id_base(), &task_context)
4639 .map(|task| (kind.clone(), task))
4640 })
4641 .collect(),
4642 position: snapshot.buffer_snapshot.anchor_before(Point::new(
4643 multibuffer_point.row,
4644 tasks.column,
4645 )),
4646 })
4647 });
4648 let spawn_straight_away = resolved_tasks
4649 .as_ref()
4650 .map_or(false, |tasks| tasks.templates.len() == 1)
4651 && code_actions
4652 .as_ref()
4653 .map_or(true, |actions| actions.is_empty());
4654 if let Ok(task) = editor.update(&mut cx, |editor, cx| {
4655 *editor.context_menu.write() =
4656 Some(ContextMenu::CodeActions(CodeActionsMenu {
4657 buffer,
4658 actions: CodeActionContents {
4659 tasks: resolved_tasks,
4660 actions: code_actions,
4661 },
4662 selected_item: Default::default(),
4663 scroll_handle: UniformListScrollHandle::default(),
4664 deployed_from_indicator,
4665 }));
4666 if spawn_straight_away {
4667 if let Some(task) = editor.confirm_code_action(
4668 &ConfirmCodeAction { item_ix: Some(0) },
4669 cx,
4670 ) {
4671 cx.notify();
4672 return task;
4673 }
4674 }
4675 cx.notify();
4676 Task::ready(Ok(()))
4677 }) {
4678 task.await
4679 } else {
4680 Ok(())
4681 }
4682 }))
4683 } else {
4684 Some(Task::ready(Ok(())))
4685 }
4686 })?;
4687 if let Some(task) = spawned_test_task {
4688 task.await?;
4689 }
4690
4691 Ok::<_, anyhow::Error>(())
4692 })
4693 .detach_and_log_err(cx);
4694 }
4695
4696 pub fn confirm_code_action(
4697 &mut self,
4698 action: &ConfirmCodeAction,
4699 cx: &mut ViewContext<Self>,
4700 ) -> Option<Task<Result<()>>> {
4701 let actions_menu = if let ContextMenu::CodeActions(menu) = self.hide_context_menu(cx)? {
4702 menu
4703 } else {
4704 return None;
4705 };
4706 let action_ix = action.item_ix.unwrap_or(actions_menu.selected_item);
4707 let action = actions_menu.actions.get(action_ix)?;
4708 let title = action.label();
4709 let buffer = actions_menu.buffer;
4710 let workspace = self.workspace()?;
4711
4712 match action {
4713 CodeActionsItem::Task(task_source_kind, resolved_task) => {
4714 workspace.update(cx, |workspace, cx| {
4715 workspace::tasks::schedule_resolved_task(
4716 workspace,
4717 task_source_kind,
4718 resolved_task,
4719 false,
4720 cx,
4721 );
4722
4723 Some(Task::ready(Ok(())))
4724 })
4725 }
4726 CodeActionsItem::CodeAction(action) => {
4727 let apply_code_actions = workspace
4728 .read(cx)
4729 .project()
4730 .clone()
4731 .update(cx, |project, cx| {
4732 project.apply_code_action(buffer, action, true, cx)
4733 });
4734 let workspace = workspace.downgrade();
4735 Some(cx.spawn(|editor, cx| async move {
4736 let project_transaction = apply_code_actions.await?;
4737 Self::open_project_transaction(
4738 &editor,
4739 workspace,
4740 project_transaction,
4741 title,
4742 cx,
4743 )
4744 .await
4745 }))
4746 }
4747 }
4748 }
4749
4750 pub async fn open_project_transaction(
4751 this: &WeakView<Editor>,
4752 workspace: WeakView<Workspace>,
4753 transaction: ProjectTransaction,
4754 title: String,
4755 mut cx: AsyncWindowContext,
4756 ) -> Result<()> {
4757 let mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4758 cx.update(|cx| {
4759 entries.sort_unstable_by_key(|(buffer, _)| {
4760 buffer.read(cx).file().map(|f| f.path().clone())
4761 });
4762 })?;
4763
4764 // If the project transaction's edits are all contained within this editor, then
4765 // avoid opening a new editor to display them.
4766
4767 if let Some((buffer, transaction)) = entries.first() {
4768 if entries.len() == 1 {
4769 let excerpt = this.update(&mut cx, |editor, cx| {
4770 editor
4771 .buffer()
4772 .read(cx)
4773 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4774 })?;
4775 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4776 if excerpted_buffer == *buffer {
4777 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4778 let excerpt_range = excerpt_range.to_offset(buffer);
4779 buffer
4780 .edited_ranges_for_transaction::<usize>(transaction)
4781 .all(|range| {
4782 excerpt_range.start <= range.start
4783 && excerpt_range.end >= range.end
4784 })
4785 })?;
4786
4787 if all_edits_within_excerpt {
4788 return Ok(());
4789 }
4790 }
4791 }
4792 }
4793 } else {
4794 return Ok(());
4795 }
4796
4797 let mut ranges_to_highlight = Vec::new();
4798 let excerpt_buffer = cx.new_model(|cx| {
4799 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4800 for (buffer_handle, transaction) in &entries {
4801 let buffer = buffer_handle.read(cx);
4802 ranges_to_highlight.extend(
4803 multibuffer.push_excerpts_with_context_lines(
4804 buffer_handle.clone(),
4805 buffer
4806 .edited_ranges_for_transaction::<usize>(transaction)
4807 .collect(),
4808 DEFAULT_MULTIBUFFER_CONTEXT,
4809 cx,
4810 ),
4811 );
4812 }
4813 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4814 multibuffer
4815 })?;
4816
4817 workspace.update(&mut cx, |workspace, cx| {
4818 let project = workspace.project().clone();
4819 let editor =
4820 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4821 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4822 editor.update(cx, |editor, cx| {
4823 editor.highlight_background::<Self>(
4824 &ranges_to_highlight,
4825 |theme| theme.editor_highlighted_line_background,
4826 cx,
4827 );
4828 });
4829 })?;
4830
4831 Ok(())
4832 }
4833
4834 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4835 let project = self.project.clone()?;
4836 let buffer = self.buffer.read(cx);
4837 let newest_selection = self.selections.newest_anchor().clone();
4838 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4839 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4840 if start_buffer != end_buffer {
4841 return None;
4842 }
4843
4844 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4845 cx.background_executor()
4846 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4847 .await;
4848
4849 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4850 project.code_actions(&start_buffer, start..end, cx)
4851 }) {
4852 code_actions.await
4853 } else {
4854 Vec::new()
4855 };
4856
4857 this.update(&mut cx, |this, cx| {
4858 this.available_code_actions = if actions.is_empty() {
4859 None
4860 } else {
4861 Some((
4862 Location {
4863 buffer: start_buffer,
4864 range: start..end,
4865 },
4866 actions.into(),
4867 ))
4868 };
4869 cx.notify();
4870 })
4871 .log_err();
4872 }));
4873 None
4874 }
4875
4876 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4877 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4878 self.show_git_blame_inline = false;
4879
4880 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4881 cx.background_executor().timer(delay).await;
4882
4883 this.update(&mut cx, |this, cx| {
4884 this.show_git_blame_inline = true;
4885 cx.notify();
4886 })
4887 .log_err();
4888 }));
4889 }
4890 }
4891
4892 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4893 if self.pending_rename.is_some() {
4894 return None;
4895 }
4896
4897 let project = self.project.clone()?;
4898 let buffer = self.buffer.read(cx);
4899 let newest_selection = self.selections.newest_anchor().clone();
4900 let cursor_position = newest_selection.head();
4901 let (cursor_buffer, cursor_buffer_position) =
4902 buffer.text_anchor_for_position(cursor_position, cx)?;
4903 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4904 if cursor_buffer != tail_buffer {
4905 return None;
4906 }
4907
4908 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4909 cx.background_executor()
4910 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4911 .await;
4912
4913 let highlights = if let Some(highlights) = project
4914 .update(&mut cx, |project, cx| {
4915 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4916 })
4917 .log_err()
4918 {
4919 highlights.await.log_err()
4920 } else {
4921 None
4922 };
4923
4924 if let Some(highlights) = highlights {
4925 this.update(&mut cx, |this, cx| {
4926 if this.pending_rename.is_some() {
4927 return;
4928 }
4929
4930 let buffer_id = cursor_position.buffer_id;
4931 let buffer = this.buffer.read(cx);
4932 if !buffer
4933 .text_anchor_for_position(cursor_position, cx)
4934 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4935 {
4936 return;
4937 }
4938
4939 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4940 let mut write_ranges = Vec::new();
4941 let mut read_ranges = Vec::new();
4942 for highlight in highlights {
4943 for (excerpt_id, excerpt_range) in
4944 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4945 {
4946 let start = highlight
4947 .range
4948 .start
4949 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4950 let end = highlight
4951 .range
4952 .end
4953 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4954 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4955 continue;
4956 }
4957
4958 let range = Anchor {
4959 buffer_id,
4960 excerpt_id,
4961 text_anchor: start,
4962 }..Anchor {
4963 buffer_id,
4964 excerpt_id,
4965 text_anchor: end,
4966 };
4967 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4968 write_ranges.push(range);
4969 } else {
4970 read_ranges.push(range);
4971 }
4972 }
4973 }
4974
4975 this.highlight_background::<DocumentHighlightRead>(
4976 &read_ranges,
4977 |theme| theme.editor_document_highlight_read_background,
4978 cx,
4979 );
4980 this.highlight_background::<DocumentHighlightWrite>(
4981 &write_ranges,
4982 |theme| theme.editor_document_highlight_write_background,
4983 cx,
4984 );
4985 cx.notify();
4986 })
4987 .log_err();
4988 }
4989 }));
4990 None
4991 }
4992
4993 pub fn refresh_inline_completion(
4994 &mut self,
4995 debounce: bool,
4996 user_requested: bool,
4997 cx: &mut ViewContext<Self>,
4998 ) -> Option<()> {
4999 let provider = self.inline_completion_provider()?;
5000 let cursor = self.selections.newest_anchor().head();
5001 let (buffer, cursor_buffer_position) =
5002 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5003
5004 if !user_requested
5005 && (!self.enable_inline_completions
5006 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5007 {
5008 self.discard_inline_completion(false, cx);
5009 return None;
5010 }
5011
5012 self.update_visible_inline_completion(cx);
5013 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5014 Some(())
5015 }
5016
5017 fn cycle_inline_completion(
5018 &mut self,
5019 direction: Direction,
5020 cx: &mut ViewContext<Self>,
5021 ) -> Option<()> {
5022 let provider = self.inline_completion_provider()?;
5023 let cursor = self.selections.newest_anchor().head();
5024 let (buffer, cursor_buffer_position) =
5025 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5026 if !self.enable_inline_completions
5027 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5028 {
5029 return None;
5030 }
5031
5032 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5033 self.update_visible_inline_completion(cx);
5034
5035 Some(())
5036 }
5037
5038 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5039 if !self.has_active_inline_completion(cx) {
5040 self.refresh_inline_completion(false, true, cx);
5041 return;
5042 }
5043
5044 self.update_visible_inline_completion(cx);
5045 }
5046
5047 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5048 self.show_cursor_names(cx);
5049 }
5050
5051 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5052 self.show_cursor_names = true;
5053 cx.notify();
5054 cx.spawn(|this, mut cx| async move {
5055 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5056 this.update(&mut cx, |this, cx| {
5057 this.show_cursor_names = false;
5058 cx.notify()
5059 })
5060 .ok()
5061 })
5062 .detach();
5063 }
5064
5065 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5066 if self.has_active_inline_completion(cx) {
5067 self.cycle_inline_completion(Direction::Next, cx);
5068 } else {
5069 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5070 if is_copilot_disabled {
5071 cx.propagate();
5072 }
5073 }
5074 }
5075
5076 pub fn previous_inline_completion(
5077 &mut self,
5078 _: &PreviousInlineCompletion,
5079 cx: &mut ViewContext<Self>,
5080 ) {
5081 if self.has_active_inline_completion(cx) {
5082 self.cycle_inline_completion(Direction::Prev, cx);
5083 } else {
5084 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5085 if is_copilot_disabled {
5086 cx.propagate();
5087 }
5088 }
5089 }
5090
5091 pub fn accept_inline_completion(
5092 &mut self,
5093 _: &AcceptInlineCompletion,
5094 cx: &mut ViewContext<Self>,
5095 ) {
5096 let Some(completion) = self.take_active_inline_completion(cx) else {
5097 return;
5098 };
5099 if let Some(provider) = self.inline_completion_provider() {
5100 provider.accept(cx);
5101 }
5102
5103 cx.emit(EditorEvent::InputHandled {
5104 utf16_range_to_replace: None,
5105 text: completion.text.to_string().into(),
5106 });
5107
5108 if let Some(range) = completion.delete_range {
5109 self.change_selections(None, cx, |s| s.select_ranges([range]))
5110 }
5111 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5112 self.refresh_inline_completion(true, true, cx);
5113 cx.notify();
5114 }
5115
5116 pub fn accept_partial_inline_completion(
5117 &mut self,
5118 _: &AcceptPartialInlineCompletion,
5119 cx: &mut ViewContext<Self>,
5120 ) {
5121 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5122 if let Some(completion) = self.take_active_inline_completion(cx) {
5123 let mut partial_completion = completion
5124 .text
5125 .chars()
5126 .by_ref()
5127 .take_while(|c| c.is_alphabetic())
5128 .collect::<String>();
5129 if partial_completion.is_empty() {
5130 partial_completion = completion
5131 .text
5132 .chars()
5133 .by_ref()
5134 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5135 .collect::<String>();
5136 }
5137
5138 cx.emit(EditorEvent::InputHandled {
5139 utf16_range_to_replace: None,
5140 text: partial_completion.clone().into(),
5141 });
5142
5143 if let Some(range) = completion.delete_range {
5144 self.change_selections(None, cx, |s| s.select_ranges([range]))
5145 }
5146 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5147
5148 self.refresh_inline_completion(true, true, cx);
5149 cx.notify();
5150 }
5151 }
5152 }
5153
5154 fn discard_inline_completion(
5155 &mut self,
5156 should_report_inline_completion_event: bool,
5157 cx: &mut ViewContext<Self>,
5158 ) -> bool {
5159 if let Some(provider) = self.inline_completion_provider() {
5160 provider.discard(should_report_inline_completion_event, cx);
5161 }
5162
5163 self.take_active_inline_completion(cx).is_some()
5164 }
5165
5166 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5167 if let Some(completion) = self.active_inline_completion.as_ref() {
5168 let buffer = self.buffer.read(cx).read(cx);
5169 completion.position.is_valid(&buffer)
5170 } else {
5171 false
5172 }
5173 }
5174
5175 fn take_active_inline_completion(
5176 &mut self,
5177 cx: &mut ViewContext<Self>,
5178 ) -> Option<CompletionState> {
5179 let completion = self.active_inline_completion.take()?;
5180 let render_inlay_ids = completion.render_inlay_ids.clone();
5181 self.display_map.update(cx, |map, cx| {
5182 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5183 });
5184 let buffer = self.buffer.read(cx).read(cx);
5185
5186 if completion.position.is_valid(&buffer) {
5187 Some(completion)
5188 } else {
5189 None
5190 }
5191 }
5192
5193 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5194 let selection = self.selections.newest_anchor();
5195 let cursor = selection.head();
5196
5197 let excerpt_id = cursor.excerpt_id;
5198
5199 if self.context_menu.read().is_none()
5200 && self.completion_tasks.is_empty()
5201 && selection.start == selection.end
5202 {
5203 if let Some(provider) = self.inline_completion_provider() {
5204 if let Some((buffer, cursor_buffer_position)) =
5205 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5206 {
5207 if let Some(proposal) =
5208 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5209 {
5210 let mut to_remove = Vec::new();
5211 if let Some(completion) = self.active_inline_completion.take() {
5212 to_remove.extend(completion.render_inlay_ids.iter());
5213 }
5214
5215 let to_add = proposal
5216 .inlays
5217 .iter()
5218 .filter_map(|inlay| {
5219 let snapshot = self.buffer.read(cx).snapshot(cx);
5220 let id = post_inc(&mut self.next_inlay_id);
5221 match inlay {
5222 InlayProposal::Hint(position, hint) => {
5223 let position =
5224 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5225 Some(Inlay::hint(id, position, hint))
5226 }
5227 InlayProposal::Suggestion(position, text) => {
5228 let position =
5229 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5230 Some(Inlay::suggestion(id, position, text.clone()))
5231 }
5232 }
5233 })
5234 .collect_vec();
5235
5236 self.active_inline_completion = Some(CompletionState {
5237 position: cursor,
5238 text: proposal.text,
5239 delete_range: proposal.delete_range.and_then(|range| {
5240 let snapshot = self.buffer.read(cx).snapshot(cx);
5241 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5242 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5243 Some(start?..end?)
5244 }),
5245 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5246 });
5247
5248 self.display_map
5249 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5250
5251 cx.notify();
5252 return;
5253 }
5254 }
5255 }
5256 }
5257
5258 self.discard_inline_completion(false, cx);
5259 }
5260
5261 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5262 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5263 }
5264
5265 fn render_code_actions_indicator(
5266 &self,
5267 _style: &EditorStyle,
5268 row: DisplayRow,
5269 is_active: bool,
5270 cx: &mut ViewContext<Self>,
5271 ) -> Option<IconButton> {
5272 if self.available_code_actions.is_some() {
5273 Some(
5274 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5275 .shape(ui::IconButtonShape::Square)
5276 .icon_size(IconSize::XSmall)
5277 .icon_color(Color::Muted)
5278 .selected(is_active)
5279 .on_click(cx.listener(move |editor, _e, cx| {
5280 editor.focus(cx);
5281 editor.toggle_code_actions(
5282 &ToggleCodeActions {
5283 deployed_from_indicator: Some(row),
5284 },
5285 cx,
5286 );
5287 })),
5288 )
5289 } else {
5290 None
5291 }
5292 }
5293
5294 fn clear_tasks(&mut self) {
5295 self.tasks.clear()
5296 }
5297
5298 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5299 if self.tasks.insert(key, value).is_some() {
5300 // This case should hopefully be rare, but just in case...
5301 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5302 }
5303 }
5304
5305 fn render_run_indicator(
5306 &self,
5307 _style: &EditorStyle,
5308 is_active: bool,
5309 row: DisplayRow,
5310 cx: &mut ViewContext<Self>,
5311 ) -> IconButton {
5312 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5313 .shape(ui::IconButtonShape::Square)
5314 .icon_size(IconSize::XSmall)
5315 .icon_color(Color::Muted)
5316 .selected(is_active)
5317 .on_click(cx.listener(move |editor, _e, cx| {
5318 editor.focus(cx);
5319 editor.toggle_code_actions(
5320 &ToggleCodeActions {
5321 deployed_from_indicator: Some(row),
5322 },
5323 cx,
5324 );
5325 }))
5326 }
5327
5328 fn close_hunk_diff_button(
5329 &self,
5330 hunk: HoveredHunk,
5331 row: DisplayRow,
5332 cx: &mut ViewContext<Self>,
5333 ) -> IconButton {
5334 IconButton::new(
5335 ("close_hunk_diff_indicator", row.0 as usize),
5336 ui::IconName::Close,
5337 )
5338 .shape(ui::IconButtonShape::Square)
5339 .icon_size(IconSize::XSmall)
5340 .icon_color(Color::Muted)
5341 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5342 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5343 }
5344
5345 pub fn context_menu_visible(&self) -> bool {
5346 self.context_menu
5347 .read()
5348 .as_ref()
5349 .map_or(false, |menu| menu.visible())
5350 }
5351
5352 fn render_context_menu(
5353 &self,
5354 cursor_position: DisplayPoint,
5355 style: &EditorStyle,
5356 max_height: Pixels,
5357 cx: &mut ViewContext<Editor>,
5358 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5359 self.context_menu.read().as_ref().map(|menu| {
5360 menu.render(
5361 cursor_position,
5362 style,
5363 max_height,
5364 self.workspace.as_ref().map(|(w, _)| w.clone()),
5365 cx,
5366 )
5367 })
5368 }
5369
5370 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5371 cx.notify();
5372 self.completion_tasks.clear();
5373 let context_menu = self.context_menu.write().take();
5374 if context_menu.is_some() {
5375 self.update_visible_inline_completion(cx);
5376 }
5377 context_menu
5378 }
5379
5380 pub fn insert_snippet(
5381 &mut self,
5382 insertion_ranges: &[Range<usize>],
5383 snippet: Snippet,
5384 cx: &mut ViewContext<Self>,
5385 ) -> Result<()> {
5386 struct Tabstop<T> {
5387 is_end_tabstop: bool,
5388 ranges: Vec<Range<T>>,
5389 }
5390
5391 let tabstops = self.buffer.update(cx, |buffer, cx| {
5392 let snippet_text: Arc<str> = snippet.text.clone().into();
5393 buffer.edit(
5394 insertion_ranges
5395 .iter()
5396 .cloned()
5397 .map(|range| (range, snippet_text.clone())),
5398 Some(AutoindentMode::EachLine),
5399 cx,
5400 );
5401
5402 let snapshot = &*buffer.read(cx);
5403 let snippet = &snippet;
5404 snippet
5405 .tabstops
5406 .iter()
5407 .map(|tabstop| {
5408 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5409 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5410 });
5411 let mut tabstop_ranges = tabstop
5412 .iter()
5413 .flat_map(|tabstop_range| {
5414 let mut delta = 0_isize;
5415 insertion_ranges.iter().map(move |insertion_range| {
5416 let insertion_start = insertion_range.start as isize + delta;
5417 delta +=
5418 snippet.text.len() as isize - insertion_range.len() as isize;
5419
5420 let start = ((insertion_start + tabstop_range.start) as usize)
5421 .min(snapshot.len());
5422 let end = ((insertion_start + tabstop_range.end) as usize)
5423 .min(snapshot.len());
5424 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5425 })
5426 })
5427 .collect::<Vec<_>>();
5428 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5429
5430 Tabstop {
5431 is_end_tabstop,
5432 ranges: tabstop_ranges,
5433 }
5434 })
5435 .collect::<Vec<_>>()
5436 });
5437 if let Some(tabstop) = tabstops.first() {
5438 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5439 s.select_ranges(tabstop.ranges.iter().cloned());
5440 });
5441
5442 // If we're already at the last tabstop and it's at the end of the snippet,
5443 // we're done, we don't need to keep the state around.
5444 if !tabstop.is_end_tabstop {
5445 let ranges = tabstops
5446 .into_iter()
5447 .map(|tabstop| tabstop.ranges)
5448 .collect::<Vec<_>>();
5449 self.snippet_stack.push(SnippetState {
5450 active_index: 0,
5451 ranges,
5452 });
5453 }
5454
5455 // Check whether the just-entered snippet ends with an auto-closable bracket.
5456 if self.autoclose_regions.is_empty() {
5457 let snapshot = self.buffer.read(cx).snapshot(cx);
5458 for selection in &mut self.selections.all::<Point>(cx) {
5459 let selection_head = selection.head();
5460 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5461 continue;
5462 };
5463
5464 let mut bracket_pair = None;
5465 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5466 let prev_chars = snapshot
5467 .reversed_chars_at(selection_head)
5468 .collect::<String>();
5469 for (pair, enabled) in scope.brackets() {
5470 if enabled
5471 && pair.close
5472 && prev_chars.starts_with(pair.start.as_str())
5473 && next_chars.starts_with(pair.end.as_str())
5474 {
5475 bracket_pair = Some(pair.clone());
5476 break;
5477 }
5478 }
5479 if let Some(pair) = bracket_pair {
5480 let start = snapshot.anchor_after(selection_head);
5481 let end = snapshot.anchor_after(selection_head);
5482 self.autoclose_regions.push(AutocloseRegion {
5483 selection_id: selection.id,
5484 range: start..end,
5485 pair,
5486 });
5487 }
5488 }
5489 }
5490 }
5491 Ok(())
5492 }
5493
5494 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5495 self.move_to_snippet_tabstop(Bias::Right, cx)
5496 }
5497
5498 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5499 self.move_to_snippet_tabstop(Bias::Left, cx)
5500 }
5501
5502 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5503 if let Some(mut snippet) = self.snippet_stack.pop() {
5504 match bias {
5505 Bias::Left => {
5506 if snippet.active_index > 0 {
5507 snippet.active_index -= 1;
5508 } else {
5509 self.snippet_stack.push(snippet);
5510 return false;
5511 }
5512 }
5513 Bias::Right => {
5514 if snippet.active_index + 1 < snippet.ranges.len() {
5515 snippet.active_index += 1;
5516 } else {
5517 self.snippet_stack.push(snippet);
5518 return false;
5519 }
5520 }
5521 }
5522 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5523 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5524 s.select_anchor_ranges(current_ranges.iter().cloned())
5525 });
5526 // If snippet state is not at the last tabstop, push it back on the stack
5527 if snippet.active_index + 1 < snippet.ranges.len() {
5528 self.snippet_stack.push(snippet);
5529 }
5530 return true;
5531 }
5532 }
5533
5534 false
5535 }
5536
5537 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5538 self.transact(cx, |this, cx| {
5539 this.select_all(&SelectAll, cx);
5540 this.insert("", cx);
5541 });
5542 }
5543
5544 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5545 self.transact(cx, |this, cx| {
5546 this.select_autoclose_pair(cx);
5547 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5548 if !this.linked_edit_ranges.is_empty() {
5549 let selections = this.selections.all::<MultiBufferPoint>(cx);
5550 let snapshot = this.buffer.read(cx).snapshot(cx);
5551
5552 for selection in selections.iter() {
5553 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5554 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5555 if selection_start.buffer_id != selection_end.buffer_id {
5556 continue;
5557 }
5558 if let Some(ranges) =
5559 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5560 {
5561 for (buffer, entries) in ranges {
5562 linked_ranges.entry(buffer).or_default().extend(entries);
5563 }
5564 }
5565 }
5566 }
5567
5568 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5569 if !this.selections.line_mode {
5570 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5571 for selection in &mut selections {
5572 if selection.is_empty() {
5573 let old_head = selection.head();
5574 let mut new_head =
5575 movement::left(&display_map, old_head.to_display_point(&display_map))
5576 .to_point(&display_map);
5577 if let Some((buffer, line_buffer_range)) = display_map
5578 .buffer_snapshot
5579 .buffer_line_for_row(MultiBufferRow(old_head.row))
5580 {
5581 let indent_size =
5582 buffer.indent_size_for_line(line_buffer_range.start.row);
5583 let indent_len = match indent_size.kind {
5584 IndentKind::Space => {
5585 buffer.settings_at(line_buffer_range.start, cx).tab_size
5586 }
5587 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5588 };
5589 if old_head.column <= indent_size.len && old_head.column > 0 {
5590 let indent_len = indent_len.get();
5591 new_head = cmp::min(
5592 new_head,
5593 MultiBufferPoint::new(
5594 old_head.row,
5595 ((old_head.column - 1) / indent_len) * indent_len,
5596 ),
5597 );
5598 }
5599 }
5600
5601 selection.set_head(new_head, SelectionGoal::None);
5602 }
5603 }
5604 }
5605
5606 this.signature_help_state.set_backspace_pressed(true);
5607 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5608 this.insert("", cx);
5609 let empty_str: Arc<str> = Arc::from("");
5610 for (buffer, edits) in linked_ranges {
5611 let snapshot = buffer.read(cx).snapshot();
5612 use text::ToPoint as TP;
5613
5614 let edits = edits
5615 .into_iter()
5616 .map(|range| {
5617 let end_point = TP::to_point(&range.end, &snapshot);
5618 let mut start_point = TP::to_point(&range.start, &snapshot);
5619
5620 if end_point == start_point {
5621 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5622 .saturating_sub(1);
5623 start_point = TP::to_point(&offset, &snapshot);
5624 };
5625
5626 (start_point..end_point, empty_str.clone())
5627 })
5628 .sorted_by_key(|(range, _)| range.start)
5629 .collect::<Vec<_>>();
5630 buffer.update(cx, |this, cx| {
5631 this.edit(edits, None, cx);
5632 })
5633 }
5634 this.refresh_inline_completion(true, false, cx);
5635 linked_editing_ranges::refresh_linked_ranges(this, cx);
5636 });
5637 }
5638
5639 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5640 self.transact(cx, |this, cx| {
5641 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5642 let line_mode = s.line_mode;
5643 s.move_with(|map, selection| {
5644 if selection.is_empty() && !line_mode {
5645 let cursor = movement::right(map, selection.head());
5646 selection.end = cursor;
5647 selection.reversed = true;
5648 selection.goal = SelectionGoal::None;
5649 }
5650 })
5651 });
5652 this.insert("", cx);
5653 this.refresh_inline_completion(true, false, cx);
5654 });
5655 }
5656
5657 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5658 if self.move_to_prev_snippet_tabstop(cx) {
5659 return;
5660 }
5661
5662 self.outdent(&Outdent, cx);
5663 }
5664
5665 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5666 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5667 return;
5668 }
5669
5670 let mut selections = self.selections.all_adjusted(cx);
5671 let buffer = self.buffer.read(cx);
5672 let snapshot = buffer.snapshot(cx);
5673 let rows_iter = selections.iter().map(|s| s.head().row);
5674 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5675
5676 let mut edits = Vec::new();
5677 let mut prev_edited_row = 0;
5678 let mut row_delta = 0;
5679 for selection in &mut selections {
5680 if selection.start.row != prev_edited_row {
5681 row_delta = 0;
5682 }
5683 prev_edited_row = selection.end.row;
5684
5685 // If the selection is non-empty, then increase the indentation of the selected lines.
5686 if !selection.is_empty() {
5687 row_delta =
5688 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5689 continue;
5690 }
5691
5692 // If the selection is empty and the cursor is in the leading whitespace before the
5693 // suggested indentation, then auto-indent the line.
5694 let cursor = selection.head();
5695 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5696 if let Some(suggested_indent) =
5697 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5698 {
5699 if cursor.column < suggested_indent.len
5700 && cursor.column <= current_indent.len
5701 && current_indent.len <= suggested_indent.len
5702 {
5703 selection.start = Point::new(cursor.row, suggested_indent.len);
5704 selection.end = selection.start;
5705 if row_delta == 0 {
5706 edits.extend(Buffer::edit_for_indent_size_adjustment(
5707 cursor.row,
5708 current_indent,
5709 suggested_indent,
5710 ));
5711 row_delta = suggested_indent.len - current_indent.len;
5712 }
5713 continue;
5714 }
5715 }
5716
5717 // Otherwise, insert a hard or soft tab.
5718 let settings = buffer.settings_at(cursor, cx);
5719 let tab_size = if settings.hard_tabs {
5720 IndentSize::tab()
5721 } else {
5722 let tab_size = settings.tab_size.get();
5723 let char_column = snapshot
5724 .text_for_range(Point::new(cursor.row, 0)..cursor)
5725 .flat_map(str::chars)
5726 .count()
5727 + row_delta as usize;
5728 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5729 IndentSize::spaces(chars_to_next_tab_stop)
5730 };
5731 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5732 selection.end = selection.start;
5733 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5734 row_delta += tab_size.len;
5735 }
5736
5737 self.transact(cx, |this, cx| {
5738 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5739 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5740 this.refresh_inline_completion(true, false, cx);
5741 });
5742 }
5743
5744 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5745 if self.read_only(cx) {
5746 return;
5747 }
5748 let mut selections = self.selections.all::<Point>(cx);
5749 let mut prev_edited_row = 0;
5750 let mut row_delta = 0;
5751 let mut edits = Vec::new();
5752 let buffer = self.buffer.read(cx);
5753 let snapshot = buffer.snapshot(cx);
5754 for selection in &mut selections {
5755 if selection.start.row != prev_edited_row {
5756 row_delta = 0;
5757 }
5758 prev_edited_row = selection.end.row;
5759
5760 row_delta =
5761 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5762 }
5763
5764 self.transact(cx, |this, cx| {
5765 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5766 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5767 });
5768 }
5769
5770 fn indent_selection(
5771 buffer: &MultiBuffer,
5772 snapshot: &MultiBufferSnapshot,
5773 selection: &mut Selection<Point>,
5774 edits: &mut Vec<(Range<Point>, String)>,
5775 delta_for_start_row: u32,
5776 cx: &AppContext,
5777 ) -> u32 {
5778 let settings = buffer.settings_at(selection.start, cx);
5779 let tab_size = settings.tab_size.get();
5780 let indent_kind = if settings.hard_tabs {
5781 IndentKind::Tab
5782 } else {
5783 IndentKind::Space
5784 };
5785 let mut start_row = selection.start.row;
5786 let mut end_row = selection.end.row + 1;
5787
5788 // If a selection ends at the beginning of a line, don't indent
5789 // that last line.
5790 if selection.end.column == 0 && selection.end.row > selection.start.row {
5791 end_row -= 1;
5792 }
5793
5794 // Avoid re-indenting a row that has already been indented by a
5795 // previous selection, but still update this selection's column
5796 // to reflect that indentation.
5797 if delta_for_start_row > 0 {
5798 start_row += 1;
5799 selection.start.column += delta_for_start_row;
5800 if selection.end.row == selection.start.row {
5801 selection.end.column += delta_for_start_row;
5802 }
5803 }
5804
5805 let mut delta_for_end_row = 0;
5806 let has_multiple_rows = start_row + 1 != end_row;
5807 for row in start_row..end_row {
5808 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5809 let indent_delta = match (current_indent.kind, indent_kind) {
5810 (IndentKind::Space, IndentKind::Space) => {
5811 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5812 IndentSize::spaces(columns_to_next_tab_stop)
5813 }
5814 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5815 (_, IndentKind::Tab) => IndentSize::tab(),
5816 };
5817
5818 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5819 0
5820 } else {
5821 selection.start.column
5822 };
5823 let row_start = Point::new(row, start);
5824 edits.push((
5825 row_start..row_start,
5826 indent_delta.chars().collect::<String>(),
5827 ));
5828
5829 // Update this selection's endpoints to reflect the indentation.
5830 if row == selection.start.row {
5831 selection.start.column += indent_delta.len;
5832 }
5833 if row == selection.end.row {
5834 selection.end.column += indent_delta.len;
5835 delta_for_end_row = indent_delta.len;
5836 }
5837 }
5838
5839 if selection.start.row == selection.end.row {
5840 delta_for_start_row + delta_for_end_row
5841 } else {
5842 delta_for_end_row
5843 }
5844 }
5845
5846 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5847 if self.read_only(cx) {
5848 return;
5849 }
5850 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5851 let selections = self.selections.all::<Point>(cx);
5852 let mut deletion_ranges = Vec::new();
5853 let mut last_outdent = None;
5854 {
5855 let buffer = self.buffer.read(cx);
5856 let snapshot = buffer.snapshot(cx);
5857 for selection in &selections {
5858 let settings = buffer.settings_at(selection.start, cx);
5859 let tab_size = settings.tab_size.get();
5860 let mut rows = selection.spanned_rows(false, &display_map);
5861
5862 // Avoid re-outdenting a row that has already been outdented by a
5863 // previous selection.
5864 if let Some(last_row) = last_outdent {
5865 if last_row == rows.start {
5866 rows.start = rows.start.next_row();
5867 }
5868 }
5869 let has_multiple_rows = rows.len() > 1;
5870 for row in rows.iter_rows() {
5871 let indent_size = snapshot.indent_size_for_line(row);
5872 if indent_size.len > 0 {
5873 let deletion_len = match indent_size.kind {
5874 IndentKind::Space => {
5875 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5876 if columns_to_prev_tab_stop == 0 {
5877 tab_size
5878 } else {
5879 columns_to_prev_tab_stop
5880 }
5881 }
5882 IndentKind::Tab => 1,
5883 };
5884 let start = if has_multiple_rows
5885 || deletion_len > selection.start.column
5886 || indent_size.len < selection.start.column
5887 {
5888 0
5889 } else {
5890 selection.start.column - deletion_len
5891 };
5892 deletion_ranges.push(
5893 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5894 );
5895 last_outdent = Some(row);
5896 }
5897 }
5898 }
5899 }
5900
5901 self.transact(cx, |this, cx| {
5902 this.buffer.update(cx, |buffer, cx| {
5903 let empty_str: Arc<str> = Arc::default();
5904 buffer.edit(
5905 deletion_ranges
5906 .into_iter()
5907 .map(|range| (range, empty_str.clone())),
5908 None,
5909 cx,
5910 );
5911 });
5912 let selections = this.selections.all::<usize>(cx);
5913 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5914 });
5915 }
5916
5917 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5918 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5919 let selections = self.selections.all::<Point>(cx);
5920
5921 let mut new_cursors = Vec::new();
5922 let mut edit_ranges = Vec::new();
5923 let mut selections = selections.iter().peekable();
5924 while let Some(selection) = selections.next() {
5925 let mut rows = selection.spanned_rows(false, &display_map);
5926 let goal_display_column = selection.head().to_display_point(&display_map).column();
5927
5928 // Accumulate contiguous regions of rows that we want to delete.
5929 while let Some(next_selection) = selections.peek() {
5930 let next_rows = next_selection.spanned_rows(false, &display_map);
5931 if next_rows.start <= rows.end {
5932 rows.end = next_rows.end;
5933 selections.next().unwrap();
5934 } else {
5935 break;
5936 }
5937 }
5938
5939 let buffer = &display_map.buffer_snapshot;
5940 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5941 let edit_end;
5942 let cursor_buffer_row;
5943 if buffer.max_point().row >= rows.end.0 {
5944 // If there's a line after the range, delete the \n from the end of the row range
5945 // and position the cursor on the next line.
5946 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5947 cursor_buffer_row = rows.end;
5948 } else {
5949 // If there isn't a line after the range, delete the \n from the line before the
5950 // start of the row range and position the cursor there.
5951 edit_start = edit_start.saturating_sub(1);
5952 edit_end = buffer.len();
5953 cursor_buffer_row = rows.start.previous_row();
5954 }
5955
5956 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5957 *cursor.column_mut() =
5958 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5959
5960 new_cursors.push((
5961 selection.id,
5962 buffer.anchor_after(cursor.to_point(&display_map)),
5963 ));
5964 edit_ranges.push(edit_start..edit_end);
5965 }
5966
5967 self.transact(cx, |this, cx| {
5968 let buffer = this.buffer.update(cx, |buffer, cx| {
5969 let empty_str: Arc<str> = Arc::default();
5970 buffer.edit(
5971 edit_ranges
5972 .into_iter()
5973 .map(|range| (range, empty_str.clone())),
5974 None,
5975 cx,
5976 );
5977 buffer.snapshot(cx)
5978 });
5979 let new_selections = new_cursors
5980 .into_iter()
5981 .map(|(id, cursor)| {
5982 let cursor = cursor.to_point(&buffer);
5983 Selection {
5984 id,
5985 start: cursor,
5986 end: cursor,
5987 reversed: false,
5988 goal: SelectionGoal::None,
5989 }
5990 })
5991 .collect();
5992
5993 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5994 s.select(new_selections);
5995 });
5996 });
5997 }
5998
5999 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6000 if self.read_only(cx) {
6001 return;
6002 }
6003 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6004 for selection in self.selections.all::<Point>(cx) {
6005 let start = MultiBufferRow(selection.start.row);
6006 let end = if selection.start.row == selection.end.row {
6007 MultiBufferRow(selection.start.row + 1)
6008 } else {
6009 MultiBufferRow(selection.end.row)
6010 };
6011
6012 if let Some(last_row_range) = row_ranges.last_mut() {
6013 if start <= last_row_range.end {
6014 last_row_range.end = end;
6015 continue;
6016 }
6017 }
6018 row_ranges.push(start..end);
6019 }
6020
6021 let snapshot = self.buffer.read(cx).snapshot(cx);
6022 let mut cursor_positions = Vec::new();
6023 for row_range in &row_ranges {
6024 let anchor = snapshot.anchor_before(Point::new(
6025 row_range.end.previous_row().0,
6026 snapshot.line_len(row_range.end.previous_row()),
6027 ));
6028 cursor_positions.push(anchor..anchor);
6029 }
6030
6031 self.transact(cx, |this, cx| {
6032 for row_range in row_ranges.into_iter().rev() {
6033 for row in row_range.iter_rows().rev() {
6034 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6035 let next_line_row = row.next_row();
6036 let indent = snapshot.indent_size_for_line(next_line_row);
6037 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6038
6039 let replace = if snapshot.line_len(next_line_row) > indent.len {
6040 " "
6041 } else {
6042 ""
6043 };
6044
6045 this.buffer.update(cx, |buffer, cx| {
6046 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6047 });
6048 }
6049 }
6050
6051 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6052 s.select_anchor_ranges(cursor_positions)
6053 });
6054 });
6055 }
6056
6057 pub fn sort_lines_case_sensitive(
6058 &mut self,
6059 _: &SortLinesCaseSensitive,
6060 cx: &mut ViewContext<Self>,
6061 ) {
6062 self.manipulate_lines(cx, |lines| lines.sort())
6063 }
6064
6065 pub fn sort_lines_case_insensitive(
6066 &mut self,
6067 _: &SortLinesCaseInsensitive,
6068 cx: &mut ViewContext<Self>,
6069 ) {
6070 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6071 }
6072
6073 pub fn unique_lines_case_insensitive(
6074 &mut self,
6075 _: &UniqueLinesCaseInsensitive,
6076 cx: &mut ViewContext<Self>,
6077 ) {
6078 self.manipulate_lines(cx, |lines| {
6079 let mut seen = HashSet::default();
6080 lines.retain(|line| seen.insert(line.to_lowercase()));
6081 })
6082 }
6083
6084 pub fn unique_lines_case_sensitive(
6085 &mut self,
6086 _: &UniqueLinesCaseSensitive,
6087 cx: &mut ViewContext<Self>,
6088 ) {
6089 self.manipulate_lines(cx, |lines| {
6090 let mut seen = HashSet::default();
6091 lines.retain(|line| seen.insert(*line));
6092 })
6093 }
6094
6095 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6096 let mut revert_changes = HashMap::default();
6097 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6098 for hunk in hunks_for_rows(
6099 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6100 &multi_buffer_snapshot,
6101 ) {
6102 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6103 }
6104 if !revert_changes.is_empty() {
6105 self.transact(cx, |editor, cx| {
6106 editor.revert(revert_changes, cx);
6107 });
6108 }
6109 }
6110
6111 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6112 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6113 if !revert_changes.is_empty() {
6114 self.transact(cx, |editor, cx| {
6115 editor.revert(revert_changes, cx);
6116 });
6117 }
6118 }
6119
6120 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6121 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6122 let project_path = buffer.read(cx).project_path(cx)?;
6123 let project = self.project.as_ref()?.read(cx);
6124 let entry = project.entry_for_path(&project_path, cx)?;
6125 let abs_path = project.absolute_path(&project_path, cx)?;
6126 let parent = if entry.is_symlink {
6127 abs_path.canonicalize().ok()?
6128 } else {
6129 abs_path
6130 }
6131 .parent()?
6132 .to_path_buf();
6133 Some(parent)
6134 }) {
6135 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6136 }
6137 }
6138
6139 fn gather_revert_changes(
6140 &mut self,
6141 selections: &[Selection<Anchor>],
6142 cx: &mut ViewContext<'_, Editor>,
6143 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6144 let mut revert_changes = HashMap::default();
6145 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6146 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6147 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6148 }
6149 revert_changes
6150 }
6151
6152 pub fn prepare_revert_change(
6153 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6154 multi_buffer: &Model<MultiBuffer>,
6155 hunk: &DiffHunk<MultiBufferRow>,
6156 cx: &AppContext,
6157 ) -> Option<()> {
6158 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6159 let buffer = buffer.read(cx);
6160 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6161 let buffer_snapshot = buffer.snapshot();
6162 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6163 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6164 probe
6165 .0
6166 .start
6167 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6168 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6169 }) {
6170 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6171 Some(())
6172 } else {
6173 None
6174 }
6175 }
6176
6177 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6178 self.manipulate_lines(cx, |lines| lines.reverse())
6179 }
6180
6181 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6182 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6183 }
6184
6185 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6186 where
6187 Fn: FnMut(&mut Vec<&str>),
6188 {
6189 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6190 let buffer = self.buffer.read(cx).snapshot(cx);
6191
6192 let mut edits = Vec::new();
6193
6194 let selections = self.selections.all::<Point>(cx);
6195 let mut selections = selections.iter().peekable();
6196 let mut contiguous_row_selections = Vec::new();
6197 let mut new_selections = Vec::new();
6198 let mut added_lines = 0;
6199 let mut removed_lines = 0;
6200
6201 while let Some(selection) = selections.next() {
6202 let (start_row, end_row) = consume_contiguous_rows(
6203 &mut contiguous_row_selections,
6204 selection,
6205 &display_map,
6206 &mut selections,
6207 );
6208
6209 let start_point = Point::new(start_row.0, 0);
6210 let end_point = Point::new(
6211 end_row.previous_row().0,
6212 buffer.line_len(end_row.previous_row()),
6213 );
6214 let text = buffer
6215 .text_for_range(start_point..end_point)
6216 .collect::<String>();
6217
6218 let mut lines = text.split('\n').collect_vec();
6219
6220 let lines_before = lines.len();
6221 callback(&mut lines);
6222 let lines_after = lines.len();
6223
6224 edits.push((start_point..end_point, lines.join("\n")));
6225
6226 // Selections must change based on added and removed line count
6227 let start_row =
6228 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6229 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6230 new_selections.push(Selection {
6231 id: selection.id,
6232 start: start_row,
6233 end: end_row,
6234 goal: SelectionGoal::None,
6235 reversed: selection.reversed,
6236 });
6237
6238 if lines_after > lines_before {
6239 added_lines += lines_after - lines_before;
6240 } else if lines_before > lines_after {
6241 removed_lines += lines_before - lines_after;
6242 }
6243 }
6244
6245 self.transact(cx, |this, cx| {
6246 let buffer = this.buffer.update(cx, |buffer, cx| {
6247 buffer.edit(edits, None, cx);
6248 buffer.snapshot(cx)
6249 });
6250
6251 // Recalculate offsets on newly edited buffer
6252 let new_selections = new_selections
6253 .iter()
6254 .map(|s| {
6255 let start_point = Point::new(s.start.0, 0);
6256 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6257 Selection {
6258 id: s.id,
6259 start: buffer.point_to_offset(start_point),
6260 end: buffer.point_to_offset(end_point),
6261 goal: s.goal,
6262 reversed: s.reversed,
6263 }
6264 })
6265 .collect();
6266
6267 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6268 s.select(new_selections);
6269 });
6270
6271 this.request_autoscroll(Autoscroll::fit(), cx);
6272 });
6273 }
6274
6275 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6276 self.manipulate_text(cx, |text| text.to_uppercase())
6277 }
6278
6279 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6280 self.manipulate_text(cx, |text| text.to_lowercase())
6281 }
6282
6283 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6284 self.manipulate_text(cx, |text| {
6285 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6286 // https://github.com/rutrum/convert-case/issues/16
6287 text.split('\n')
6288 .map(|line| line.to_case(Case::Title))
6289 .join("\n")
6290 })
6291 }
6292
6293 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6294 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6295 }
6296
6297 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6298 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6299 }
6300
6301 pub fn convert_to_upper_camel_case(
6302 &mut self,
6303 _: &ConvertToUpperCamelCase,
6304 cx: &mut ViewContext<Self>,
6305 ) {
6306 self.manipulate_text(cx, |text| {
6307 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6308 // https://github.com/rutrum/convert-case/issues/16
6309 text.split('\n')
6310 .map(|line| line.to_case(Case::UpperCamel))
6311 .join("\n")
6312 })
6313 }
6314
6315 pub fn convert_to_lower_camel_case(
6316 &mut self,
6317 _: &ConvertToLowerCamelCase,
6318 cx: &mut ViewContext<Self>,
6319 ) {
6320 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6321 }
6322
6323 pub fn convert_to_opposite_case(
6324 &mut self,
6325 _: &ConvertToOppositeCase,
6326 cx: &mut ViewContext<Self>,
6327 ) {
6328 self.manipulate_text(cx, |text| {
6329 text.chars()
6330 .fold(String::with_capacity(text.len()), |mut t, c| {
6331 if c.is_uppercase() {
6332 t.extend(c.to_lowercase());
6333 } else {
6334 t.extend(c.to_uppercase());
6335 }
6336 t
6337 })
6338 })
6339 }
6340
6341 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6342 where
6343 Fn: FnMut(&str) -> String,
6344 {
6345 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6346 let buffer = self.buffer.read(cx).snapshot(cx);
6347
6348 let mut new_selections = Vec::new();
6349 let mut edits = Vec::new();
6350 let mut selection_adjustment = 0i32;
6351
6352 for selection in self.selections.all::<usize>(cx) {
6353 let selection_is_empty = selection.is_empty();
6354
6355 let (start, end) = if selection_is_empty {
6356 let word_range = movement::surrounding_word(
6357 &display_map,
6358 selection.start.to_display_point(&display_map),
6359 );
6360 let start = word_range.start.to_offset(&display_map, Bias::Left);
6361 let end = word_range.end.to_offset(&display_map, Bias::Left);
6362 (start, end)
6363 } else {
6364 (selection.start, selection.end)
6365 };
6366
6367 let text = buffer.text_for_range(start..end).collect::<String>();
6368 let old_length = text.len() as i32;
6369 let text = callback(&text);
6370
6371 new_selections.push(Selection {
6372 start: (start as i32 - selection_adjustment) as usize,
6373 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6374 goal: SelectionGoal::None,
6375 ..selection
6376 });
6377
6378 selection_adjustment += old_length - text.len() as i32;
6379
6380 edits.push((start..end, text));
6381 }
6382
6383 self.transact(cx, |this, cx| {
6384 this.buffer.update(cx, |buffer, cx| {
6385 buffer.edit(edits, None, cx);
6386 });
6387
6388 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6389 s.select(new_selections);
6390 });
6391
6392 this.request_autoscroll(Autoscroll::fit(), cx);
6393 });
6394 }
6395
6396 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6397 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6398 let buffer = &display_map.buffer_snapshot;
6399 let selections = self.selections.all::<Point>(cx);
6400
6401 let mut edits = Vec::new();
6402 let mut selections_iter = selections.iter().peekable();
6403 while let Some(selection) = selections_iter.next() {
6404 // Avoid duplicating the same lines twice.
6405 let mut rows = selection.spanned_rows(false, &display_map);
6406
6407 while let Some(next_selection) = selections_iter.peek() {
6408 let next_rows = next_selection.spanned_rows(false, &display_map);
6409 if next_rows.start < rows.end {
6410 rows.end = next_rows.end;
6411 selections_iter.next().unwrap();
6412 } else {
6413 break;
6414 }
6415 }
6416
6417 // Copy the text from the selected row region and splice it either at the start
6418 // or end of the region.
6419 let start = Point::new(rows.start.0, 0);
6420 let end = Point::new(
6421 rows.end.previous_row().0,
6422 buffer.line_len(rows.end.previous_row()),
6423 );
6424 let text = buffer
6425 .text_for_range(start..end)
6426 .chain(Some("\n"))
6427 .collect::<String>();
6428 let insert_location = if upwards {
6429 Point::new(rows.end.0, 0)
6430 } else {
6431 start
6432 };
6433 edits.push((insert_location..insert_location, text));
6434 }
6435
6436 self.transact(cx, |this, cx| {
6437 this.buffer.update(cx, |buffer, cx| {
6438 buffer.edit(edits, None, cx);
6439 });
6440
6441 this.request_autoscroll(Autoscroll::fit(), cx);
6442 });
6443 }
6444
6445 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6446 self.duplicate_line(true, cx);
6447 }
6448
6449 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6450 self.duplicate_line(false, cx);
6451 }
6452
6453 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6454 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6455 let buffer = self.buffer.read(cx).snapshot(cx);
6456
6457 let mut edits = Vec::new();
6458 let mut unfold_ranges = Vec::new();
6459 let mut refold_ranges = Vec::new();
6460
6461 let selections = self.selections.all::<Point>(cx);
6462 let mut selections = selections.iter().peekable();
6463 let mut contiguous_row_selections = Vec::new();
6464 let mut new_selections = Vec::new();
6465
6466 while let Some(selection) = selections.next() {
6467 // Find all the selections that span a contiguous row range
6468 let (start_row, end_row) = consume_contiguous_rows(
6469 &mut contiguous_row_selections,
6470 selection,
6471 &display_map,
6472 &mut selections,
6473 );
6474
6475 // Move the text spanned by the row range to be before the line preceding the row range
6476 if start_row.0 > 0 {
6477 let range_to_move = Point::new(
6478 start_row.previous_row().0,
6479 buffer.line_len(start_row.previous_row()),
6480 )
6481 ..Point::new(
6482 end_row.previous_row().0,
6483 buffer.line_len(end_row.previous_row()),
6484 );
6485 let insertion_point = display_map
6486 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6487 .0;
6488
6489 // Don't move lines across excerpts
6490 if buffer
6491 .excerpt_boundaries_in_range((
6492 Bound::Excluded(insertion_point),
6493 Bound::Included(range_to_move.end),
6494 ))
6495 .next()
6496 .is_none()
6497 {
6498 let text = buffer
6499 .text_for_range(range_to_move.clone())
6500 .flat_map(|s| s.chars())
6501 .skip(1)
6502 .chain(['\n'])
6503 .collect::<String>();
6504
6505 edits.push((
6506 buffer.anchor_after(range_to_move.start)
6507 ..buffer.anchor_before(range_to_move.end),
6508 String::new(),
6509 ));
6510 let insertion_anchor = buffer.anchor_after(insertion_point);
6511 edits.push((insertion_anchor..insertion_anchor, text));
6512
6513 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6514
6515 // Move selections up
6516 new_selections.extend(contiguous_row_selections.drain(..).map(
6517 |mut selection| {
6518 selection.start.row -= row_delta;
6519 selection.end.row -= row_delta;
6520 selection
6521 },
6522 ));
6523
6524 // Move folds up
6525 unfold_ranges.push(range_to_move.clone());
6526 for fold in display_map.folds_in_range(
6527 buffer.anchor_before(range_to_move.start)
6528 ..buffer.anchor_after(range_to_move.end),
6529 ) {
6530 let mut start = fold.range.start.to_point(&buffer);
6531 let mut end = fold.range.end.to_point(&buffer);
6532 start.row -= row_delta;
6533 end.row -= row_delta;
6534 refold_ranges.push((start..end, fold.placeholder.clone()));
6535 }
6536 }
6537 }
6538
6539 // If we didn't move line(s), preserve the existing selections
6540 new_selections.append(&mut contiguous_row_selections);
6541 }
6542
6543 self.transact(cx, |this, cx| {
6544 this.unfold_ranges(unfold_ranges, true, true, cx);
6545 this.buffer.update(cx, |buffer, cx| {
6546 for (range, text) in edits {
6547 buffer.edit([(range, text)], None, cx);
6548 }
6549 });
6550 this.fold_ranges(refold_ranges, true, cx);
6551 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6552 s.select(new_selections);
6553 })
6554 });
6555 }
6556
6557 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6558 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6559 let buffer = self.buffer.read(cx).snapshot(cx);
6560
6561 let mut edits = Vec::new();
6562 let mut unfold_ranges = Vec::new();
6563 let mut refold_ranges = Vec::new();
6564
6565 let selections = self.selections.all::<Point>(cx);
6566 let mut selections = selections.iter().peekable();
6567 let mut contiguous_row_selections = Vec::new();
6568 let mut new_selections = Vec::new();
6569
6570 while let Some(selection) = selections.next() {
6571 // Find all the selections that span a contiguous row range
6572 let (start_row, end_row) = consume_contiguous_rows(
6573 &mut contiguous_row_selections,
6574 selection,
6575 &display_map,
6576 &mut selections,
6577 );
6578
6579 // Move the text spanned by the row range to be after the last line of the row range
6580 if end_row.0 <= buffer.max_point().row {
6581 let range_to_move =
6582 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6583 let insertion_point = display_map
6584 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6585 .0;
6586
6587 // Don't move lines across excerpt boundaries
6588 if buffer
6589 .excerpt_boundaries_in_range((
6590 Bound::Excluded(range_to_move.start),
6591 Bound::Included(insertion_point),
6592 ))
6593 .next()
6594 .is_none()
6595 {
6596 let mut text = String::from("\n");
6597 text.extend(buffer.text_for_range(range_to_move.clone()));
6598 text.pop(); // Drop trailing newline
6599 edits.push((
6600 buffer.anchor_after(range_to_move.start)
6601 ..buffer.anchor_before(range_to_move.end),
6602 String::new(),
6603 ));
6604 let insertion_anchor = buffer.anchor_after(insertion_point);
6605 edits.push((insertion_anchor..insertion_anchor, text));
6606
6607 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6608
6609 // Move selections down
6610 new_selections.extend(contiguous_row_selections.drain(..).map(
6611 |mut selection| {
6612 selection.start.row += row_delta;
6613 selection.end.row += row_delta;
6614 selection
6615 },
6616 ));
6617
6618 // Move folds down
6619 unfold_ranges.push(range_to_move.clone());
6620 for fold in display_map.folds_in_range(
6621 buffer.anchor_before(range_to_move.start)
6622 ..buffer.anchor_after(range_to_move.end),
6623 ) {
6624 let mut start = fold.range.start.to_point(&buffer);
6625 let mut end = fold.range.end.to_point(&buffer);
6626 start.row += row_delta;
6627 end.row += row_delta;
6628 refold_ranges.push((start..end, fold.placeholder.clone()));
6629 }
6630 }
6631 }
6632
6633 // If we didn't move line(s), preserve the existing selections
6634 new_selections.append(&mut contiguous_row_selections);
6635 }
6636
6637 self.transact(cx, |this, cx| {
6638 this.unfold_ranges(unfold_ranges, true, true, cx);
6639 this.buffer.update(cx, |buffer, cx| {
6640 for (range, text) in edits {
6641 buffer.edit([(range, text)], None, cx);
6642 }
6643 });
6644 this.fold_ranges(refold_ranges, true, cx);
6645 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6646 });
6647 }
6648
6649 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6650 let text_layout_details = &self.text_layout_details(cx);
6651 self.transact(cx, |this, cx| {
6652 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6653 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6654 let line_mode = s.line_mode;
6655 s.move_with(|display_map, selection| {
6656 if !selection.is_empty() || line_mode {
6657 return;
6658 }
6659
6660 let mut head = selection.head();
6661 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6662 if head.column() == display_map.line_len(head.row()) {
6663 transpose_offset = display_map
6664 .buffer_snapshot
6665 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6666 }
6667
6668 if transpose_offset == 0 {
6669 return;
6670 }
6671
6672 *head.column_mut() += 1;
6673 head = display_map.clip_point(head, Bias::Right);
6674 let goal = SelectionGoal::HorizontalPosition(
6675 display_map
6676 .x_for_display_point(head, text_layout_details)
6677 .into(),
6678 );
6679 selection.collapse_to(head, goal);
6680
6681 let transpose_start = display_map
6682 .buffer_snapshot
6683 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6684 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6685 let transpose_end = display_map
6686 .buffer_snapshot
6687 .clip_offset(transpose_offset + 1, Bias::Right);
6688 if let Some(ch) =
6689 display_map.buffer_snapshot.chars_at(transpose_start).next()
6690 {
6691 edits.push((transpose_start..transpose_offset, String::new()));
6692 edits.push((transpose_end..transpose_end, ch.to_string()));
6693 }
6694 }
6695 });
6696 edits
6697 });
6698 this.buffer
6699 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6700 let selections = this.selections.all::<usize>(cx);
6701 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6702 s.select(selections);
6703 });
6704 });
6705 }
6706
6707 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6708 self.rewrap_impl(true, cx)
6709 }
6710
6711 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6712 let buffer = self.buffer.read(cx).snapshot(cx);
6713 let selections = self.selections.all::<Point>(cx);
6714 let mut selections = selections.iter().peekable();
6715
6716 let mut edits = Vec::new();
6717 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6718
6719 while let Some(selection) = selections.next() {
6720 let mut start_row = selection.start.row;
6721 let mut end_row = selection.end.row;
6722
6723 // Skip selections that overlap with a range that has already been rewrapped.
6724 let selection_range = start_row..end_row;
6725 if rewrapped_row_ranges
6726 .iter()
6727 .any(|range| range.overlaps(&selection_range))
6728 {
6729 continue;
6730 }
6731
6732 let mut should_rewrap = !only_text;
6733
6734 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6735 match language_scope.language_name().0.as_ref() {
6736 "Markdown" | "Plain Text" => {
6737 should_rewrap = true;
6738 }
6739 _ => {}
6740 }
6741 }
6742
6743 // Since not all lines in the selection may be at the same indent
6744 // level, choose the indent size that is the most common between all
6745 // of the lines.
6746 //
6747 // If there is a tie, we use the deepest indent.
6748 let (indent_size, indent_end) = {
6749 let mut indent_size_occurrences = HashMap::default();
6750 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6751
6752 for row in start_row..=end_row {
6753 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6754 rows_by_indent_size.entry(indent).or_default().push(row);
6755 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6756 }
6757
6758 let indent_size = indent_size_occurrences
6759 .into_iter()
6760 .max_by_key(|(indent, count)| (*count, indent.len))
6761 .map(|(indent, _)| indent)
6762 .unwrap_or_default();
6763 let row = rows_by_indent_size[&indent_size][0];
6764 let indent_end = Point::new(row, indent_size.len);
6765
6766 (indent_size, indent_end)
6767 };
6768
6769 let mut line_prefix = indent_size.chars().collect::<String>();
6770
6771 if let Some(comment_prefix) =
6772 buffer
6773 .language_scope_at(selection.head())
6774 .and_then(|language| {
6775 language
6776 .line_comment_prefixes()
6777 .iter()
6778 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6779 .cloned()
6780 })
6781 {
6782 line_prefix.push_str(&comment_prefix);
6783 should_rewrap = true;
6784 }
6785
6786 if selection.is_empty() {
6787 'expand_upwards: while start_row > 0 {
6788 let prev_row = start_row - 1;
6789 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6790 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6791 {
6792 start_row = prev_row;
6793 } else {
6794 break 'expand_upwards;
6795 }
6796 }
6797
6798 'expand_downwards: while end_row < buffer.max_point().row {
6799 let next_row = end_row + 1;
6800 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6801 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6802 {
6803 end_row = next_row;
6804 } else {
6805 break 'expand_downwards;
6806 }
6807 }
6808 }
6809
6810 if !should_rewrap {
6811 continue;
6812 }
6813
6814 let start = Point::new(start_row, 0);
6815 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6816 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6817 let Some(lines_without_prefixes) = selection_text
6818 .lines()
6819 .map(|line| {
6820 line.strip_prefix(&line_prefix)
6821 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6822 .ok_or_else(|| {
6823 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6824 })
6825 })
6826 .collect::<Result<Vec<_>, _>>()
6827 .log_err()
6828 else {
6829 continue;
6830 };
6831
6832 let unwrapped_text = lines_without_prefixes.join(" ");
6833 let wrap_column = buffer
6834 .settings_at(Point::new(start_row, 0), cx)
6835 .preferred_line_length as usize;
6836 let mut wrapped_text = String::new();
6837 let mut current_line = line_prefix.clone();
6838 for word in unwrapped_text.split_whitespace() {
6839 if current_line.len() + word.len() >= wrap_column {
6840 wrapped_text.push_str(¤t_line);
6841 wrapped_text.push('\n');
6842 current_line.truncate(line_prefix.len());
6843 }
6844
6845 if current_line.len() > line_prefix.len() {
6846 current_line.push(' ');
6847 }
6848
6849 current_line.push_str(word);
6850 }
6851
6852 if !current_line.is_empty() {
6853 wrapped_text.push_str(¤t_line);
6854 }
6855
6856 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
6857 let mut offset = start.to_offset(&buffer);
6858 let mut moved_since_edit = true;
6859
6860 for change in diff.iter_all_changes() {
6861 let value = change.value();
6862 match change.tag() {
6863 ChangeTag::Equal => {
6864 offset += value.len();
6865 moved_since_edit = true;
6866 }
6867 ChangeTag::Delete => {
6868 let start = buffer.anchor_after(offset);
6869 let end = buffer.anchor_before(offset + value.len());
6870
6871 if moved_since_edit {
6872 edits.push((start..end, String::new()));
6873 } else {
6874 edits.last_mut().unwrap().0.end = end;
6875 }
6876
6877 offset += value.len();
6878 moved_since_edit = false;
6879 }
6880 ChangeTag::Insert => {
6881 if moved_since_edit {
6882 let anchor = buffer.anchor_after(offset);
6883 edits.push((anchor..anchor, value.to_string()));
6884 } else {
6885 edits.last_mut().unwrap().1.push_str(value);
6886 }
6887
6888 moved_since_edit = false;
6889 }
6890 }
6891 }
6892
6893 rewrapped_row_ranges.push(start_row..=end_row);
6894 }
6895
6896 self.buffer
6897 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6898 }
6899
6900 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6901 let mut text = String::new();
6902 let buffer = self.buffer.read(cx).snapshot(cx);
6903 let mut selections = self.selections.all::<Point>(cx);
6904 let mut clipboard_selections = Vec::with_capacity(selections.len());
6905 {
6906 let max_point = buffer.max_point();
6907 let mut is_first = true;
6908 for selection in &mut selections {
6909 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6910 if is_entire_line {
6911 selection.start = Point::new(selection.start.row, 0);
6912 if !selection.is_empty() && selection.end.column == 0 {
6913 selection.end = cmp::min(max_point, selection.end);
6914 } else {
6915 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6916 }
6917 selection.goal = SelectionGoal::None;
6918 }
6919 if is_first {
6920 is_first = false;
6921 } else {
6922 text += "\n";
6923 }
6924 let mut len = 0;
6925 for chunk in buffer.text_for_range(selection.start..selection.end) {
6926 text.push_str(chunk);
6927 len += chunk.len();
6928 }
6929 clipboard_selections.push(ClipboardSelection {
6930 len,
6931 is_entire_line,
6932 first_line_indent: buffer
6933 .indent_size_for_line(MultiBufferRow(selection.start.row))
6934 .len,
6935 });
6936 }
6937 }
6938
6939 self.transact(cx, |this, cx| {
6940 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6941 s.select(selections);
6942 });
6943 this.insert("", cx);
6944 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6945 text,
6946 clipboard_selections,
6947 ));
6948 });
6949 }
6950
6951 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6952 let selections = self.selections.all::<Point>(cx);
6953 let buffer = self.buffer.read(cx).read(cx);
6954 let mut text = String::new();
6955
6956 let mut clipboard_selections = Vec::with_capacity(selections.len());
6957 {
6958 let max_point = buffer.max_point();
6959 let mut is_first = true;
6960 for selection in selections.iter() {
6961 let mut start = selection.start;
6962 let mut end = selection.end;
6963 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6964 if is_entire_line {
6965 start = Point::new(start.row, 0);
6966 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6967 }
6968 if is_first {
6969 is_first = false;
6970 } else {
6971 text += "\n";
6972 }
6973 let mut len = 0;
6974 for chunk in buffer.text_for_range(start..end) {
6975 text.push_str(chunk);
6976 len += chunk.len();
6977 }
6978 clipboard_selections.push(ClipboardSelection {
6979 len,
6980 is_entire_line,
6981 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6982 });
6983 }
6984 }
6985
6986 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6987 text,
6988 clipboard_selections,
6989 ));
6990 }
6991
6992 pub fn do_paste(
6993 &mut self,
6994 text: &String,
6995 clipboard_selections: Option<Vec<ClipboardSelection>>,
6996 handle_entire_lines: bool,
6997 cx: &mut ViewContext<Self>,
6998 ) {
6999 if self.read_only(cx) {
7000 return;
7001 }
7002
7003 let clipboard_text = Cow::Borrowed(text);
7004
7005 self.transact(cx, |this, cx| {
7006 if let Some(mut clipboard_selections) = clipboard_selections {
7007 let old_selections = this.selections.all::<usize>(cx);
7008 let all_selections_were_entire_line =
7009 clipboard_selections.iter().all(|s| s.is_entire_line);
7010 let first_selection_indent_column =
7011 clipboard_selections.first().map(|s| s.first_line_indent);
7012 if clipboard_selections.len() != old_selections.len() {
7013 clipboard_selections.drain(..);
7014 }
7015
7016 this.buffer.update(cx, |buffer, cx| {
7017 let snapshot = buffer.read(cx);
7018 let mut start_offset = 0;
7019 let mut edits = Vec::new();
7020 let mut original_indent_columns = Vec::new();
7021 for (ix, selection) in old_selections.iter().enumerate() {
7022 let to_insert;
7023 let entire_line;
7024 let original_indent_column;
7025 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7026 let end_offset = start_offset + clipboard_selection.len;
7027 to_insert = &clipboard_text[start_offset..end_offset];
7028 entire_line = clipboard_selection.is_entire_line;
7029 start_offset = end_offset + 1;
7030 original_indent_column = Some(clipboard_selection.first_line_indent);
7031 } else {
7032 to_insert = clipboard_text.as_str();
7033 entire_line = all_selections_were_entire_line;
7034 original_indent_column = first_selection_indent_column
7035 }
7036
7037 // If the corresponding selection was empty when this slice of the
7038 // clipboard text was written, then the entire line containing the
7039 // selection was copied. If this selection is also currently empty,
7040 // then paste the line before the current line of the buffer.
7041 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7042 let column = selection.start.to_point(&snapshot).column as usize;
7043 let line_start = selection.start - column;
7044 line_start..line_start
7045 } else {
7046 selection.range()
7047 };
7048
7049 edits.push((range, to_insert));
7050 original_indent_columns.extend(original_indent_column);
7051 }
7052 drop(snapshot);
7053
7054 buffer.edit(
7055 edits,
7056 Some(AutoindentMode::Block {
7057 original_indent_columns,
7058 }),
7059 cx,
7060 );
7061 });
7062
7063 let selections = this.selections.all::<usize>(cx);
7064 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7065 } else {
7066 this.insert(&clipboard_text, cx);
7067 }
7068 });
7069 }
7070
7071 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7072 if let Some(item) = cx.read_from_clipboard() {
7073 let entries = item.entries();
7074
7075 match entries.first() {
7076 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7077 // of all the pasted entries.
7078 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7079 .do_paste(
7080 clipboard_string.text(),
7081 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7082 true,
7083 cx,
7084 ),
7085 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7086 }
7087 }
7088 }
7089
7090 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7091 if self.read_only(cx) {
7092 return;
7093 }
7094
7095 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7096 if let Some((selections, _)) =
7097 self.selection_history.transaction(transaction_id).cloned()
7098 {
7099 self.change_selections(None, cx, |s| {
7100 s.select_anchors(selections.to_vec());
7101 });
7102 }
7103 self.request_autoscroll(Autoscroll::fit(), cx);
7104 self.unmark_text(cx);
7105 self.refresh_inline_completion(true, false, cx);
7106 cx.emit(EditorEvent::Edited { transaction_id });
7107 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7108 }
7109 }
7110
7111 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7112 if self.read_only(cx) {
7113 return;
7114 }
7115
7116 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7117 if let Some((_, Some(selections))) =
7118 self.selection_history.transaction(transaction_id).cloned()
7119 {
7120 self.change_selections(None, cx, |s| {
7121 s.select_anchors(selections.to_vec());
7122 });
7123 }
7124 self.request_autoscroll(Autoscroll::fit(), cx);
7125 self.unmark_text(cx);
7126 self.refresh_inline_completion(true, false, cx);
7127 cx.emit(EditorEvent::Edited { transaction_id });
7128 }
7129 }
7130
7131 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7132 self.buffer
7133 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7134 }
7135
7136 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7137 self.buffer
7138 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7139 }
7140
7141 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7142 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7143 let line_mode = s.line_mode;
7144 s.move_with(|map, selection| {
7145 let cursor = if selection.is_empty() && !line_mode {
7146 movement::left(map, selection.start)
7147 } else {
7148 selection.start
7149 };
7150 selection.collapse_to(cursor, SelectionGoal::None);
7151 });
7152 })
7153 }
7154
7155 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7156 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7157 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7158 })
7159 }
7160
7161 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7162 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7163 let line_mode = s.line_mode;
7164 s.move_with(|map, selection| {
7165 let cursor = if selection.is_empty() && !line_mode {
7166 movement::right(map, selection.end)
7167 } else {
7168 selection.end
7169 };
7170 selection.collapse_to(cursor, SelectionGoal::None)
7171 });
7172 })
7173 }
7174
7175 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7176 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7177 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7178 })
7179 }
7180
7181 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7182 if self.take_rename(true, cx).is_some() {
7183 return;
7184 }
7185
7186 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7187 cx.propagate();
7188 return;
7189 }
7190
7191 let text_layout_details = &self.text_layout_details(cx);
7192 let selection_count = self.selections.count();
7193 let first_selection = self.selections.first_anchor();
7194
7195 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7196 let line_mode = s.line_mode;
7197 s.move_with(|map, selection| {
7198 if !selection.is_empty() && !line_mode {
7199 selection.goal = SelectionGoal::None;
7200 }
7201 let (cursor, goal) = movement::up(
7202 map,
7203 selection.start,
7204 selection.goal,
7205 false,
7206 text_layout_details,
7207 );
7208 selection.collapse_to(cursor, goal);
7209 });
7210 });
7211
7212 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7213 {
7214 cx.propagate();
7215 }
7216 }
7217
7218 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7219 if self.take_rename(true, cx).is_some() {
7220 return;
7221 }
7222
7223 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7224 cx.propagate();
7225 return;
7226 }
7227
7228 let text_layout_details = &self.text_layout_details(cx);
7229
7230 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7231 let line_mode = s.line_mode;
7232 s.move_with(|map, selection| {
7233 if !selection.is_empty() && !line_mode {
7234 selection.goal = SelectionGoal::None;
7235 }
7236 let (cursor, goal) = movement::up_by_rows(
7237 map,
7238 selection.start,
7239 action.lines,
7240 selection.goal,
7241 false,
7242 text_layout_details,
7243 );
7244 selection.collapse_to(cursor, goal);
7245 });
7246 })
7247 }
7248
7249 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7250 if self.take_rename(true, cx).is_some() {
7251 return;
7252 }
7253
7254 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7255 cx.propagate();
7256 return;
7257 }
7258
7259 let text_layout_details = &self.text_layout_details(cx);
7260
7261 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7262 let line_mode = s.line_mode;
7263 s.move_with(|map, selection| {
7264 if !selection.is_empty() && !line_mode {
7265 selection.goal = SelectionGoal::None;
7266 }
7267 let (cursor, goal) = movement::down_by_rows(
7268 map,
7269 selection.start,
7270 action.lines,
7271 selection.goal,
7272 false,
7273 text_layout_details,
7274 );
7275 selection.collapse_to(cursor, goal);
7276 });
7277 })
7278 }
7279
7280 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7281 let text_layout_details = &self.text_layout_details(cx);
7282 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7283 s.move_heads_with(|map, head, goal| {
7284 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7285 })
7286 })
7287 }
7288
7289 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7290 let text_layout_details = &self.text_layout_details(cx);
7291 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7292 s.move_heads_with(|map, head, goal| {
7293 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7294 })
7295 })
7296 }
7297
7298 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7299 let Some(row_count) = self.visible_row_count() else {
7300 return;
7301 };
7302
7303 let text_layout_details = &self.text_layout_details(cx);
7304
7305 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7306 s.move_heads_with(|map, head, goal| {
7307 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7308 })
7309 })
7310 }
7311
7312 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7313 if self.take_rename(true, cx).is_some() {
7314 return;
7315 }
7316
7317 if self
7318 .context_menu
7319 .write()
7320 .as_mut()
7321 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7322 .unwrap_or(false)
7323 {
7324 return;
7325 }
7326
7327 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7328 cx.propagate();
7329 return;
7330 }
7331
7332 let Some(row_count) = self.visible_row_count() else {
7333 return;
7334 };
7335
7336 let autoscroll = if action.center_cursor {
7337 Autoscroll::center()
7338 } else {
7339 Autoscroll::fit()
7340 };
7341
7342 let text_layout_details = &self.text_layout_details(cx);
7343
7344 self.change_selections(Some(autoscroll), cx, |s| {
7345 let line_mode = s.line_mode;
7346 s.move_with(|map, selection| {
7347 if !selection.is_empty() && !line_mode {
7348 selection.goal = SelectionGoal::None;
7349 }
7350 let (cursor, goal) = movement::up_by_rows(
7351 map,
7352 selection.end,
7353 row_count,
7354 selection.goal,
7355 false,
7356 text_layout_details,
7357 );
7358 selection.collapse_to(cursor, goal);
7359 });
7360 });
7361 }
7362
7363 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7364 let text_layout_details = &self.text_layout_details(cx);
7365 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7366 s.move_heads_with(|map, head, goal| {
7367 movement::up(map, head, goal, false, text_layout_details)
7368 })
7369 })
7370 }
7371
7372 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7373 self.take_rename(true, cx);
7374
7375 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7376 cx.propagate();
7377 return;
7378 }
7379
7380 let text_layout_details = &self.text_layout_details(cx);
7381 let selection_count = self.selections.count();
7382 let first_selection = self.selections.first_anchor();
7383
7384 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7385 let line_mode = s.line_mode;
7386 s.move_with(|map, selection| {
7387 if !selection.is_empty() && !line_mode {
7388 selection.goal = SelectionGoal::None;
7389 }
7390 let (cursor, goal) = movement::down(
7391 map,
7392 selection.end,
7393 selection.goal,
7394 false,
7395 text_layout_details,
7396 );
7397 selection.collapse_to(cursor, goal);
7398 });
7399 });
7400
7401 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7402 {
7403 cx.propagate();
7404 }
7405 }
7406
7407 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7408 let Some(row_count) = self.visible_row_count() else {
7409 return;
7410 };
7411
7412 let text_layout_details = &self.text_layout_details(cx);
7413
7414 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7415 s.move_heads_with(|map, head, goal| {
7416 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7417 })
7418 })
7419 }
7420
7421 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7422 if self.take_rename(true, cx).is_some() {
7423 return;
7424 }
7425
7426 if self
7427 .context_menu
7428 .write()
7429 .as_mut()
7430 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7431 .unwrap_or(false)
7432 {
7433 return;
7434 }
7435
7436 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7437 cx.propagate();
7438 return;
7439 }
7440
7441 let Some(row_count) = self.visible_row_count() else {
7442 return;
7443 };
7444
7445 let autoscroll = if action.center_cursor {
7446 Autoscroll::center()
7447 } else {
7448 Autoscroll::fit()
7449 };
7450
7451 let text_layout_details = &self.text_layout_details(cx);
7452 self.change_selections(Some(autoscroll), cx, |s| {
7453 let line_mode = s.line_mode;
7454 s.move_with(|map, selection| {
7455 if !selection.is_empty() && !line_mode {
7456 selection.goal = SelectionGoal::None;
7457 }
7458 let (cursor, goal) = movement::down_by_rows(
7459 map,
7460 selection.end,
7461 row_count,
7462 selection.goal,
7463 false,
7464 text_layout_details,
7465 );
7466 selection.collapse_to(cursor, goal);
7467 });
7468 });
7469 }
7470
7471 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7472 let text_layout_details = &self.text_layout_details(cx);
7473 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7474 s.move_heads_with(|map, head, goal| {
7475 movement::down(map, head, goal, false, text_layout_details)
7476 })
7477 });
7478 }
7479
7480 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7481 if let Some(context_menu) = self.context_menu.write().as_mut() {
7482 context_menu.select_first(self.project.as_ref(), cx);
7483 }
7484 }
7485
7486 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7487 if let Some(context_menu) = self.context_menu.write().as_mut() {
7488 context_menu.select_prev(self.project.as_ref(), cx);
7489 }
7490 }
7491
7492 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7493 if let Some(context_menu) = self.context_menu.write().as_mut() {
7494 context_menu.select_next(self.project.as_ref(), cx);
7495 }
7496 }
7497
7498 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7499 if let Some(context_menu) = self.context_menu.write().as_mut() {
7500 context_menu.select_last(self.project.as_ref(), cx);
7501 }
7502 }
7503
7504 pub fn move_to_previous_word_start(
7505 &mut self,
7506 _: &MoveToPreviousWordStart,
7507 cx: &mut ViewContext<Self>,
7508 ) {
7509 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7510 s.move_cursors_with(|map, head, _| {
7511 (
7512 movement::previous_word_start(map, head),
7513 SelectionGoal::None,
7514 )
7515 });
7516 })
7517 }
7518
7519 pub fn move_to_previous_subword_start(
7520 &mut self,
7521 _: &MoveToPreviousSubwordStart,
7522 cx: &mut ViewContext<Self>,
7523 ) {
7524 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7525 s.move_cursors_with(|map, head, _| {
7526 (
7527 movement::previous_subword_start(map, head),
7528 SelectionGoal::None,
7529 )
7530 });
7531 })
7532 }
7533
7534 pub fn select_to_previous_word_start(
7535 &mut self,
7536 _: &SelectToPreviousWordStart,
7537 cx: &mut ViewContext<Self>,
7538 ) {
7539 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7540 s.move_heads_with(|map, head, _| {
7541 (
7542 movement::previous_word_start(map, head),
7543 SelectionGoal::None,
7544 )
7545 });
7546 })
7547 }
7548
7549 pub fn select_to_previous_subword_start(
7550 &mut self,
7551 _: &SelectToPreviousSubwordStart,
7552 cx: &mut ViewContext<Self>,
7553 ) {
7554 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7555 s.move_heads_with(|map, head, _| {
7556 (
7557 movement::previous_subword_start(map, head),
7558 SelectionGoal::None,
7559 )
7560 });
7561 })
7562 }
7563
7564 pub fn delete_to_previous_word_start(
7565 &mut self,
7566 action: &DeleteToPreviousWordStart,
7567 cx: &mut ViewContext<Self>,
7568 ) {
7569 self.transact(cx, |this, cx| {
7570 this.select_autoclose_pair(cx);
7571 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7572 let line_mode = s.line_mode;
7573 s.move_with(|map, selection| {
7574 if selection.is_empty() && !line_mode {
7575 let cursor = if action.ignore_newlines {
7576 movement::previous_word_start(map, selection.head())
7577 } else {
7578 movement::previous_word_start_or_newline(map, selection.head())
7579 };
7580 selection.set_head(cursor, SelectionGoal::None);
7581 }
7582 });
7583 });
7584 this.insert("", cx);
7585 });
7586 }
7587
7588 pub fn delete_to_previous_subword_start(
7589 &mut self,
7590 _: &DeleteToPreviousSubwordStart,
7591 cx: &mut ViewContext<Self>,
7592 ) {
7593 self.transact(cx, |this, cx| {
7594 this.select_autoclose_pair(cx);
7595 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7596 let line_mode = s.line_mode;
7597 s.move_with(|map, selection| {
7598 if selection.is_empty() && !line_mode {
7599 let cursor = movement::previous_subword_start(map, selection.head());
7600 selection.set_head(cursor, SelectionGoal::None);
7601 }
7602 });
7603 });
7604 this.insert("", cx);
7605 });
7606 }
7607
7608 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7609 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7610 s.move_cursors_with(|map, head, _| {
7611 (movement::next_word_end(map, head), SelectionGoal::None)
7612 });
7613 })
7614 }
7615
7616 pub fn move_to_next_subword_end(
7617 &mut self,
7618 _: &MoveToNextSubwordEnd,
7619 cx: &mut ViewContext<Self>,
7620 ) {
7621 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7622 s.move_cursors_with(|map, head, _| {
7623 (movement::next_subword_end(map, head), SelectionGoal::None)
7624 });
7625 })
7626 }
7627
7628 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7629 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7630 s.move_heads_with(|map, head, _| {
7631 (movement::next_word_end(map, head), SelectionGoal::None)
7632 });
7633 })
7634 }
7635
7636 pub fn select_to_next_subword_end(
7637 &mut self,
7638 _: &SelectToNextSubwordEnd,
7639 cx: &mut ViewContext<Self>,
7640 ) {
7641 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7642 s.move_heads_with(|map, head, _| {
7643 (movement::next_subword_end(map, head), SelectionGoal::None)
7644 });
7645 })
7646 }
7647
7648 pub fn delete_to_next_word_end(
7649 &mut self,
7650 action: &DeleteToNextWordEnd,
7651 cx: &mut ViewContext<Self>,
7652 ) {
7653 self.transact(cx, |this, cx| {
7654 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7655 let line_mode = s.line_mode;
7656 s.move_with(|map, selection| {
7657 if selection.is_empty() && !line_mode {
7658 let cursor = if action.ignore_newlines {
7659 movement::next_word_end(map, selection.head())
7660 } else {
7661 movement::next_word_end_or_newline(map, selection.head())
7662 };
7663 selection.set_head(cursor, SelectionGoal::None);
7664 }
7665 });
7666 });
7667 this.insert("", cx);
7668 });
7669 }
7670
7671 pub fn delete_to_next_subword_end(
7672 &mut self,
7673 _: &DeleteToNextSubwordEnd,
7674 cx: &mut ViewContext<Self>,
7675 ) {
7676 self.transact(cx, |this, cx| {
7677 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7678 s.move_with(|map, selection| {
7679 if selection.is_empty() {
7680 let cursor = movement::next_subword_end(map, selection.head());
7681 selection.set_head(cursor, SelectionGoal::None);
7682 }
7683 });
7684 });
7685 this.insert("", cx);
7686 });
7687 }
7688
7689 pub fn move_to_beginning_of_line(
7690 &mut self,
7691 action: &MoveToBeginningOfLine,
7692 cx: &mut ViewContext<Self>,
7693 ) {
7694 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7695 s.move_cursors_with(|map, head, _| {
7696 (
7697 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7698 SelectionGoal::None,
7699 )
7700 });
7701 })
7702 }
7703
7704 pub fn select_to_beginning_of_line(
7705 &mut self,
7706 action: &SelectToBeginningOfLine,
7707 cx: &mut ViewContext<Self>,
7708 ) {
7709 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7710 s.move_heads_with(|map, head, _| {
7711 (
7712 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7713 SelectionGoal::None,
7714 )
7715 });
7716 });
7717 }
7718
7719 pub fn delete_to_beginning_of_line(
7720 &mut self,
7721 _: &DeleteToBeginningOfLine,
7722 cx: &mut ViewContext<Self>,
7723 ) {
7724 self.transact(cx, |this, cx| {
7725 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7726 s.move_with(|_, selection| {
7727 selection.reversed = true;
7728 });
7729 });
7730
7731 this.select_to_beginning_of_line(
7732 &SelectToBeginningOfLine {
7733 stop_at_soft_wraps: false,
7734 },
7735 cx,
7736 );
7737 this.backspace(&Backspace, cx);
7738 });
7739 }
7740
7741 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7742 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7743 s.move_cursors_with(|map, head, _| {
7744 (
7745 movement::line_end(map, head, action.stop_at_soft_wraps),
7746 SelectionGoal::None,
7747 )
7748 });
7749 })
7750 }
7751
7752 pub fn select_to_end_of_line(
7753 &mut self,
7754 action: &SelectToEndOfLine,
7755 cx: &mut ViewContext<Self>,
7756 ) {
7757 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7758 s.move_heads_with(|map, head, _| {
7759 (
7760 movement::line_end(map, head, action.stop_at_soft_wraps),
7761 SelectionGoal::None,
7762 )
7763 });
7764 })
7765 }
7766
7767 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7768 self.transact(cx, |this, cx| {
7769 this.select_to_end_of_line(
7770 &SelectToEndOfLine {
7771 stop_at_soft_wraps: false,
7772 },
7773 cx,
7774 );
7775 this.delete(&Delete, cx);
7776 });
7777 }
7778
7779 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7780 self.transact(cx, |this, cx| {
7781 this.select_to_end_of_line(
7782 &SelectToEndOfLine {
7783 stop_at_soft_wraps: false,
7784 },
7785 cx,
7786 );
7787 this.cut(&Cut, cx);
7788 });
7789 }
7790
7791 pub fn move_to_start_of_paragraph(
7792 &mut self,
7793 _: &MoveToStartOfParagraph,
7794 cx: &mut ViewContext<Self>,
7795 ) {
7796 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7797 cx.propagate();
7798 return;
7799 }
7800
7801 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7802 s.move_with(|map, selection| {
7803 selection.collapse_to(
7804 movement::start_of_paragraph(map, selection.head(), 1),
7805 SelectionGoal::None,
7806 )
7807 });
7808 })
7809 }
7810
7811 pub fn move_to_end_of_paragraph(
7812 &mut self,
7813 _: &MoveToEndOfParagraph,
7814 cx: &mut ViewContext<Self>,
7815 ) {
7816 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7817 cx.propagate();
7818 return;
7819 }
7820
7821 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7822 s.move_with(|map, selection| {
7823 selection.collapse_to(
7824 movement::end_of_paragraph(map, selection.head(), 1),
7825 SelectionGoal::None,
7826 )
7827 });
7828 })
7829 }
7830
7831 pub fn select_to_start_of_paragraph(
7832 &mut self,
7833 _: &SelectToStartOfParagraph,
7834 cx: &mut ViewContext<Self>,
7835 ) {
7836 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7837 cx.propagate();
7838 return;
7839 }
7840
7841 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7842 s.move_heads_with(|map, head, _| {
7843 (
7844 movement::start_of_paragraph(map, head, 1),
7845 SelectionGoal::None,
7846 )
7847 });
7848 })
7849 }
7850
7851 pub fn select_to_end_of_paragraph(
7852 &mut self,
7853 _: &SelectToEndOfParagraph,
7854 cx: &mut ViewContext<Self>,
7855 ) {
7856 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7857 cx.propagate();
7858 return;
7859 }
7860
7861 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7862 s.move_heads_with(|map, head, _| {
7863 (
7864 movement::end_of_paragraph(map, head, 1),
7865 SelectionGoal::None,
7866 )
7867 });
7868 })
7869 }
7870
7871 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7872 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7873 cx.propagate();
7874 return;
7875 }
7876
7877 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7878 s.select_ranges(vec![0..0]);
7879 });
7880 }
7881
7882 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7883 let mut selection = self.selections.last::<Point>(cx);
7884 selection.set_head(Point::zero(), SelectionGoal::None);
7885
7886 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7887 s.select(vec![selection]);
7888 });
7889 }
7890
7891 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7892 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7893 cx.propagate();
7894 return;
7895 }
7896
7897 let cursor = self.buffer.read(cx).read(cx).len();
7898 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7899 s.select_ranges(vec![cursor..cursor])
7900 });
7901 }
7902
7903 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7904 self.nav_history = nav_history;
7905 }
7906
7907 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7908 self.nav_history.as_ref()
7909 }
7910
7911 fn push_to_nav_history(
7912 &mut self,
7913 cursor_anchor: Anchor,
7914 new_position: Option<Point>,
7915 cx: &mut ViewContext<Self>,
7916 ) {
7917 if let Some(nav_history) = self.nav_history.as_mut() {
7918 let buffer = self.buffer.read(cx).read(cx);
7919 let cursor_position = cursor_anchor.to_point(&buffer);
7920 let scroll_state = self.scroll_manager.anchor();
7921 let scroll_top_row = scroll_state.top_row(&buffer);
7922 drop(buffer);
7923
7924 if let Some(new_position) = new_position {
7925 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7926 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7927 return;
7928 }
7929 }
7930
7931 nav_history.push(
7932 Some(NavigationData {
7933 cursor_anchor,
7934 cursor_position,
7935 scroll_anchor: scroll_state,
7936 scroll_top_row,
7937 }),
7938 cx,
7939 );
7940 }
7941 }
7942
7943 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7944 let buffer = self.buffer.read(cx).snapshot(cx);
7945 let mut selection = self.selections.first::<usize>(cx);
7946 selection.set_head(buffer.len(), SelectionGoal::None);
7947 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7948 s.select(vec![selection]);
7949 });
7950 }
7951
7952 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7953 let end = self.buffer.read(cx).read(cx).len();
7954 self.change_selections(None, cx, |s| {
7955 s.select_ranges(vec![0..end]);
7956 });
7957 }
7958
7959 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7960 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7961 let mut selections = self.selections.all::<Point>(cx);
7962 let max_point = display_map.buffer_snapshot.max_point();
7963 for selection in &mut selections {
7964 let rows = selection.spanned_rows(true, &display_map);
7965 selection.start = Point::new(rows.start.0, 0);
7966 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7967 selection.reversed = false;
7968 }
7969 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7970 s.select(selections);
7971 });
7972 }
7973
7974 pub fn split_selection_into_lines(
7975 &mut self,
7976 _: &SplitSelectionIntoLines,
7977 cx: &mut ViewContext<Self>,
7978 ) {
7979 let mut to_unfold = Vec::new();
7980 let mut new_selection_ranges = Vec::new();
7981 {
7982 let selections = self.selections.all::<Point>(cx);
7983 let buffer = self.buffer.read(cx).read(cx);
7984 for selection in selections {
7985 for row in selection.start.row..selection.end.row {
7986 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7987 new_selection_ranges.push(cursor..cursor);
7988 }
7989 new_selection_ranges.push(selection.end..selection.end);
7990 to_unfold.push(selection.start..selection.end);
7991 }
7992 }
7993 self.unfold_ranges(to_unfold, true, true, cx);
7994 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7995 s.select_ranges(new_selection_ranges);
7996 });
7997 }
7998
7999 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8000 self.add_selection(true, cx);
8001 }
8002
8003 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8004 self.add_selection(false, cx);
8005 }
8006
8007 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8008 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8009 let mut selections = self.selections.all::<Point>(cx);
8010 let text_layout_details = self.text_layout_details(cx);
8011 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8012 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8013 let range = oldest_selection.display_range(&display_map).sorted();
8014
8015 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8016 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8017 let positions = start_x.min(end_x)..start_x.max(end_x);
8018
8019 selections.clear();
8020 let mut stack = Vec::new();
8021 for row in range.start.row().0..=range.end.row().0 {
8022 if let Some(selection) = self.selections.build_columnar_selection(
8023 &display_map,
8024 DisplayRow(row),
8025 &positions,
8026 oldest_selection.reversed,
8027 &text_layout_details,
8028 ) {
8029 stack.push(selection.id);
8030 selections.push(selection);
8031 }
8032 }
8033
8034 if above {
8035 stack.reverse();
8036 }
8037
8038 AddSelectionsState { above, stack }
8039 });
8040
8041 let last_added_selection = *state.stack.last().unwrap();
8042 let mut new_selections = Vec::new();
8043 if above == state.above {
8044 let end_row = if above {
8045 DisplayRow(0)
8046 } else {
8047 display_map.max_point().row()
8048 };
8049
8050 'outer: for selection in selections {
8051 if selection.id == last_added_selection {
8052 let range = selection.display_range(&display_map).sorted();
8053 debug_assert_eq!(range.start.row(), range.end.row());
8054 let mut row = range.start.row();
8055 let positions =
8056 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8057 px(start)..px(end)
8058 } else {
8059 let start_x =
8060 display_map.x_for_display_point(range.start, &text_layout_details);
8061 let end_x =
8062 display_map.x_for_display_point(range.end, &text_layout_details);
8063 start_x.min(end_x)..start_x.max(end_x)
8064 };
8065
8066 while row != end_row {
8067 if above {
8068 row.0 -= 1;
8069 } else {
8070 row.0 += 1;
8071 }
8072
8073 if let Some(new_selection) = self.selections.build_columnar_selection(
8074 &display_map,
8075 row,
8076 &positions,
8077 selection.reversed,
8078 &text_layout_details,
8079 ) {
8080 state.stack.push(new_selection.id);
8081 if above {
8082 new_selections.push(new_selection);
8083 new_selections.push(selection);
8084 } else {
8085 new_selections.push(selection);
8086 new_selections.push(new_selection);
8087 }
8088
8089 continue 'outer;
8090 }
8091 }
8092 }
8093
8094 new_selections.push(selection);
8095 }
8096 } else {
8097 new_selections = selections;
8098 new_selections.retain(|s| s.id != last_added_selection);
8099 state.stack.pop();
8100 }
8101
8102 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8103 s.select(new_selections);
8104 });
8105 if state.stack.len() > 1 {
8106 self.add_selections_state = Some(state);
8107 }
8108 }
8109
8110 pub fn select_next_match_internal(
8111 &mut self,
8112 display_map: &DisplaySnapshot,
8113 replace_newest: bool,
8114 autoscroll: Option<Autoscroll>,
8115 cx: &mut ViewContext<Self>,
8116 ) -> Result<()> {
8117 fn select_next_match_ranges(
8118 this: &mut Editor,
8119 range: Range<usize>,
8120 replace_newest: bool,
8121 auto_scroll: Option<Autoscroll>,
8122 cx: &mut ViewContext<Editor>,
8123 ) {
8124 this.unfold_ranges([range.clone()], false, true, cx);
8125 this.change_selections(auto_scroll, cx, |s| {
8126 if replace_newest {
8127 s.delete(s.newest_anchor().id);
8128 }
8129 s.insert_range(range.clone());
8130 });
8131 }
8132
8133 let buffer = &display_map.buffer_snapshot;
8134 let mut selections = self.selections.all::<usize>(cx);
8135 if let Some(mut select_next_state) = self.select_next_state.take() {
8136 let query = &select_next_state.query;
8137 if !select_next_state.done {
8138 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8139 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8140 let mut next_selected_range = None;
8141
8142 let bytes_after_last_selection =
8143 buffer.bytes_in_range(last_selection.end..buffer.len());
8144 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8145 let query_matches = query
8146 .stream_find_iter(bytes_after_last_selection)
8147 .map(|result| (last_selection.end, result))
8148 .chain(
8149 query
8150 .stream_find_iter(bytes_before_first_selection)
8151 .map(|result| (0, result)),
8152 );
8153
8154 for (start_offset, query_match) in query_matches {
8155 let query_match = query_match.unwrap(); // can only fail due to I/O
8156 let offset_range =
8157 start_offset + query_match.start()..start_offset + query_match.end();
8158 let display_range = offset_range.start.to_display_point(display_map)
8159 ..offset_range.end.to_display_point(display_map);
8160
8161 if !select_next_state.wordwise
8162 || (!movement::is_inside_word(display_map, display_range.start)
8163 && !movement::is_inside_word(display_map, display_range.end))
8164 {
8165 // TODO: This is n^2, because we might check all the selections
8166 if !selections
8167 .iter()
8168 .any(|selection| selection.range().overlaps(&offset_range))
8169 {
8170 next_selected_range = Some(offset_range);
8171 break;
8172 }
8173 }
8174 }
8175
8176 if let Some(next_selected_range) = next_selected_range {
8177 select_next_match_ranges(
8178 self,
8179 next_selected_range,
8180 replace_newest,
8181 autoscroll,
8182 cx,
8183 );
8184 } else {
8185 select_next_state.done = true;
8186 }
8187 }
8188
8189 self.select_next_state = Some(select_next_state);
8190 } else {
8191 let mut only_carets = true;
8192 let mut same_text_selected = true;
8193 let mut selected_text = None;
8194
8195 let mut selections_iter = selections.iter().peekable();
8196 while let Some(selection) = selections_iter.next() {
8197 if selection.start != selection.end {
8198 only_carets = false;
8199 }
8200
8201 if same_text_selected {
8202 if selected_text.is_none() {
8203 selected_text =
8204 Some(buffer.text_for_range(selection.range()).collect::<String>());
8205 }
8206
8207 if let Some(next_selection) = selections_iter.peek() {
8208 if next_selection.range().len() == selection.range().len() {
8209 let next_selected_text = buffer
8210 .text_for_range(next_selection.range())
8211 .collect::<String>();
8212 if Some(next_selected_text) != selected_text {
8213 same_text_selected = false;
8214 selected_text = None;
8215 }
8216 } else {
8217 same_text_selected = false;
8218 selected_text = None;
8219 }
8220 }
8221 }
8222 }
8223
8224 if only_carets {
8225 for selection in &mut selections {
8226 let word_range = movement::surrounding_word(
8227 display_map,
8228 selection.start.to_display_point(display_map),
8229 );
8230 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8231 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8232 selection.goal = SelectionGoal::None;
8233 selection.reversed = false;
8234 select_next_match_ranges(
8235 self,
8236 selection.start..selection.end,
8237 replace_newest,
8238 autoscroll,
8239 cx,
8240 );
8241 }
8242
8243 if selections.len() == 1 {
8244 let selection = selections
8245 .last()
8246 .expect("ensured that there's only one selection");
8247 let query = buffer
8248 .text_for_range(selection.start..selection.end)
8249 .collect::<String>();
8250 let is_empty = query.is_empty();
8251 let select_state = SelectNextState {
8252 query: AhoCorasick::new(&[query])?,
8253 wordwise: true,
8254 done: is_empty,
8255 };
8256 self.select_next_state = Some(select_state);
8257 } else {
8258 self.select_next_state = None;
8259 }
8260 } else if let Some(selected_text) = selected_text {
8261 self.select_next_state = Some(SelectNextState {
8262 query: AhoCorasick::new(&[selected_text])?,
8263 wordwise: false,
8264 done: false,
8265 });
8266 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8267 }
8268 }
8269 Ok(())
8270 }
8271
8272 pub fn select_all_matches(
8273 &mut self,
8274 _action: &SelectAllMatches,
8275 cx: &mut ViewContext<Self>,
8276 ) -> Result<()> {
8277 self.push_to_selection_history();
8278 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8279
8280 self.select_next_match_internal(&display_map, false, None, cx)?;
8281 let Some(select_next_state) = self.select_next_state.as_mut() else {
8282 return Ok(());
8283 };
8284 if select_next_state.done {
8285 return Ok(());
8286 }
8287
8288 let mut new_selections = self.selections.all::<usize>(cx);
8289
8290 let buffer = &display_map.buffer_snapshot;
8291 let query_matches = select_next_state
8292 .query
8293 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8294
8295 for query_match in query_matches {
8296 let query_match = query_match.unwrap(); // can only fail due to I/O
8297 let offset_range = query_match.start()..query_match.end();
8298 let display_range = offset_range.start.to_display_point(&display_map)
8299 ..offset_range.end.to_display_point(&display_map);
8300
8301 if !select_next_state.wordwise
8302 || (!movement::is_inside_word(&display_map, display_range.start)
8303 && !movement::is_inside_word(&display_map, display_range.end))
8304 {
8305 self.selections.change_with(cx, |selections| {
8306 new_selections.push(Selection {
8307 id: selections.new_selection_id(),
8308 start: offset_range.start,
8309 end: offset_range.end,
8310 reversed: false,
8311 goal: SelectionGoal::None,
8312 });
8313 });
8314 }
8315 }
8316
8317 new_selections.sort_by_key(|selection| selection.start);
8318 let mut ix = 0;
8319 while ix + 1 < new_selections.len() {
8320 let current_selection = &new_selections[ix];
8321 let next_selection = &new_selections[ix + 1];
8322 if current_selection.range().overlaps(&next_selection.range()) {
8323 if current_selection.id < next_selection.id {
8324 new_selections.remove(ix + 1);
8325 } else {
8326 new_selections.remove(ix);
8327 }
8328 } else {
8329 ix += 1;
8330 }
8331 }
8332
8333 select_next_state.done = true;
8334 self.unfold_ranges(
8335 new_selections.iter().map(|selection| selection.range()),
8336 false,
8337 false,
8338 cx,
8339 );
8340 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8341 selections.select(new_selections)
8342 });
8343
8344 Ok(())
8345 }
8346
8347 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8348 self.push_to_selection_history();
8349 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8350 self.select_next_match_internal(
8351 &display_map,
8352 action.replace_newest,
8353 Some(Autoscroll::newest()),
8354 cx,
8355 )?;
8356 Ok(())
8357 }
8358
8359 pub fn select_previous(
8360 &mut self,
8361 action: &SelectPrevious,
8362 cx: &mut ViewContext<Self>,
8363 ) -> Result<()> {
8364 self.push_to_selection_history();
8365 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8366 let buffer = &display_map.buffer_snapshot;
8367 let mut selections = self.selections.all::<usize>(cx);
8368 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8369 let query = &select_prev_state.query;
8370 if !select_prev_state.done {
8371 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8372 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8373 let mut next_selected_range = None;
8374 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8375 let bytes_before_last_selection =
8376 buffer.reversed_bytes_in_range(0..last_selection.start);
8377 let bytes_after_first_selection =
8378 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8379 let query_matches = query
8380 .stream_find_iter(bytes_before_last_selection)
8381 .map(|result| (last_selection.start, result))
8382 .chain(
8383 query
8384 .stream_find_iter(bytes_after_first_selection)
8385 .map(|result| (buffer.len(), result)),
8386 );
8387 for (end_offset, query_match) in query_matches {
8388 let query_match = query_match.unwrap(); // can only fail due to I/O
8389 let offset_range =
8390 end_offset - query_match.end()..end_offset - query_match.start();
8391 let display_range = offset_range.start.to_display_point(&display_map)
8392 ..offset_range.end.to_display_point(&display_map);
8393
8394 if !select_prev_state.wordwise
8395 || (!movement::is_inside_word(&display_map, display_range.start)
8396 && !movement::is_inside_word(&display_map, display_range.end))
8397 {
8398 next_selected_range = Some(offset_range);
8399 break;
8400 }
8401 }
8402
8403 if let Some(next_selected_range) = next_selected_range {
8404 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8405 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8406 if action.replace_newest {
8407 s.delete(s.newest_anchor().id);
8408 }
8409 s.insert_range(next_selected_range);
8410 });
8411 } else {
8412 select_prev_state.done = true;
8413 }
8414 }
8415
8416 self.select_prev_state = Some(select_prev_state);
8417 } else {
8418 let mut only_carets = true;
8419 let mut same_text_selected = true;
8420 let mut selected_text = None;
8421
8422 let mut selections_iter = selections.iter().peekable();
8423 while let Some(selection) = selections_iter.next() {
8424 if selection.start != selection.end {
8425 only_carets = false;
8426 }
8427
8428 if same_text_selected {
8429 if selected_text.is_none() {
8430 selected_text =
8431 Some(buffer.text_for_range(selection.range()).collect::<String>());
8432 }
8433
8434 if let Some(next_selection) = selections_iter.peek() {
8435 if next_selection.range().len() == selection.range().len() {
8436 let next_selected_text = buffer
8437 .text_for_range(next_selection.range())
8438 .collect::<String>();
8439 if Some(next_selected_text) != selected_text {
8440 same_text_selected = false;
8441 selected_text = None;
8442 }
8443 } else {
8444 same_text_selected = false;
8445 selected_text = None;
8446 }
8447 }
8448 }
8449 }
8450
8451 if only_carets {
8452 for selection in &mut selections {
8453 let word_range = movement::surrounding_word(
8454 &display_map,
8455 selection.start.to_display_point(&display_map),
8456 );
8457 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8458 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8459 selection.goal = SelectionGoal::None;
8460 selection.reversed = false;
8461 }
8462 if selections.len() == 1 {
8463 let selection = selections
8464 .last()
8465 .expect("ensured that there's only one selection");
8466 let query = buffer
8467 .text_for_range(selection.start..selection.end)
8468 .collect::<String>();
8469 let is_empty = query.is_empty();
8470 let select_state = SelectNextState {
8471 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8472 wordwise: true,
8473 done: is_empty,
8474 };
8475 self.select_prev_state = Some(select_state);
8476 } else {
8477 self.select_prev_state = None;
8478 }
8479
8480 self.unfold_ranges(
8481 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8482 false,
8483 true,
8484 cx,
8485 );
8486 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8487 s.select(selections);
8488 });
8489 } else if let Some(selected_text) = selected_text {
8490 self.select_prev_state = Some(SelectNextState {
8491 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8492 wordwise: false,
8493 done: false,
8494 });
8495 self.select_previous(action, cx)?;
8496 }
8497 }
8498 Ok(())
8499 }
8500
8501 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8502 let text_layout_details = &self.text_layout_details(cx);
8503 self.transact(cx, |this, cx| {
8504 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8505 let mut edits = Vec::new();
8506 let mut selection_edit_ranges = Vec::new();
8507 let mut last_toggled_row = None;
8508 let snapshot = this.buffer.read(cx).read(cx);
8509 let empty_str: Arc<str> = Arc::default();
8510 let mut suffixes_inserted = Vec::new();
8511
8512 fn comment_prefix_range(
8513 snapshot: &MultiBufferSnapshot,
8514 row: MultiBufferRow,
8515 comment_prefix: &str,
8516 comment_prefix_whitespace: &str,
8517 ) -> Range<Point> {
8518 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8519
8520 let mut line_bytes = snapshot
8521 .bytes_in_range(start..snapshot.max_point())
8522 .flatten()
8523 .copied();
8524
8525 // If this line currently begins with the line comment prefix, then record
8526 // the range containing the prefix.
8527 if line_bytes
8528 .by_ref()
8529 .take(comment_prefix.len())
8530 .eq(comment_prefix.bytes())
8531 {
8532 // Include any whitespace that matches the comment prefix.
8533 let matching_whitespace_len = line_bytes
8534 .zip(comment_prefix_whitespace.bytes())
8535 .take_while(|(a, b)| a == b)
8536 .count() as u32;
8537 let end = Point::new(
8538 start.row,
8539 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8540 );
8541 start..end
8542 } else {
8543 start..start
8544 }
8545 }
8546
8547 fn comment_suffix_range(
8548 snapshot: &MultiBufferSnapshot,
8549 row: MultiBufferRow,
8550 comment_suffix: &str,
8551 comment_suffix_has_leading_space: bool,
8552 ) -> Range<Point> {
8553 let end = Point::new(row.0, snapshot.line_len(row));
8554 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8555
8556 let mut line_end_bytes = snapshot
8557 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8558 .flatten()
8559 .copied();
8560
8561 let leading_space_len = if suffix_start_column > 0
8562 && line_end_bytes.next() == Some(b' ')
8563 && comment_suffix_has_leading_space
8564 {
8565 1
8566 } else {
8567 0
8568 };
8569
8570 // If this line currently begins with the line comment prefix, then record
8571 // the range containing the prefix.
8572 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8573 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8574 start..end
8575 } else {
8576 end..end
8577 }
8578 }
8579
8580 // TODO: Handle selections that cross excerpts
8581 for selection in &mut selections {
8582 let start_column = snapshot
8583 .indent_size_for_line(MultiBufferRow(selection.start.row))
8584 .len;
8585 let language = if let Some(language) =
8586 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8587 {
8588 language
8589 } else {
8590 continue;
8591 };
8592
8593 selection_edit_ranges.clear();
8594
8595 // If multiple selections contain a given row, avoid processing that
8596 // row more than once.
8597 let mut start_row = MultiBufferRow(selection.start.row);
8598 if last_toggled_row == Some(start_row) {
8599 start_row = start_row.next_row();
8600 }
8601 let end_row =
8602 if selection.end.row > selection.start.row && selection.end.column == 0 {
8603 MultiBufferRow(selection.end.row - 1)
8604 } else {
8605 MultiBufferRow(selection.end.row)
8606 };
8607 last_toggled_row = Some(end_row);
8608
8609 if start_row > end_row {
8610 continue;
8611 }
8612
8613 // If the language has line comments, toggle those.
8614 let full_comment_prefixes = language.line_comment_prefixes();
8615 if !full_comment_prefixes.is_empty() {
8616 let first_prefix = full_comment_prefixes
8617 .first()
8618 .expect("prefixes is non-empty");
8619 let prefix_trimmed_lengths = full_comment_prefixes
8620 .iter()
8621 .map(|p| p.trim_end_matches(' ').len())
8622 .collect::<SmallVec<[usize; 4]>>();
8623
8624 let mut all_selection_lines_are_comments = true;
8625
8626 for row in start_row.0..=end_row.0 {
8627 let row = MultiBufferRow(row);
8628 if start_row < end_row && snapshot.is_line_blank(row) {
8629 continue;
8630 }
8631
8632 let prefix_range = full_comment_prefixes
8633 .iter()
8634 .zip(prefix_trimmed_lengths.iter().copied())
8635 .map(|(prefix, trimmed_prefix_len)| {
8636 comment_prefix_range(
8637 snapshot.deref(),
8638 row,
8639 &prefix[..trimmed_prefix_len],
8640 &prefix[trimmed_prefix_len..],
8641 )
8642 })
8643 .max_by_key(|range| range.end.column - range.start.column)
8644 .expect("prefixes is non-empty");
8645
8646 if prefix_range.is_empty() {
8647 all_selection_lines_are_comments = false;
8648 }
8649
8650 selection_edit_ranges.push(prefix_range);
8651 }
8652
8653 if all_selection_lines_are_comments {
8654 edits.extend(
8655 selection_edit_ranges
8656 .iter()
8657 .cloned()
8658 .map(|range| (range, empty_str.clone())),
8659 );
8660 } else {
8661 let min_column = selection_edit_ranges
8662 .iter()
8663 .map(|range| range.start.column)
8664 .min()
8665 .unwrap_or(0);
8666 edits.extend(selection_edit_ranges.iter().map(|range| {
8667 let position = Point::new(range.start.row, min_column);
8668 (position..position, first_prefix.clone())
8669 }));
8670 }
8671 } else if let Some((full_comment_prefix, comment_suffix)) =
8672 language.block_comment_delimiters()
8673 {
8674 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8675 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8676 let prefix_range = comment_prefix_range(
8677 snapshot.deref(),
8678 start_row,
8679 comment_prefix,
8680 comment_prefix_whitespace,
8681 );
8682 let suffix_range = comment_suffix_range(
8683 snapshot.deref(),
8684 end_row,
8685 comment_suffix.trim_start_matches(' '),
8686 comment_suffix.starts_with(' '),
8687 );
8688
8689 if prefix_range.is_empty() || suffix_range.is_empty() {
8690 edits.push((
8691 prefix_range.start..prefix_range.start,
8692 full_comment_prefix.clone(),
8693 ));
8694 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8695 suffixes_inserted.push((end_row, comment_suffix.len()));
8696 } else {
8697 edits.push((prefix_range, empty_str.clone()));
8698 edits.push((suffix_range, empty_str.clone()));
8699 }
8700 } else {
8701 continue;
8702 }
8703 }
8704
8705 drop(snapshot);
8706 this.buffer.update(cx, |buffer, cx| {
8707 buffer.edit(edits, None, cx);
8708 });
8709
8710 // Adjust selections so that they end before any comment suffixes that
8711 // were inserted.
8712 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8713 let mut selections = this.selections.all::<Point>(cx);
8714 let snapshot = this.buffer.read(cx).read(cx);
8715 for selection in &mut selections {
8716 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8717 match row.cmp(&MultiBufferRow(selection.end.row)) {
8718 Ordering::Less => {
8719 suffixes_inserted.next();
8720 continue;
8721 }
8722 Ordering::Greater => break,
8723 Ordering::Equal => {
8724 if selection.end.column == snapshot.line_len(row) {
8725 if selection.is_empty() {
8726 selection.start.column -= suffix_len as u32;
8727 }
8728 selection.end.column -= suffix_len as u32;
8729 }
8730 break;
8731 }
8732 }
8733 }
8734 }
8735
8736 drop(snapshot);
8737 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8738
8739 let selections = this.selections.all::<Point>(cx);
8740 let selections_on_single_row = selections.windows(2).all(|selections| {
8741 selections[0].start.row == selections[1].start.row
8742 && selections[0].end.row == selections[1].end.row
8743 && selections[0].start.row == selections[0].end.row
8744 });
8745 let selections_selecting = selections
8746 .iter()
8747 .any(|selection| selection.start != selection.end);
8748 let advance_downwards = action.advance_downwards
8749 && selections_on_single_row
8750 && !selections_selecting
8751 && !matches!(this.mode, EditorMode::SingleLine { .. });
8752
8753 if advance_downwards {
8754 let snapshot = this.buffer.read(cx).snapshot(cx);
8755
8756 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8757 s.move_cursors_with(|display_snapshot, display_point, _| {
8758 let mut point = display_point.to_point(display_snapshot);
8759 point.row += 1;
8760 point = snapshot.clip_point(point, Bias::Left);
8761 let display_point = point.to_display_point(display_snapshot);
8762 let goal = SelectionGoal::HorizontalPosition(
8763 display_snapshot
8764 .x_for_display_point(display_point, text_layout_details)
8765 .into(),
8766 );
8767 (display_point, goal)
8768 })
8769 });
8770 }
8771 });
8772 }
8773
8774 pub fn select_enclosing_symbol(
8775 &mut self,
8776 _: &SelectEnclosingSymbol,
8777 cx: &mut ViewContext<Self>,
8778 ) {
8779 let buffer = self.buffer.read(cx).snapshot(cx);
8780 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8781
8782 fn update_selection(
8783 selection: &Selection<usize>,
8784 buffer_snap: &MultiBufferSnapshot,
8785 ) -> Option<Selection<usize>> {
8786 let cursor = selection.head();
8787 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8788 for symbol in symbols.iter().rev() {
8789 let start = symbol.range.start.to_offset(buffer_snap);
8790 let end = symbol.range.end.to_offset(buffer_snap);
8791 let new_range = start..end;
8792 if start < selection.start || end > selection.end {
8793 return Some(Selection {
8794 id: selection.id,
8795 start: new_range.start,
8796 end: new_range.end,
8797 goal: SelectionGoal::None,
8798 reversed: selection.reversed,
8799 });
8800 }
8801 }
8802 None
8803 }
8804
8805 let mut selected_larger_symbol = false;
8806 let new_selections = old_selections
8807 .iter()
8808 .map(|selection| match update_selection(selection, &buffer) {
8809 Some(new_selection) => {
8810 if new_selection.range() != selection.range() {
8811 selected_larger_symbol = true;
8812 }
8813 new_selection
8814 }
8815 None => selection.clone(),
8816 })
8817 .collect::<Vec<_>>();
8818
8819 if selected_larger_symbol {
8820 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8821 s.select(new_selections);
8822 });
8823 }
8824 }
8825
8826 pub fn select_larger_syntax_node(
8827 &mut self,
8828 _: &SelectLargerSyntaxNode,
8829 cx: &mut ViewContext<Self>,
8830 ) {
8831 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8832 let buffer = self.buffer.read(cx).snapshot(cx);
8833 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8834
8835 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8836 let mut selected_larger_node = false;
8837 let new_selections = old_selections
8838 .iter()
8839 .map(|selection| {
8840 let old_range = selection.start..selection.end;
8841 let mut new_range = old_range.clone();
8842 while let Some(containing_range) =
8843 buffer.range_for_syntax_ancestor(new_range.clone())
8844 {
8845 new_range = containing_range;
8846 if !display_map.intersects_fold(new_range.start)
8847 && !display_map.intersects_fold(new_range.end)
8848 {
8849 break;
8850 }
8851 }
8852
8853 selected_larger_node |= new_range != old_range;
8854 Selection {
8855 id: selection.id,
8856 start: new_range.start,
8857 end: new_range.end,
8858 goal: SelectionGoal::None,
8859 reversed: selection.reversed,
8860 }
8861 })
8862 .collect::<Vec<_>>();
8863
8864 if selected_larger_node {
8865 stack.push(old_selections);
8866 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8867 s.select(new_selections);
8868 });
8869 }
8870 self.select_larger_syntax_node_stack = stack;
8871 }
8872
8873 pub fn select_smaller_syntax_node(
8874 &mut self,
8875 _: &SelectSmallerSyntaxNode,
8876 cx: &mut ViewContext<Self>,
8877 ) {
8878 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8879 if let Some(selections) = stack.pop() {
8880 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8881 s.select(selections.to_vec());
8882 });
8883 }
8884 self.select_larger_syntax_node_stack = stack;
8885 }
8886
8887 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8888 if !EditorSettings::get_global(cx).gutter.runnables {
8889 self.clear_tasks();
8890 return Task::ready(());
8891 }
8892 let project = self.project.clone();
8893 cx.spawn(|this, mut cx| async move {
8894 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8895 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8896 }) else {
8897 return;
8898 };
8899
8900 let Some(project) = project else {
8901 return;
8902 };
8903
8904 let hide_runnables = project
8905 .update(&mut cx, |project, cx| {
8906 // Do not display any test indicators in non-dev server remote projects.
8907 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8908 })
8909 .unwrap_or(true);
8910 if hide_runnables {
8911 return;
8912 }
8913 let new_rows =
8914 cx.background_executor()
8915 .spawn({
8916 let snapshot = display_snapshot.clone();
8917 async move {
8918 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8919 }
8920 })
8921 .await;
8922 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8923
8924 this.update(&mut cx, |this, _| {
8925 this.clear_tasks();
8926 for (key, value) in rows {
8927 this.insert_tasks(key, value);
8928 }
8929 })
8930 .ok();
8931 })
8932 }
8933 fn fetch_runnable_ranges(
8934 snapshot: &DisplaySnapshot,
8935 range: Range<Anchor>,
8936 ) -> Vec<language::RunnableRange> {
8937 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8938 }
8939
8940 fn runnable_rows(
8941 project: Model<Project>,
8942 snapshot: DisplaySnapshot,
8943 runnable_ranges: Vec<RunnableRange>,
8944 mut cx: AsyncWindowContext,
8945 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8946 runnable_ranges
8947 .into_iter()
8948 .filter_map(|mut runnable| {
8949 let tasks = cx
8950 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8951 .ok()?;
8952 if tasks.is_empty() {
8953 return None;
8954 }
8955
8956 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8957
8958 let row = snapshot
8959 .buffer_snapshot
8960 .buffer_line_for_row(MultiBufferRow(point.row))?
8961 .1
8962 .start
8963 .row;
8964
8965 let context_range =
8966 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8967 Some((
8968 (runnable.buffer_id, row),
8969 RunnableTasks {
8970 templates: tasks,
8971 offset: MultiBufferOffset(runnable.run_range.start),
8972 context_range,
8973 column: point.column,
8974 extra_variables: runnable.extra_captures,
8975 },
8976 ))
8977 })
8978 .collect()
8979 }
8980
8981 fn templates_with_tags(
8982 project: &Model<Project>,
8983 runnable: &mut Runnable,
8984 cx: &WindowContext<'_>,
8985 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8986 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8987 let (worktree_id, file) = project
8988 .buffer_for_id(runnable.buffer, cx)
8989 .and_then(|buffer| buffer.read(cx).file())
8990 .map(|file| (file.worktree_id(cx), file.clone()))
8991 .unzip();
8992
8993 (project.task_inventory().clone(), worktree_id, file)
8994 });
8995
8996 let inventory = inventory.read(cx);
8997 let tags = mem::take(&mut runnable.tags);
8998 let mut tags: Vec<_> = tags
8999 .into_iter()
9000 .flat_map(|tag| {
9001 let tag = tag.0.clone();
9002 inventory
9003 .list_tasks(
9004 file.clone(),
9005 Some(runnable.language.clone()),
9006 worktree_id,
9007 cx,
9008 )
9009 .into_iter()
9010 .filter(move |(_, template)| {
9011 template.tags.iter().any(|source_tag| source_tag == &tag)
9012 })
9013 })
9014 .sorted_by_key(|(kind, _)| kind.to_owned())
9015 .collect();
9016 if let Some((leading_tag_source, _)) = tags.first() {
9017 // Strongest source wins; if we have worktree tag binding, prefer that to
9018 // global and language bindings;
9019 // if we have a global binding, prefer that to language binding.
9020 let first_mismatch = tags
9021 .iter()
9022 .position(|(tag_source, _)| tag_source != leading_tag_source);
9023 if let Some(index) = first_mismatch {
9024 tags.truncate(index);
9025 }
9026 }
9027
9028 tags
9029 }
9030
9031 pub fn move_to_enclosing_bracket(
9032 &mut self,
9033 _: &MoveToEnclosingBracket,
9034 cx: &mut ViewContext<Self>,
9035 ) {
9036 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9037 s.move_offsets_with(|snapshot, selection| {
9038 let Some(enclosing_bracket_ranges) =
9039 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9040 else {
9041 return;
9042 };
9043
9044 let mut best_length = usize::MAX;
9045 let mut best_inside = false;
9046 let mut best_in_bracket_range = false;
9047 let mut best_destination = None;
9048 for (open, close) in enclosing_bracket_ranges {
9049 let close = close.to_inclusive();
9050 let length = close.end() - open.start;
9051 let inside = selection.start >= open.end && selection.end <= *close.start();
9052 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9053 || close.contains(&selection.head());
9054
9055 // If best is next to a bracket and current isn't, skip
9056 if !in_bracket_range && best_in_bracket_range {
9057 continue;
9058 }
9059
9060 // Prefer smaller lengths unless best is inside and current isn't
9061 if length > best_length && (best_inside || !inside) {
9062 continue;
9063 }
9064
9065 best_length = length;
9066 best_inside = inside;
9067 best_in_bracket_range = in_bracket_range;
9068 best_destination = Some(
9069 if close.contains(&selection.start) && close.contains(&selection.end) {
9070 if inside {
9071 open.end
9072 } else {
9073 open.start
9074 }
9075 } else if inside {
9076 *close.start()
9077 } else {
9078 *close.end()
9079 },
9080 );
9081 }
9082
9083 if let Some(destination) = best_destination {
9084 selection.collapse_to(destination, SelectionGoal::None);
9085 }
9086 })
9087 });
9088 }
9089
9090 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9091 self.end_selection(cx);
9092 self.selection_history.mode = SelectionHistoryMode::Undoing;
9093 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9094 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9095 self.select_next_state = entry.select_next_state;
9096 self.select_prev_state = entry.select_prev_state;
9097 self.add_selections_state = entry.add_selections_state;
9098 self.request_autoscroll(Autoscroll::newest(), cx);
9099 }
9100 self.selection_history.mode = SelectionHistoryMode::Normal;
9101 }
9102
9103 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9104 self.end_selection(cx);
9105 self.selection_history.mode = SelectionHistoryMode::Redoing;
9106 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9107 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9108 self.select_next_state = entry.select_next_state;
9109 self.select_prev_state = entry.select_prev_state;
9110 self.add_selections_state = entry.add_selections_state;
9111 self.request_autoscroll(Autoscroll::newest(), cx);
9112 }
9113 self.selection_history.mode = SelectionHistoryMode::Normal;
9114 }
9115
9116 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9117 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9118 }
9119
9120 pub fn expand_excerpts_down(
9121 &mut self,
9122 action: &ExpandExcerptsDown,
9123 cx: &mut ViewContext<Self>,
9124 ) {
9125 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9126 }
9127
9128 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9129 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9130 }
9131
9132 pub fn expand_excerpts_for_direction(
9133 &mut self,
9134 lines: u32,
9135 direction: ExpandExcerptDirection,
9136 cx: &mut ViewContext<Self>,
9137 ) {
9138 let selections = self.selections.disjoint_anchors();
9139
9140 let lines = if lines == 0 {
9141 EditorSettings::get_global(cx).expand_excerpt_lines
9142 } else {
9143 lines
9144 };
9145
9146 self.buffer.update(cx, |buffer, cx| {
9147 buffer.expand_excerpts(
9148 selections
9149 .iter()
9150 .map(|selection| selection.head().excerpt_id)
9151 .dedup(),
9152 lines,
9153 direction,
9154 cx,
9155 )
9156 })
9157 }
9158
9159 pub fn expand_excerpt(
9160 &mut self,
9161 excerpt: ExcerptId,
9162 direction: ExpandExcerptDirection,
9163 cx: &mut ViewContext<Self>,
9164 ) {
9165 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9166 self.buffer.update(cx, |buffer, cx| {
9167 buffer.expand_excerpts([excerpt], lines, direction, cx)
9168 })
9169 }
9170
9171 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9172 self.go_to_diagnostic_impl(Direction::Next, cx)
9173 }
9174
9175 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9176 self.go_to_diagnostic_impl(Direction::Prev, cx)
9177 }
9178
9179 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9180 let buffer = self.buffer.read(cx).snapshot(cx);
9181 let selection = self.selections.newest::<usize>(cx);
9182
9183 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9184 if direction == Direction::Next {
9185 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9186 let (group_id, jump_to) = popover.activation_info();
9187 if self.activate_diagnostics(group_id, cx) {
9188 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9189 let mut new_selection = s.newest_anchor().clone();
9190 new_selection.collapse_to(jump_to, SelectionGoal::None);
9191 s.select_anchors(vec![new_selection.clone()]);
9192 });
9193 }
9194 return;
9195 }
9196 }
9197
9198 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9199 active_diagnostics
9200 .primary_range
9201 .to_offset(&buffer)
9202 .to_inclusive()
9203 });
9204 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9205 if active_primary_range.contains(&selection.head()) {
9206 *active_primary_range.start()
9207 } else {
9208 selection.head()
9209 }
9210 } else {
9211 selection.head()
9212 };
9213 let snapshot = self.snapshot(cx);
9214 loop {
9215 let diagnostics = if direction == Direction::Prev {
9216 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9217 } else {
9218 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9219 }
9220 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9221 let group = diagnostics
9222 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9223 // be sorted in a stable way
9224 // skip until we are at current active diagnostic, if it exists
9225 .skip_while(|entry| {
9226 (match direction {
9227 Direction::Prev => entry.range.start >= search_start,
9228 Direction::Next => entry.range.start <= search_start,
9229 }) && self
9230 .active_diagnostics
9231 .as_ref()
9232 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9233 })
9234 .find_map(|entry| {
9235 if entry.diagnostic.is_primary
9236 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9237 && !entry.range.is_empty()
9238 // if we match with the active diagnostic, skip it
9239 && Some(entry.diagnostic.group_id)
9240 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9241 {
9242 Some((entry.range, entry.diagnostic.group_id))
9243 } else {
9244 None
9245 }
9246 });
9247
9248 if let Some((primary_range, group_id)) = group {
9249 if self.activate_diagnostics(group_id, cx) {
9250 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9251 s.select(vec![Selection {
9252 id: selection.id,
9253 start: primary_range.start,
9254 end: primary_range.start,
9255 reversed: false,
9256 goal: SelectionGoal::None,
9257 }]);
9258 });
9259 }
9260 break;
9261 } else {
9262 // Cycle around to the start of the buffer, potentially moving back to the start of
9263 // the currently active diagnostic.
9264 active_primary_range.take();
9265 if direction == Direction::Prev {
9266 if search_start == buffer.len() {
9267 break;
9268 } else {
9269 search_start = buffer.len();
9270 }
9271 } else if search_start == 0 {
9272 break;
9273 } else {
9274 search_start = 0;
9275 }
9276 }
9277 }
9278 }
9279
9280 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9281 let snapshot = self
9282 .display_map
9283 .update(cx, |display_map, cx| display_map.snapshot(cx));
9284 let selection = self.selections.newest::<Point>(cx);
9285
9286 if !self.seek_in_direction(
9287 &snapshot,
9288 selection.head(),
9289 false,
9290 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9291 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
9292 ),
9293 cx,
9294 ) {
9295 let wrapped_point = Point::zero();
9296 self.seek_in_direction(
9297 &snapshot,
9298 wrapped_point,
9299 true,
9300 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9301 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9302 ),
9303 cx,
9304 );
9305 }
9306 }
9307
9308 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9309 let snapshot = self
9310 .display_map
9311 .update(cx, |display_map, cx| display_map.snapshot(cx));
9312 let selection = self.selections.newest::<Point>(cx);
9313
9314 if !self.seek_in_direction(
9315 &snapshot,
9316 selection.head(),
9317 false,
9318 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9319 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
9320 ),
9321 cx,
9322 ) {
9323 let wrapped_point = snapshot.buffer_snapshot.max_point();
9324 self.seek_in_direction(
9325 &snapshot,
9326 wrapped_point,
9327 true,
9328 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9329 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9330 ),
9331 cx,
9332 );
9333 }
9334 }
9335
9336 fn seek_in_direction(
9337 &mut self,
9338 snapshot: &DisplaySnapshot,
9339 initial_point: Point,
9340 is_wrapped: bool,
9341 hunks: impl Iterator<Item = DiffHunk<MultiBufferRow>>,
9342 cx: &mut ViewContext<Editor>,
9343 ) -> bool {
9344 let display_point = initial_point.to_display_point(snapshot);
9345 let mut hunks = hunks
9346 .map(|hunk| diff_hunk_to_display(&hunk, snapshot))
9347 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9348 .dedup();
9349
9350 if let Some(hunk) = hunks.next() {
9351 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9352 let row = hunk.start_display_row();
9353 let point = DisplayPoint::new(row, 0);
9354 s.select_display_ranges([point..point]);
9355 });
9356
9357 true
9358 } else {
9359 false
9360 }
9361 }
9362
9363 pub fn go_to_definition(
9364 &mut self,
9365 _: &GoToDefinition,
9366 cx: &mut ViewContext<Self>,
9367 ) -> Task<Result<Navigated>> {
9368 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9369 cx.spawn(|editor, mut cx| async move {
9370 if definition.await? == Navigated::Yes {
9371 return Ok(Navigated::Yes);
9372 }
9373 match editor.update(&mut cx, |editor, cx| {
9374 editor.find_all_references(&FindAllReferences, cx)
9375 })? {
9376 Some(references) => references.await,
9377 None => Ok(Navigated::No),
9378 }
9379 })
9380 }
9381
9382 pub fn go_to_declaration(
9383 &mut self,
9384 _: &GoToDeclaration,
9385 cx: &mut ViewContext<Self>,
9386 ) -> Task<Result<Navigated>> {
9387 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9388 }
9389
9390 pub fn go_to_declaration_split(
9391 &mut self,
9392 _: &GoToDeclaration,
9393 cx: &mut ViewContext<Self>,
9394 ) -> Task<Result<Navigated>> {
9395 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9396 }
9397
9398 pub fn go_to_implementation(
9399 &mut self,
9400 _: &GoToImplementation,
9401 cx: &mut ViewContext<Self>,
9402 ) -> Task<Result<Navigated>> {
9403 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9404 }
9405
9406 pub fn go_to_implementation_split(
9407 &mut self,
9408 _: &GoToImplementationSplit,
9409 cx: &mut ViewContext<Self>,
9410 ) -> Task<Result<Navigated>> {
9411 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9412 }
9413
9414 pub fn go_to_type_definition(
9415 &mut self,
9416 _: &GoToTypeDefinition,
9417 cx: &mut ViewContext<Self>,
9418 ) -> Task<Result<Navigated>> {
9419 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9420 }
9421
9422 pub fn go_to_definition_split(
9423 &mut self,
9424 _: &GoToDefinitionSplit,
9425 cx: &mut ViewContext<Self>,
9426 ) -> Task<Result<Navigated>> {
9427 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9428 }
9429
9430 pub fn go_to_type_definition_split(
9431 &mut self,
9432 _: &GoToTypeDefinitionSplit,
9433 cx: &mut ViewContext<Self>,
9434 ) -> Task<Result<Navigated>> {
9435 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9436 }
9437
9438 fn go_to_definition_of_kind(
9439 &mut self,
9440 kind: GotoDefinitionKind,
9441 split: bool,
9442 cx: &mut ViewContext<Self>,
9443 ) -> Task<Result<Navigated>> {
9444 let Some(workspace) = self.workspace() else {
9445 return Task::ready(Ok(Navigated::No));
9446 };
9447 let buffer = self.buffer.read(cx);
9448 let head = self.selections.newest::<usize>(cx).head();
9449 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9450 text_anchor
9451 } else {
9452 return Task::ready(Ok(Navigated::No));
9453 };
9454
9455 let project = workspace.read(cx).project().clone();
9456 let definitions = project.update(cx, |project, cx| match kind {
9457 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9458 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9459 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9460 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9461 });
9462
9463 cx.spawn(|editor, mut cx| async move {
9464 let definitions = definitions.await?;
9465 let navigated = editor
9466 .update(&mut cx, |editor, cx| {
9467 editor.navigate_to_hover_links(
9468 Some(kind),
9469 definitions
9470 .into_iter()
9471 .filter(|location| {
9472 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9473 })
9474 .map(HoverLink::Text)
9475 .collect::<Vec<_>>(),
9476 split,
9477 cx,
9478 )
9479 })?
9480 .await?;
9481 anyhow::Ok(navigated)
9482 })
9483 }
9484
9485 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9486 let position = self.selections.newest_anchor().head();
9487 let Some((buffer, buffer_position)) =
9488 self.buffer.read(cx).text_anchor_for_position(position, cx)
9489 else {
9490 return;
9491 };
9492
9493 cx.spawn(|editor, mut cx| async move {
9494 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9495 editor.update(&mut cx, |_, cx| {
9496 cx.open_url(&url);
9497 })
9498 } else {
9499 Ok(())
9500 }
9501 })
9502 .detach();
9503 }
9504
9505 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9506 let Some(workspace) = self.workspace() else {
9507 return;
9508 };
9509
9510 let position = self.selections.newest_anchor().head();
9511
9512 let Some((buffer, buffer_position)) =
9513 self.buffer.read(cx).text_anchor_for_position(position, cx)
9514 else {
9515 return;
9516 };
9517
9518 let Some(project) = self.project.clone() else {
9519 return;
9520 };
9521
9522 cx.spawn(|_, mut cx| async move {
9523 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9524
9525 if let Some((_, path)) = result {
9526 workspace
9527 .update(&mut cx, |workspace, cx| {
9528 workspace.open_resolved_path(path, cx)
9529 })?
9530 .await?;
9531 }
9532 anyhow::Ok(())
9533 })
9534 .detach();
9535 }
9536
9537 pub(crate) fn navigate_to_hover_links(
9538 &mut self,
9539 kind: Option<GotoDefinitionKind>,
9540 mut definitions: Vec<HoverLink>,
9541 split: bool,
9542 cx: &mut ViewContext<Editor>,
9543 ) -> Task<Result<Navigated>> {
9544 // If there is one definition, just open it directly
9545 if definitions.len() == 1 {
9546 let definition = definitions.pop().unwrap();
9547
9548 enum TargetTaskResult {
9549 Location(Option<Location>),
9550 AlreadyNavigated,
9551 }
9552
9553 let target_task = match definition {
9554 HoverLink::Text(link) => {
9555 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9556 }
9557 HoverLink::InlayHint(lsp_location, server_id) => {
9558 let computation = self.compute_target_location(lsp_location, server_id, cx);
9559 cx.background_executor().spawn(async move {
9560 let location = computation.await?;
9561 Ok(TargetTaskResult::Location(location))
9562 })
9563 }
9564 HoverLink::Url(url) => {
9565 cx.open_url(&url);
9566 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9567 }
9568 HoverLink::File(path) => {
9569 if let Some(workspace) = self.workspace() {
9570 cx.spawn(|_, mut cx| async move {
9571 workspace
9572 .update(&mut cx, |workspace, cx| {
9573 workspace.open_resolved_path(path, cx)
9574 })?
9575 .await
9576 .map(|_| TargetTaskResult::AlreadyNavigated)
9577 })
9578 } else {
9579 Task::ready(Ok(TargetTaskResult::Location(None)))
9580 }
9581 }
9582 };
9583 cx.spawn(|editor, mut cx| async move {
9584 let target = match target_task.await.context("target resolution task")? {
9585 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9586 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9587 TargetTaskResult::Location(Some(target)) => target,
9588 };
9589
9590 editor.update(&mut cx, |editor, cx| {
9591 let Some(workspace) = editor.workspace() else {
9592 return Navigated::No;
9593 };
9594 let pane = workspace.read(cx).active_pane().clone();
9595
9596 let range = target.range.to_offset(target.buffer.read(cx));
9597 let range = editor.range_for_match(&range);
9598
9599 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9600 let buffer = target.buffer.read(cx);
9601 let range = check_multiline_range(buffer, range);
9602 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9603 s.select_ranges([range]);
9604 });
9605 } else {
9606 cx.window_context().defer(move |cx| {
9607 let target_editor: View<Self> =
9608 workspace.update(cx, |workspace, cx| {
9609 let pane = if split {
9610 workspace.adjacent_pane(cx)
9611 } else {
9612 workspace.active_pane().clone()
9613 };
9614
9615 workspace.open_project_item(
9616 pane,
9617 target.buffer.clone(),
9618 true,
9619 true,
9620 cx,
9621 )
9622 });
9623 target_editor.update(cx, |target_editor, cx| {
9624 // When selecting a definition in a different buffer, disable the nav history
9625 // to avoid creating a history entry at the previous cursor location.
9626 pane.update(cx, |pane, _| pane.disable_history());
9627 let buffer = target.buffer.read(cx);
9628 let range = check_multiline_range(buffer, range);
9629 target_editor.change_selections(
9630 Some(Autoscroll::focused()),
9631 cx,
9632 |s| {
9633 s.select_ranges([range]);
9634 },
9635 );
9636 pane.update(cx, |pane, _| pane.enable_history());
9637 });
9638 });
9639 }
9640 Navigated::Yes
9641 })
9642 })
9643 } else if !definitions.is_empty() {
9644 cx.spawn(|editor, mut cx| async move {
9645 let (title, location_tasks, workspace) = editor
9646 .update(&mut cx, |editor, cx| {
9647 let tab_kind = match kind {
9648 Some(GotoDefinitionKind::Implementation) => "Implementations",
9649 _ => "Definitions",
9650 };
9651 let title = definitions
9652 .iter()
9653 .find_map(|definition| match definition {
9654 HoverLink::Text(link) => link.origin.as_ref().map(|origin| {
9655 let buffer = origin.buffer.read(cx);
9656 format!(
9657 "{} for {}",
9658 tab_kind,
9659 buffer
9660 .text_for_range(origin.range.clone())
9661 .collect::<String>()
9662 )
9663 }),
9664 HoverLink::InlayHint(_, _) => None,
9665 HoverLink::Url(_) => None,
9666 HoverLink::File(_) => None,
9667 })
9668 .unwrap_or(tab_kind.to_string());
9669 let location_tasks = definitions
9670 .into_iter()
9671 .map(|definition| match definition {
9672 HoverLink::Text(link) => Task::Ready(Some(Ok(Some(link.target)))),
9673 HoverLink::InlayHint(lsp_location, server_id) => {
9674 editor.compute_target_location(lsp_location, server_id, cx)
9675 }
9676 HoverLink::Url(_) => Task::ready(Ok(None)),
9677 HoverLink::File(_) => Task::ready(Ok(None)),
9678 })
9679 .collect::<Vec<_>>();
9680 (title, location_tasks, editor.workspace().clone())
9681 })
9682 .context("location tasks preparation")?;
9683
9684 let locations = futures::future::join_all(location_tasks)
9685 .await
9686 .into_iter()
9687 .filter_map(|location| location.transpose())
9688 .collect::<Result<_>>()
9689 .context("location tasks")?;
9690
9691 let Some(workspace) = workspace else {
9692 return Ok(Navigated::No);
9693 };
9694 let opened = workspace
9695 .update(&mut cx, |workspace, cx| {
9696 Self::open_locations_in_multibuffer(workspace, locations, title, split, cx)
9697 })
9698 .ok();
9699
9700 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9701 })
9702 } else {
9703 Task::ready(Ok(Navigated::No))
9704 }
9705 }
9706
9707 fn compute_target_location(
9708 &self,
9709 lsp_location: lsp::Location,
9710 server_id: LanguageServerId,
9711 cx: &mut ViewContext<Editor>,
9712 ) -> Task<anyhow::Result<Option<Location>>> {
9713 let Some(project) = self.project.clone() else {
9714 return Task::Ready(Some(Ok(None)));
9715 };
9716
9717 cx.spawn(move |editor, mut cx| async move {
9718 let location_task = editor.update(&mut cx, |editor, cx| {
9719 project.update(cx, |project, cx| {
9720 let language_server_name =
9721 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9722 project
9723 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9724 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9725 });
9726 language_server_name.map(|language_server_name| {
9727 project.open_local_buffer_via_lsp(
9728 lsp_location.uri.clone(),
9729 server_id,
9730 language_server_name,
9731 cx,
9732 )
9733 })
9734 })
9735 })?;
9736 let location = match location_task {
9737 Some(task) => Some({
9738 let target_buffer_handle = task.await.context("open local buffer")?;
9739 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9740 let target_start = target_buffer
9741 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9742 let target_end = target_buffer
9743 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9744 target_buffer.anchor_after(target_start)
9745 ..target_buffer.anchor_before(target_end)
9746 })?;
9747 Location {
9748 buffer: target_buffer_handle,
9749 range,
9750 }
9751 }),
9752 None => None,
9753 };
9754 Ok(location)
9755 })
9756 }
9757
9758 pub fn find_all_references(
9759 &mut self,
9760 _: &FindAllReferences,
9761 cx: &mut ViewContext<Self>,
9762 ) -> Option<Task<Result<Navigated>>> {
9763 let multi_buffer = self.buffer.read(cx);
9764 let selection = self.selections.newest::<usize>(cx);
9765 let head = selection.head();
9766
9767 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9768 let head_anchor = multi_buffer_snapshot.anchor_at(
9769 head,
9770 if head < selection.tail() {
9771 Bias::Right
9772 } else {
9773 Bias::Left
9774 },
9775 );
9776
9777 match self
9778 .find_all_references_task_sources
9779 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9780 {
9781 Ok(_) => {
9782 log::info!(
9783 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9784 );
9785 return None;
9786 }
9787 Err(i) => {
9788 self.find_all_references_task_sources.insert(i, head_anchor);
9789 }
9790 }
9791
9792 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9793 let workspace = self.workspace()?;
9794 let project = workspace.read(cx).project().clone();
9795 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9796 Some(cx.spawn(|editor, mut cx| async move {
9797 let _cleanup = defer({
9798 let mut cx = cx.clone();
9799 move || {
9800 let _ = editor.update(&mut cx, |editor, _| {
9801 if let Ok(i) =
9802 editor
9803 .find_all_references_task_sources
9804 .binary_search_by(|anchor| {
9805 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9806 })
9807 {
9808 editor.find_all_references_task_sources.remove(i);
9809 }
9810 });
9811 }
9812 });
9813
9814 let locations = references.await?;
9815 if locations.is_empty() {
9816 return anyhow::Ok(Navigated::No);
9817 }
9818
9819 workspace.update(&mut cx, |workspace, cx| {
9820 let title = locations
9821 .first()
9822 .as_ref()
9823 .map(|location| {
9824 let buffer = location.buffer.read(cx);
9825 format!(
9826 "References to `{}`",
9827 buffer
9828 .text_for_range(location.range.clone())
9829 .collect::<String>()
9830 )
9831 })
9832 .unwrap();
9833 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9834 Navigated::Yes
9835 })
9836 }))
9837 }
9838
9839 /// Opens a multibuffer with the given project locations in it
9840 pub fn open_locations_in_multibuffer(
9841 workspace: &mut Workspace,
9842 mut locations: Vec<Location>,
9843 title: String,
9844 split: bool,
9845 cx: &mut ViewContext<Workspace>,
9846 ) {
9847 // If there are multiple definitions, open them in a multibuffer
9848 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9849 let mut locations = locations.into_iter().peekable();
9850 let mut ranges_to_highlight = Vec::new();
9851 let capability = workspace.project().read(cx).capability();
9852
9853 let excerpt_buffer = cx.new_model(|cx| {
9854 let mut multibuffer = MultiBuffer::new(capability);
9855 while let Some(location) = locations.next() {
9856 let buffer = location.buffer.read(cx);
9857 let mut ranges_for_buffer = Vec::new();
9858 let range = location.range.to_offset(buffer);
9859 ranges_for_buffer.push(range.clone());
9860
9861 while let Some(next_location) = locations.peek() {
9862 if next_location.buffer == location.buffer {
9863 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9864 locations.next();
9865 } else {
9866 break;
9867 }
9868 }
9869
9870 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9871 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9872 location.buffer.clone(),
9873 ranges_for_buffer,
9874 DEFAULT_MULTIBUFFER_CONTEXT,
9875 cx,
9876 ))
9877 }
9878
9879 multibuffer.with_title(title)
9880 });
9881
9882 let editor = cx.new_view(|cx| {
9883 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9884 });
9885 editor.update(cx, |editor, cx| {
9886 if let Some(first_range) = ranges_to_highlight.first() {
9887 editor.change_selections(None, cx, |selections| {
9888 selections.clear_disjoint();
9889 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9890 });
9891 }
9892 editor.highlight_background::<Self>(
9893 &ranges_to_highlight,
9894 |theme| theme.editor_highlighted_line_background,
9895 cx,
9896 );
9897 });
9898
9899 let item = Box::new(editor);
9900 let item_id = item.item_id();
9901
9902 if split {
9903 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9904 } else {
9905 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9906 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9907 pane.close_current_preview_item(cx)
9908 } else {
9909 None
9910 }
9911 });
9912 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9913 }
9914 workspace.active_pane().update(cx, |pane, cx| {
9915 pane.set_preview_item_id(Some(item_id), cx);
9916 });
9917 }
9918
9919 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9920 use language::ToOffset as _;
9921
9922 let project = self.project.clone()?;
9923 let selection = self.selections.newest_anchor().clone();
9924 let (cursor_buffer, cursor_buffer_position) = self
9925 .buffer
9926 .read(cx)
9927 .text_anchor_for_position(selection.head(), cx)?;
9928 let (tail_buffer, cursor_buffer_position_end) = self
9929 .buffer
9930 .read(cx)
9931 .text_anchor_for_position(selection.tail(), cx)?;
9932 if tail_buffer != cursor_buffer {
9933 return None;
9934 }
9935
9936 let snapshot = cursor_buffer.read(cx).snapshot();
9937 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9938 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9939 let prepare_rename = project.update(cx, |project, cx| {
9940 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9941 });
9942 drop(snapshot);
9943
9944 Some(cx.spawn(|this, mut cx| async move {
9945 let rename_range = if let Some(range) = prepare_rename.await? {
9946 Some(range)
9947 } else {
9948 this.update(&mut cx, |this, cx| {
9949 let buffer = this.buffer.read(cx).snapshot(cx);
9950 let mut buffer_highlights = this
9951 .document_highlights_for_position(selection.head(), &buffer)
9952 .filter(|highlight| {
9953 highlight.start.excerpt_id == selection.head().excerpt_id
9954 && highlight.end.excerpt_id == selection.head().excerpt_id
9955 });
9956 buffer_highlights
9957 .next()
9958 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9959 })?
9960 };
9961 if let Some(rename_range) = rename_range {
9962 this.update(&mut cx, |this, cx| {
9963 let snapshot = cursor_buffer.read(cx).snapshot();
9964 let rename_buffer_range = rename_range.to_offset(&snapshot);
9965 let cursor_offset_in_rename_range =
9966 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9967 let cursor_offset_in_rename_range_end =
9968 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9969
9970 this.take_rename(false, cx);
9971 let buffer = this.buffer.read(cx).read(cx);
9972 let cursor_offset = selection.head().to_offset(&buffer);
9973 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9974 let rename_end = rename_start + rename_buffer_range.len();
9975 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9976 let mut old_highlight_id = None;
9977 let old_name: Arc<str> = buffer
9978 .chunks(rename_start..rename_end, true)
9979 .map(|chunk| {
9980 if old_highlight_id.is_none() {
9981 old_highlight_id = chunk.syntax_highlight_id;
9982 }
9983 chunk.text
9984 })
9985 .collect::<String>()
9986 .into();
9987
9988 drop(buffer);
9989
9990 // Position the selection in the rename editor so that it matches the current selection.
9991 this.show_local_selections = false;
9992 let rename_editor = cx.new_view(|cx| {
9993 let mut editor = Editor::single_line(cx);
9994 editor.buffer.update(cx, |buffer, cx| {
9995 buffer.edit([(0..0, old_name.clone())], None, cx)
9996 });
9997 let rename_selection_range = match cursor_offset_in_rename_range
9998 .cmp(&cursor_offset_in_rename_range_end)
9999 {
10000 Ordering::Equal => {
10001 editor.select_all(&SelectAll, cx);
10002 return editor;
10003 }
10004 Ordering::Less => {
10005 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10006 }
10007 Ordering::Greater => {
10008 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10009 }
10010 };
10011 if rename_selection_range.end > old_name.len() {
10012 editor.select_all(&SelectAll, cx);
10013 } else {
10014 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10015 s.select_ranges([rename_selection_range]);
10016 });
10017 }
10018 editor
10019 });
10020 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10021 if e == &EditorEvent::Focused {
10022 cx.emit(EditorEvent::FocusedIn)
10023 }
10024 })
10025 .detach();
10026
10027 let write_highlights =
10028 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10029 let read_highlights =
10030 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10031 let ranges = write_highlights
10032 .iter()
10033 .flat_map(|(_, ranges)| ranges.iter())
10034 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10035 .cloned()
10036 .collect();
10037
10038 this.highlight_text::<Rename>(
10039 ranges,
10040 HighlightStyle {
10041 fade_out: Some(0.6),
10042 ..Default::default()
10043 },
10044 cx,
10045 );
10046 let rename_focus_handle = rename_editor.focus_handle(cx);
10047 cx.focus(&rename_focus_handle);
10048 let block_id = this.insert_blocks(
10049 [BlockProperties {
10050 style: BlockStyle::Flex,
10051 position: range.start,
10052 height: 1,
10053 render: Box::new({
10054 let rename_editor = rename_editor.clone();
10055 move |cx: &mut BlockContext| {
10056 let mut text_style = cx.editor_style.text.clone();
10057 if let Some(highlight_style) = old_highlight_id
10058 .and_then(|h| h.style(&cx.editor_style.syntax))
10059 {
10060 text_style = text_style.highlight(highlight_style);
10061 }
10062 div()
10063 .pl(cx.anchor_x)
10064 .child(EditorElement::new(
10065 &rename_editor,
10066 EditorStyle {
10067 background: cx.theme().system().transparent,
10068 local_player: cx.editor_style.local_player,
10069 text: text_style,
10070 scrollbar_width: cx.editor_style.scrollbar_width,
10071 syntax: cx.editor_style.syntax.clone(),
10072 status: cx.editor_style.status.clone(),
10073 inlay_hints_style: HighlightStyle {
10074 font_weight: Some(FontWeight::BOLD),
10075 ..make_inlay_hints_style(cx)
10076 },
10077 suggestions_style: HighlightStyle {
10078 color: Some(cx.theme().status().predictive),
10079 ..HighlightStyle::default()
10080 },
10081 ..EditorStyle::default()
10082 },
10083 ))
10084 .into_any_element()
10085 }
10086 }),
10087 disposition: BlockDisposition::Below,
10088 priority: 0,
10089 }],
10090 Some(Autoscroll::fit()),
10091 cx,
10092 )[0];
10093 this.pending_rename = Some(RenameState {
10094 range,
10095 old_name,
10096 editor: rename_editor,
10097 block_id,
10098 });
10099 })?;
10100 }
10101
10102 Ok(())
10103 }))
10104 }
10105
10106 pub fn confirm_rename(
10107 &mut self,
10108 _: &ConfirmRename,
10109 cx: &mut ViewContext<Self>,
10110 ) -> Option<Task<Result<()>>> {
10111 let rename = self.take_rename(false, cx)?;
10112 let workspace = self.workspace()?;
10113 let (start_buffer, start) = self
10114 .buffer
10115 .read(cx)
10116 .text_anchor_for_position(rename.range.start, cx)?;
10117 let (end_buffer, end) = self
10118 .buffer
10119 .read(cx)
10120 .text_anchor_for_position(rename.range.end, cx)?;
10121 if start_buffer != end_buffer {
10122 return None;
10123 }
10124
10125 let buffer = start_buffer;
10126 let range = start..end;
10127 let old_name = rename.old_name;
10128 let new_name = rename.editor.read(cx).text(cx);
10129
10130 let rename = workspace
10131 .read(cx)
10132 .project()
10133 .clone()
10134 .update(cx, |project, cx| {
10135 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10136 });
10137 let workspace = workspace.downgrade();
10138
10139 Some(cx.spawn(|editor, mut cx| async move {
10140 let project_transaction = rename.await?;
10141 Self::open_project_transaction(
10142 &editor,
10143 workspace,
10144 project_transaction,
10145 format!("Rename: {} → {}", old_name, new_name),
10146 cx.clone(),
10147 )
10148 .await?;
10149
10150 editor.update(&mut cx, |editor, cx| {
10151 editor.refresh_document_highlights(cx);
10152 })?;
10153 Ok(())
10154 }))
10155 }
10156
10157 fn take_rename(
10158 &mut self,
10159 moving_cursor: bool,
10160 cx: &mut ViewContext<Self>,
10161 ) -> Option<RenameState> {
10162 let rename = self.pending_rename.take()?;
10163 if rename.editor.focus_handle(cx).is_focused(cx) {
10164 cx.focus(&self.focus_handle);
10165 }
10166
10167 self.remove_blocks(
10168 [rename.block_id].into_iter().collect(),
10169 Some(Autoscroll::fit()),
10170 cx,
10171 );
10172 self.clear_highlights::<Rename>(cx);
10173 self.show_local_selections = true;
10174
10175 if moving_cursor {
10176 let rename_editor = rename.editor.read(cx);
10177 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10178
10179 // Update the selection to match the position of the selection inside
10180 // the rename editor.
10181 let snapshot = self.buffer.read(cx).read(cx);
10182 let rename_range = rename.range.to_offset(&snapshot);
10183 let cursor_in_editor = snapshot
10184 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10185 .min(rename_range.end);
10186 drop(snapshot);
10187
10188 self.change_selections(None, cx, |s| {
10189 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10190 });
10191 } else {
10192 self.refresh_document_highlights(cx);
10193 }
10194
10195 Some(rename)
10196 }
10197
10198 pub fn pending_rename(&self) -> Option<&RenameState> {
10199 self.pending_rename.as_ref()
10200 }
10201
10202 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10203 let project = match &self.project {
10204 Some(project) => project.clone(),
10205 None => return None,
10206 };
10207
10208 Some(self.perform_format(project, FormatTrigger::Manual, cx))
10209 }
10210
10211 fn perform_format(
10212 &mut self,
10213 project: Model<Project>,
10214 trigger: FormatTrigger,
10215 cx: &mut ViewContext<Self>,
10216 ) -> Task<Result<()>> {
10217 let buffer = self.buffer().clone();
10218 let mut buffers = buffer.read(cx).all_buffers();
10219 if trigger == FormatTrigger::Save {
10220 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10221 }
10222
10223 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10224 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10225
10226 cx.spawn(|_, mut cx| async move {
10227 let transaction = futures::select_biased! {
10228 () = timeout => {
10229 log::warn!("timed out waiting for formatting");
10230 None
10231 }
10232 transaction = format.log_err().fuse() => transaction,
10233 };
10234
10235 buffer
10236 .update(&mut cx, |buffer, cx| {
10237 if let Some(transaction) = transaction {
10238 if !buffer.is_singleton() {
10239 buffer.push_transaction(&transaction.0, cx);
10240 }
10241 }
10242
10243 cx.notify();
10244 })
10245 .ok();
10246
10247 Ok(())
10248 })
10249 }
10250
10251 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10252 if let Some(project) = self.project.clone() {
10253 self.buffer.update(cx, |multi_buffer, cx| {
10254 project.update(cx, |project, cx| {
10255 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10256 });
10257 })
10258 }
10259 }
10260
10261 fn cancel_language_server_work(
10262 &mut self,
10263 _: &CancelLanguageServerWork,
10264 cx: &mut ViewContext<Self>,
10265 ) {
10266 if let Some(project) = self.project.clone() {
10267 self.buffer.update(cx, |multi_buffer, cx| {
10268 project.update(cx, |project, cx| {
10269 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10270 });
10271 })
10272 }
10273 }
10274
10275 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10276 cx.show_character_palette();
10277 }
10278
10279 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10280 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10281 let buffer = self.buffer.read(cx).snapshot(cx);
10282 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10283 let is_valid = buffer
10284 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10285 .any(|entry| {
10286 entry.diagnostic.is_primary
10287 && !entry.range.is_empty()
10288 && entry.range.start == primary_range_start
10289 && entry.diagnostic.message == active_diagnostics.primary_message
10290 });
10291
10292 if is_valid != active_diagnostics.is_valid {
10293 active_diagnostics.is_valid = is_valid;
10294 let mut new_styles = HashMap::default();
10295 for (block_id, diagnostic) in &active_diagnostics.blocks {
10296 new_styles.insert(
10297 *block_id,
10298 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10299 );
10300 }
10301 self.display_map.update(cx, |display_map, _cx| {
10302 display_map.replace_blocks(new_styles)
10303 });
10304 }
10305 }
10306 }
10307
10308 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10309 self.dismiss_diagnostics(cx);
10310 let snapshot = self.snapshot(cx);
10311 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10312 let buffer = self.buffer.read(cx).snapshot(cx);
10313
10314 let mut primary_range = None;
10315 let mut primary_message = None;
10316 let mut group_end = Point::zero();
10317 let diagnostic_group = buffer
10318 .diagnostic_group::<MultiBufferPoint>(group_id)
10319 .filter_map(|entry| {
10320 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10321 && (entry.range.start.row == entry.range.end.row
10322 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10323 {
10324 return None;
10325 }
10326 if entry.range.end > group_end {
10327 group_end = entry.range.end;
10328 }
10329 if entry.diagnostic.is_primary {
10330 primary_range = Some(entry.range.clone());
10331 primary_message = Some(entry.diagnostic.message.clone());
10332 }
10333 Some(entry)
10334 })
10335 .collect::<Vec<_>>();
10336 let primary_range = primary_range?;
10337 let primary_message = primary_message?;
10338 let primary_range =
10339 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10340
10341 let blocks = display_map
10342 .insert_blocks(
10343 diagnostic_group.iter().map(|entry| {
10344 let diagnostic = entry.diagnostic.clone();
10345 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10346 BlockProperties {
10347 style: BlockStyle::Fixed,
10348 position: buffer.anchor_after(entry.range.start),
10349 height: message_height,
10350 render: diagnostic_block_renderer(diagnostic, None, true, true),
10351 disposition: BlockDisposition::Below,
10352 priority: 0,
10353 }
10354 }),
10355 cx,
10356 )
10357 .into_iter()
10358 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10359 .collect();
10360
10361 Some(ActiveDiagnosticGroup {
10362 primary_range,
10363 primary_message,
10364 group_id,
10365 blocks,
10366 is_valid: true,
10367 })
10368 });
10369 self.active_diagnostics.is_some()
10370 }
10371
10372 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10373 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10374 self.display_map.update(cx, |display_map, cx| {
10375 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10376 });
10377 cx.notify();
10378 }
10379 }
10380
10381 pub fn set_selections_from_remote(
10382 &mut self,
10383 selections: Vec<Selection<Anchor>>,
10384 pending_selection: Option<Selection<Anchor>>,
10385 cx: &mut ViewContext<Self>,
10386 ) {
10387 let old_cursor_position = self.selections.newest_anchor().head();
10388 self.selections.change_with(cx, |s| {
10389 s.select_anchors(selections);
10390 if let Some(pending_selection) = pending_selection {
10391 s.set_pending(pending_selection, SelectMode::Character);
10392 } else {
10393 s.clear_pending();
10394 }
10395 });
10396 self.selections_did_change(false, &old_cursor_position, true, cx);
10397 }
10398
10399 fn push_to_selection_history(&mut self) {
10400 self.selection_history.push(SelectionHistoryEntry {
10401 selections: self.selections.disjoint_anchors(),
10402 select_next_state: self.select_next_state.clone(),
10403 select_prev_state: self.select_prev_state.clone(),
10404 add_selections_state: self.add_selections_state.clone(),
10405 });
10406 }
10407
10408 pub fn transact(
10409 &mut self,
10410 cx: &mut ViewContext<Self>,
10411 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10412 ) -> Option<TransactionId> {
10413 self.start_transaction_at(Instant::now(), cx);
10414 update(self, cx);
10415 self.end_transaction_at(Instant::now(), cx)
10416 }
10417
10418 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10419 self.end_selection(cx);
10420 if let Some(tx_id) = self
10421 .buffer
10422 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10423 {
10424 self.selection_history
10425 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10426 cx.emit(EditorEvent::TransactionBegun {
10427 transaction_id: tx_id,
10428 })
10429 }
10430 }
10431
10432 fn end_transaction_at(
10433 &mut self,
10434 now: Instant,
10435 cx: &mut ViewContext<Self>,
10436 ) -> Option<TransactionId> {
10437 if let Some(transaction_id) = self
10438 .buffer
10439 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10440 {
10441 if let Some((_, end_selections)) =
10442 self.selection_history.transaction_mut(transaction_id)
10443 {
10444 *end_selections = Some(self.selections.disjoint_anchors());
10445 } else {
10446 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10447 }
10448
10449 cx.emit(EditorEvent::Edited { transaction_id });
10450 Some(transaction_id)
10451 } else {
10452 None
10453 }
10454 }
10455
10456 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10457 let mut fold_ranges = Vec::new();
10458
10459 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10460
10461 let selections = self.selections.all_adjusted(cx);
10462 for selection in selections {
10463 let range = selection.range().sorted();
10464 let buffer_start_row = range.start.row;
10465
10466 for row in (0..=range.end.row).rev() {
10467 if let Some((foldable_range, fold_text)) =
10468 display_map.foldable_range(MultiBufferRow(row))
10469 {
10470 if foldable_range.end.row >= buffer_start_row {
10471 fold_ranges.push((foldable_range, fold_text));
10472 if row <= range.start.row {
10473 break;
10474 }
10475 }
10476 }
10477 }
10478 }
10479
10480 self.fold_ranges(fold_ranges, true, cx);
10481 }
10482
10483 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10484 let buffer_row = fold_at.buffer_row;
10485 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10486
10487 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10488 let autoscroll = self
10489 .selections
10490 .all::<Point>(cx)
10491 .iter()
10492 .any(|selection| fold_range.overlaps(&selection.range()));
10493
10494 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10495 }
10496 }
10497
10498 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10499 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10500 let buffer = &display_map.buffer_snapshot;
10501 let selections = self.selections.all::<Point>(cx);
10502 let ranges = selections
10503 .iter()
10504 .map(|s| {
10505 let range = s.display_range(&display_map).sorted();
10506 let mut start = range.start.to_point(&display_map);
10507 let mut end = range.end.to_point(&display_map);
10508 start.column = 0;
10509 end.column = buffer.line_len(MultiBufferRow(end.row));
10510 start..end
10511 })
10512 .collect::<Vec<_>>();
10513
10514 self.unfold_ranges(ranges, true, true, cx);
10515 }
10516
10517 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10518 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10519
10520 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10521 ..Point::new(
10522 unfold_at.buffer_row.0,
10523 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10524 );
10525
10526 let autoscroll = self
10527 .selections
10528 .all::<Point>(cx)
10529 .iter()
10530 .any(|selection| selection.range().overlaps(&intersection_range));
10531
10532 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10533 }
10534
10535 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10536 let selections = self.selections.all::<Point>(cx);
10537 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10538 let line_mode = self.selections.line_mode;
10539 let ranges = selections.into_iter().map(|s| {
10540 if line_mode {
10541 let start = Point::new(s.start.row, 0);
10542 let end = Point::new(
10543 s.end.row,
10544 display_map
10545 .buffer_snapshot
10546 .line_len(MultiBufferRow(s.end.row)),
10547 );
10548 (start..end, display_map.fold_placeholder.clone())
10549 } else {
10550 (s.start..s.end, display_map.fold_placeholder.clone())
10551 }
10552 });
10553 self.fold_ranges(ranges, true, cx);
10554 }
10555
10556 pub fn fold_ranges<T: ToOffset + Clone>(
10557 &mut self,
10558 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10559 auto_scroll: bool,
10560 cx: &mut ViewContext<Self>,
10561 ) {
10562 let mut fold_ranges = Vec::new();
10563 let mut buffers_affected = HashMap::default();
10564 let multi_buffer = self.buffer().read(cx);
10565 for (fold_range, fold_text) in ranges {
10566 if let Some((_, buffer, _)) =
10567 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10568 {
10569 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10570 };
10571 fold_ranges.push((fold_range, fold_text));
10572 }
10573
10574 let mut ranges = fold_ranges.into_iter().peekable();
10575 if ranges.peek().is_some() {
10576 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10577
10578 if auto_scroll {
10579 self.request_autoscroll(Autoscroll::fit(), cx);
10580 }
10581
10582 for buffer in buffers_affected.into_values() {
10583 self.sync_expanded_diff_hunks(buffer, cx);
10584 }
10585
10586 cx.notify();
10587
10588 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10589 // Clear diagnostics block when folding a range that contains it.
10590 let snapshot = self.snapshot(cx);
10591 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10592 drop(snapshot);
10593 self.active_diagnostics = Some(active_diagnostics);
10594 self.dismiss_diagnostics(cx);
10595 } else {
10596 self.active_diagnostics = Some(active_diagnostics);
10597 }
10598 }
10599
10600 self.scrollbar_marker_state.dirty = true;
10601 }
10602 }
10603
10604 pub fn unfold_ranges<T: ToOffset + Clone>(
10605 &mut self,
10606 ranges: impl IntoIterator<Item = Range<T>>,
10607 inclusive: bool,
10608 auto_scroll: bool,
10609 cx: &mut ViewContext<Self>,
10610 ) {
10611 let mut unfold_ranges = Vec::new();
10612 let mut buffers_affected = HashMap::default();
10613 let multi_buffer = self.buffer().read(cx);
10614 for range in ranges {
10615 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10616 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10617 };
10618 unfold_ranges.push(range);
10619 }
10620
10621 let mut ranges = unfold_ranges.into_iter().peekable();
10622 if ranges.peek().is_some() {
10623 self.display_map
10624 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10625 if auto_scroll {
10626 self.request_autoscroll(Autoscroll::fit(), cx);
10627 }
10628
10629 for buffer in buffers_affected.into_values() {
10630 self.sync_expanded_diff_hunks(buffer, cx);
10631 }
10632
10633 cx.notify();
10634 self.scrollbar_marker_state.dirty = true;
10635 self.active_indent_guides_state.dirty = true;
10636 }
10637 }
10638
10639 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10640 self.display_map.read(cx).fold_placeholder.clone()
10641 }
10642
10643 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10644 if hovered != self.gutter_hovered {
10645 self.gutter_hovered = hovered;
10646 cx.notify();
10647 }
10648 }
10649
10650 pub fn insert_blocks(
10651 &mut self,
10652 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10653 autoscroll: Option<Autoscroll>,
10654 cx: &mut ViewContext<Self>,
10655 ) -> Vec<CustomBlockId> {
10656 let blocks = self
10657 .display_map
10658 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10659 if let Some(autoscroll) = autoscroll {
10660 self.request_autoscroll(autoscroll, cx);
10661 }
10662 cx.notify();
10663 blocks
10664 }
10665
10666 pub fn resize_blocks(
10667 &mut self,
10668 heights: HashMap<CustomBlockId, u32>,
10669 autoscroll: Option<Autoscroll>,
10670 cx: &mut ViewContext<Self>,
10671 ) {
10672 self.display_map
10673 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10674 if let Some(autoscroll) = autoscroll {
10675 self.request_autoscroll(autoscroll, cx);
10676 }
10677 cx.notify();
10678 }
10679
10680 pub fn replace_blocks(
10681 &mut self,
10682 renderers: HashMap<CustomBlockId, RenderBlock>,
10683 autoscroll: Option<Autoscroll>,
10684 cx: &mut ViewContext<Self>,
10685 ) {
10686 self.display_map
10687 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10688 if let Some(autoscroll) = autoscroll {
10689 self.request_autoscroll(autoscroll, cx);
10690 }
10691 cx.notify();
10692 }
10693
10694 pub fn remove_blocks(
10695 &mut self,
10696 block_ids: HashSet<CustomBlockId>,
10697 autoscroll: Option<Autoscroll>,
10698 cx: &mut ViewContext<Self>,
10699 ) {
10700 self.display_map.update(cx, |display_map, cx| {
10701 display_map.remove_blocks(block_ids, cx)
10702 });
10703 if let Some(autoscroll) = autoscroll {
10704 self.request_autoscroll(autoscroll, cx);
10705 }
10706 cx.notify();
10707 }
10708
10709 pub fn row_for_block(
10710 &self,
10711 block_id: CustomBlockId,
10712 cx: &mut ViewContext<Self>,
10713 ) -> Option<DisplayRow> {
10714 self.display_map
10715 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10716 }
10717
10718 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10719 self.focused_block = Some(focused_block);
10720 }
10721
10722 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10723 self.focused_block.take()
10724 }
10725
10726 pub fn insert_creases(
10727 &mut self,
10728 creases: impl IntoIterator<Item = Crease>,
10729 cx: &mut ViewContext<Self>,
10730 ) -> Vec<CreaseId> {
10731 self.display_map
10732 .update(cx, |map, cx| map.insert_creases(creases, cx))
10733 }
10734
10735 pub fn remove_creases(
10736 &mut self,
10737 ids: impl IntoIterator<Item = CreaseId>,
10738 cx: &mut ViewContext<Self>,
10739 ) {
10740 self.display_map
10741 .update(cx, |map, cx| map.remove_creases(ids, cx));
10742 }
10743
10744 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10745 self.display_map
10746 .update(cx, |map, cx| map.snapshot(cx))
10747 .longest_row()
10748 }
10749
10750 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10751 self.display_map
10752 .update(cx, |map, cx| map.snapshot(cx))
10753 .max_point()
10754 }
10755
10756 pub fn text(&self, cx: &AppContext) -> String {
10757 self.buffer.read(cx).read(cx).text()
10758 }
10759
10760 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10761 let text = self.text(cx);
10762 let text = text.trim();
10763
10764 if text.is_empty() {
10765 return None;
10766 }
10767
10768 Some(text.to_string())
10769 }
10770
10771 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10772 self.transact(cx, |this, cx| {
10773 this.buffer
10774 .read(cx)
10775 .as_singleton()
10776 .expect("you can only call set_text on editors for singleton buffers")
10777 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10778 });
10779 }
10780
10781 pub fn display_text(&self, cx: &mut AppContext) -> String {
10782 self.display_map
10783 .update(cx, |map, cx| map.snapshot(cx))
10784 .text()
10785 }
10786
10787 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10788 let mut wrap_guides = smallvec::smallvec![];
10789
10790 if self.show_wrap_guides == Some(false) {
10791 return wrap_guides;
10792 }
10793
10794 let settings = self.buffer.read(cx).settings_at(0, cx);
10795 if settings.show_wrap_guides {
10796 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10797 wrap_guides.push((soft_wrap as usize, true));
10798 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10799 wrap_guides.push((soft_wrap as usize, true));
10800 }
10801 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10802 }
10803
10804 wrap_guides
10805 }
10806
10807 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10808 let settings = self.buffer.read(cx).settings_at(0, cx);
10809 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10810 match mode {
10811 language_settings::SoftWrap::None => SoftWrap::None,
10812 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10813 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10814 language_settings::SoftWrap::PreferredLineLength => {
10815 SoftWrap::Column(settings.preferred_line_length)
10816 }
10817 language_settings::SoftWrap::Bounded => {
10818 SoftWrap::Bounded(settings.preferred_line_length)
10819 }
10820 }
10821 }
10822
10823 pub fn set_soft_wrap_mode(
10824 &mut self,
10825 mode: language_settings::SoftWrap,
10826 cx: &mut ViewContext<Self>,
10827 ) {
10828 self.soft_wrap_mode_override = Some(mode);
10829 cx.notify();
10830 }
10831
10832 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10833 let rem_size = cx.rem_size();
10834 self.display_map.update(cx, |map, cx| {
10835 map.set_font(
10836 style.text.font(),
10837 style.text.font_size.to_pixels(rem_size),
10838 cx,
10839 )
10840 });
10841 self.style = Some(style);
10842 }
10843
10844 pub fn style(&self) -> Option<&EditorStyle> {
10845 self.style.as_ref()
10846 }
10847
10848 // Called by the element. This method is not designed to be called outside of the editor
10849 // element's layout code because it does not notify when rewrapping is computed synchronously.
10850 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10851 self.display_map
10852 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10853 }
10854
10855 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10856 if self.soft_wrap_mode_override.is_some() {
10857 self.soft_wrap_mode_override.take();
10858 } else {
10859 let soft_wrap = match self.soft_wrap_mode(cx) {
10860 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10861 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10862 language_settings::SoftWrap::PreferLine
10863 }
10864 };
10865 self.soft_wrap_mode_override = Some(soft_wrap);
10866 }
10867 cx.notify();
10868 }
10869
10870 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10871 let Some(workspace) = self.workspace() else {
10872 return;
10873 };
10874 let fs = workspace.read(cx).app_state().fs.clone();
10875 let current_show = TabBarSettings::get_global(cx).show;
10876 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10877 setting.show = Some(!current_show);
10878 });
10879 }
10880
10881 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10882 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10883 self.buffer
10884 .read(cx)
10885 .settings_at(0, cx)
10886 .indent_guides
10887 .enabled
10888 });
10889 self.show_indent_guides = Some(!currently_enabled);
10890 cx.notify();
10891 }
10892
10893 fn should_show_indent_guides(&self) -> Option<bool> {
10894 self.show_indent_guides
10895 }
10896
10897 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10898 let mut editor_settings = EditorSettings::get_global(cx).clone();
10899 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10900 EditorSettings::override_global(editor_settings, cx);
10901 }
10902
10903 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10904 self.use_relative_line_numbers
10905 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10906 }
10907
10908 pub fn toggle_relative_line_numbers(
10909 &mut self,
10910 _: &ToggleRelativeLineNumbers,
10911 cx: &mut ViewContext<Self>,
10912 ) {
10913 let is_relative = self.should_use_relative_line_numbers(cx);
10914 self.set_relative_line_number(Some(!is_relative), cx)
10915 }
10916
10917 pub fn set_relative_line_number(
10918 &mut self,
10919 is_relative: Option<bool>,
10920 cx: &mut ViewContext<Self>,
10921 ) {
10922 self.use_relative_line_numbers = is_relative;
10923 cx.notify();
10924 }
10925
10926 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10927 self.show_gutter = show_gutter;
10928 cx.notify();
10929 }
10930
10931 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10932 self.show_line_numbers = Some(show_line_numbers);
10933 cx.notify();
10934 }
10935
10936 pub fn set_show_git_diff_gutter(
10937 &mut self,
10938 show_git_diff_gutter: bool,
10939 cx: &mut ViewContext<Self>,
10940 ) {
10941 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10942 cx.notify();
10943 }
10944
10945 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10946 self.show_code_actions = Some(show_code_actions);
10947 cx.notify();
10948 }
10949
10950 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10951 self.show_runnables = Some(show_runnables);
10952 cx.notify();
10953 }
10954
10955 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10956 if self.display_map.read(cx).masked != masked {
10957 self.display_map.update(cx, |map, _| map.masked = masked);
10958 }
10959 cx.notify()
10960 }
10961
10962 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10963 self.show_wrap_guides = Some(show_wrap_guides);
10964 cx.notify();
10965 }
10966
10967 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10968 self.show_indent_guides = Some(show_indent_guides);
10969 cx.notify();
10970 }
10971
10972 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10973 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10974 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10975 if let Some(dir) = file.abs_path(cx).parent() {
10976 return Some(dir.to_owned());
10977 }
10978 }
10979
10980 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10981 return Some(project_path.path.to_path_buf());
10982 }
10983 }
10984
10985 None
10986 }
10987
10988 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10989 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10990 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10991 cx.reveal_path(&file.abs_path(cx));
10992 }
10993 }
10994 }
10995
10996 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
10997 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10998 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10999 if let Some(path) = file.abs_path(cx).to_str() {
11000 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11001 }
11002 }
11003 }
11004 }
11005
11006 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11007 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11008 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11009 if let Some(path) = file.path().to_str() {
11010 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11011 }
11012 }
11013 }
11014 }
11015
11016 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11017 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11018
11019 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11020 self.start_git_blame(true, cx);
11021 }
11022
11023 cx.notify();
11024 }
11025
11026 pub fn toggle_git_blame_inline(
11027 &mut self,
11028 _: &ToggleGitBlameInline,
11029 cx: &mut ViewContext<Self>,
11030 ) {
11031 self.toggle_git_blame_inline_internal(true, cx);
11032 cx.notify();
11033 }
11034
11035 pub fn git_blame_inline_enabled(&self) -> bool {
11036 self.git_blame_inline_enabled
11037 }
11038
11039 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11040 self.show_selection_menu = self
11041 .show_selection_menu
11042 .map(|show_selections_menu| !show_selections_menu)
11043 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11044
11045 cx.notify();
11046 }
11047
11048 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11049 self.show_selection_menu
11050 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11051 }
11052
11053 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11054 if let Some(project) = self.project.as_ref() {
11055 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11056 return;
11057 };
11058
11059 if buffer.read(cx).file().is_none() {
11060 return;
11061 }
11062
11063 let focused = self.focus_handle(cx).contains_focused(cx);
11064
11065 let project = project.clone();
11066 let blame =
11067 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11068 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11069 self.blame = Some(blame);
11070 }
11071 }
11072
11073 fn toggle_git_blame_inline_internal(
11074 &mut self,
11075 user_triggered: bool,
11076 cx: &mut ViewContext<Self>,
11077 ) {
11078 if self.git_blame_inline_enabled {
11079 self.git_blame_inline_enabled = false;
11080 self.show_git_blame_inline = false;
11081 self.show_git_blame_inline_delay_task.take();
11082 } else {
11083 self.git_blame_inline_enabled = true;
11084 self.start_git_blame_inline(user_triggered, cx);
11085 }
11086
11087 cx.notify();
11088 }
11089
11090 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11091 self.start_git_blame(user_triggered, cx);
11092
11093 if ProjectSettings::get_global(cx)
11094 .git
11095 .inline_blame_delay()
11096 .is_some()
11097 {
11098 self.start_inline_blame_timer(cx);
11099 } else {
11100 self.show_git_blame_inline = true
11101 }
11102 }
11103
11104 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11105 self.blame.as_ref()
11106 }
11107
11108 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11109 self.show_git_blame_gutter && self.has_blame_entries(cx)
11110 }
11111
11112 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11113 self.show_git_blame_inline
11114 && self.focus_handle.is_focused(cx)
11115 && !self.newest_selection_head_on_empty_line(cx)
11116 && self.has_blame_entries(cx)
11117 }
11118
11119 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11120 self.blame()
11121 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11122 }
11123
11124 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11125 let cursor_anchor = self.selections.newest_anchor().head();
11126
11127 let snapshot = self.buffer.read(cx).snapshot(cx);
11128 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11129
11130 snapshot.line_len(buffer_row) == 0
11131 }
11132
11133 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11134 let (path, selection, repo) = maybe!({
11135 let project_handle = self.project.as_ref()?.clone();
11136 let project = project_handle.read(cx);
11137
11138 let selection = self.selections.newest::<Point>(cx);
11139 let selection_range = selection.range();
11140
11141 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11142 (buffer, selection_range.start.row..selection_range.end.row)
11143 } else {
11144 let buffer_ranges = self
11145 .buffer()
11146 .read(cx)
11147 .range_to_buffer_ranges(selection_range, cx);
11148
11149 let (buffer, range, _) = if selection.reversed {
11150 buffer_ranges.first()
11151 } else {
11152 buffer_ranges.last()
11153 }?;
11154
11155 let snapshot = buffer.read(cx).snapshot();
11156 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11157 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11158 (buffer.clone(), selection)
11159 };
11160
11161 let path = buffer
11162 .read(cx)
11163 .file()?
11164 .as_local()?
11165 .path()
11166 .to_str()?
11167 .to_string();
11168 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11169 Some((path, selection, repo))
11170 })
11171 .ok_or_else(|| anyhow!("unable to open git repository"))?;
11172
11173 const REMOTE_NAME: &str = "origin";
11174 let origin_url = repo
11175 .remote_url(REMOTE_NAME)
11176 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11177 let sha = repo
11178 .head_sha()
11179 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11180
11181 let (provider, remote) =
11182 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11183 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11184
11185 Ok(provider.build_permalink(
11186 remote,
11187 BuildPermalinkParams {
11188 sha: &sha,
11189 path: &path,
11190 selection: Some(selection),
11191 },
11192 ))
11193 }
11194
11195 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11196 let permalink = self.get_permalink_to_line(cx);
11197
11198 match permalink {
11199 Ok(permalink) => {
11200 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11201 }
11202 Err(err) => {
11203 let message = format!("Failed to copy permalink: {err}");
11204
11205 Err::<(), anyhow::Error>(err).log_err();
11206
11207 if let Some(workspace) = self.workspace() {
11208 workspace.update(cx, |workspace, cx| {
11209 struct CopyPermalinkToLine;
11210
11211 workspace.show_toast(
11212 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11213 cx,
11214 )
11215 })
11216 }
11217 }
11218 }
11219 }
11220
11221 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11222 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11223 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11224 if let Some(path) = file.path().to_str() {
11225 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11226 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11227 }
11228 }
11229 }
11230 }
11231
11232 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11233 let permalink = self.get_permalink_to_line(cx);
11234
11235 match permalink {
11236 Ok(permalink) => {
11237 cx.open_url(permalink.as_ref());
11238 }
11239 Err(err) => {
11240 let message = format!("Failed to open permalink: {err}");
11241
11242 Err::<(), anyhow::Error>(err).log_err();
11243
11244 if let Some(workspace) = self.workspace() {
11245 workspace.update(cx, |workspace, cx| {
11246 struct OpenPermalinkToLine;
11247
11248 workspace.show_toast(
11249 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11250 cx,
11251 )
11252 })
11253 }
11254 }
11255 }
11256 }
11257
11258 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11259 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11260 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11261 pub fn highlight_rows<T: 'static>(
11262 &mut self,
11263 rows: RangeInclusive<Anchor>,
11264 color: Option<Hsla>,
11265 should_autoscroll: bool,
11266 cx: &mut ViewContext<Self>,
11267 ) {
11268 let snapshot = self.buffer().read(cx).snapshot(cx);
11269 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11270 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11271 highlight
11272 .range
11273 .start()
11274 .cmp(rows.start(), &snapshot)
11275 .then(highlight.range.end().cmp(rows.end(), &snapshot))
11276 });
11277 match (color, existing_highlight_index) {
11278 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11279 ix,
11280 RowHighlight {
11281 index: post_inc(&mut self.highlight_order),
11282 range: rows,
11283 should_autoscroll,
11284 color,
11285 },
11286 ),
11287 (None, Ok(i)) => {
11288 row_highlights.remove(i);
11289 }
11290 }
11291 }
11292
11293 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11294 pub fn clear_row_highlights<T: 'static>(&mut self) {
11295 self.highlighted_rows.remove(&TypeId::of::<T>());
11296 }
11297
11298 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11299 pub fn highlighted_rows<T: 'static>(
11300 &self,
11301 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11302 Some(
11303 self.highlighted_rows
11304 .get(&TypeId::of::<T>())?
11305 .iter()
11306 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11307 )
11308 }
11309
11310 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11311 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11312 /// Allows to ignore certain kinds of highlights.
11313 pub fn highlighted_display_rows(
11314 &mut self,
11315 cx: &mut WindowContext,
11316 ) -> BTreeMap<DisplayRow, Hsla> {
11317 let snapshot = self.snapshot(cx);
11318 let mut used_highlight_orders = HashMap::default();
11319 self.highlighted_rows
11320 .iter()
11321 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11322 .fold(
11323 BTreeMap::<DisplayRow, Hsla>::new(),
11324 |mut unique_rows, highlight| {
11325 let start_row = highlight.range.start().to_display_point(&snapshot).row();
11326 let end_row = highlight.range.end().to_display_point(&snapshot).row();
11327 for row in start_row.0..=end_row.0 {
11328 let used_index =
11329 used_highlight_orders.entry(row).or_insert(highlight.index);
11330 if highlight.index >= *used_index {
11331 *used_index = highlight.index;
11332 match highlight.color {
11333 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11334 None => unique_rows.remove(&DisplayRow(row)),
11335 };
11336 }
11337 }
11338 unique_rows
11339 },
11340 )
11341 }
11342
11343 pub fn highlighted_display_row_for_autoscroll(
11344 &self,
11345 snapshot: &DisplaySnapshot,
11346 ) -> Option<DisplayRow> {
11347 self.highlighted_rows
11348 .values()
11349 .flat_map(|highlighted_rows| highlighted_rows.iter())
11350 .filter_map(|highlight| {
11351 if highlight.color.is_none() || !highlight.should_autoscroll {
11352 return None;
11353 }
11354 Some(highlight.range.start().to_display_point(snapshot).row())
11355 })
11356 .min()
11357 }
11358
11359 pub fn set_search_within_ranges(
11360 &mut self,
11361 ranges: &[Range<Anchor>],
11362 cx: &mut ViewContext<Self>,
11363 ) {
11364 self.highlight_background::<SearchWithinRange>(
11365 ranges,
11366 |colors| colors.editor_document_highlight_read_background,
11367 cx,
11368 )
11369 }
11370
11371 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11372 self.breadcrumb_header = Some(new_header);
11373 }
11374
11375 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11376 self.clear_background_highlights::<SearchWithinRange>(cx);
11377 }
11378
11379 pub fn highlight_background<T: 'static>(
11380 &mut self,
11381 ranges: &[Range<Anchor>],
11382 color_fetcher: fn(&ThemeColors) -> Hsla,
11383 cx: &mut ViewContext<Self>,
11384 ) {
11385 self.background_highlights
11386 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11387 self.scrollbar_marker_state.dirty = true;
11388 cx.notify();
11389 }
11390
11391 pub fn clear_background_highlights<T: 'static>(
11392 &mut self,
11393 cx: &mut ViewContext<Self>,
11394 ) -> Option<BackgroundHighlight> {
11395 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11396 if !text_highlights.1.is_empty() {
11397 self.scrollbar_marker_state.dirty = true;
11398 cx.notify();
11399 }
11400 Some(text_highlights)
11401 }
11402
11403 pub fn highlight_gutter<T: 'static>(
11404 &mut self,
11405 ranges: &[Range<Anchor>],
11406 color_fetcher: fn(&AppContext) -> Hsla,
11407 cx: &mut ViewContext<Self>,
11408 ) {
11409 self.gutter_highlights
11410 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11411 cx.notify();
11412 }
11413
11414 pub fn clear_gutter_highlights<T: 'static>(
11415 &mut self,
11416 cx: &mut ViewContext<Self>,
11417 ) -> Option<GutterHighlight> {
11418 cx.notify();
11419 self.gutter_highlights.remove(&TypeId::of::<T>())
11420 }
11421
11422 #[cfg(feature = "test-support")]
11423 pub fn all_text_background_highlights(
11424 &mut self,
11425 cx: &mut ViewContext<Self>,
11426 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11427 let snapshot = self.snapshot(cx);
11428 let buffer = &snapshot.buffer_snapshot;
11429 let start = buffer.anchor_before(0);
11430 let end = buffer.anchor_after(buffer.len());
11431 let theme = cx.theme().colors();
11432 self.background_highlights_in_range(start..end, &snapshot, theme)
11433 }
11434
11435 #[cfg(feature = "test-support")]
11436 pub fn search_background_highlights(
11437 &mut self,
11438 cx: &mut ViewContext<Self>,
11439 ) -> Vec<Range<Point>> {
11440 let snapshot = self.buffer().read(cx).snapshot(cx);
11441
11442 let highlights = self
11443 .background_highlights
11444 .get(&TypeId::of::<items::BufferSearchHighlights>());
11445
11446 if let Some((_color, ranges)) = highlights {
11447 ranges
11448 .iter()
11449 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11450 .collect_vec()
11451 } else {
11452 vec![]
11453 }
11454 }
11455
11456 fn document_highlights_for_position<'a>(
11457 &'a self,
11458 position: Anchor,
11459 buffer: &'a MultiBufferSnapshot,
11460 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11461 let read_highlights = self
11462 .background_highlights
11463 .get(&TypeId::of::<DocumentHighlightRead>())
11464 .map(|h| &h.1);
11465 let write_highlights = self
11466 .background_highlights
11467 .get(&TypeId::of::<DocumentHighlightWrite>())
11468 .map(|h| &h.1);
11469 let left_position = position.bias_left(buffer);
11470 let right_position = position.bias_right(buffer);
11471 read_highlights
11472 .into_iter()
11473 .chain(write_highlights)
11474 .flat_map(move |ranges| {
11475 let start_ix = match ranges.binary_search_by(|probe| {
11476 let cmp = probe.end.cmp(&left_position, buffer);
11477 if cmp.is_ge() {
11478 Ordering::Greater
11479 } else {
11480 Ordering::Less
11481 }
11482 }) {
11483 Ok(i) | Err(i) => i,
11484 };
11485
11486 ranges[start_ix..]
11487 .iter()
11488 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11489 })
11490 }
11491
11492 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11493 self.background_highlights
11494 .get(&TypeId::of::<T>())
11495 .map_or(false, |(_, highlights)| !highlights.is_empty())
11496 }
11497
11498 pub fn background_highlights_in_range(
11499 &self,
11500 search_range: Range<Anchor>,
11501 display_snapshot: &DisplaySnapshot,
11502 theme: &ThemeColors,
11503 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11504 let mut results = Vec::new();
11505 for (color_fetcher, ranges) in self.background_highlights.values() {
11506 let color = color_fetcher(theme);
11507 let start_ix = match ranges.binary_search_by(|probe| {
11508 let cmp = probe
11509 .end
11510 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11511 if cmp.is_gt() {
11512 Ordering::Greater
11513 } else {
11514 Ordering::Less
11515 }
11516 }) {
11517 Ok(i) | Err(i) => i,
11518 };
11519 for range in &ranges[start_ix..] {
11520 if range
11521 .start
11522 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11523 .is_ge()
11524 {
11525 break;
11526 }
11527
11528 let start = range.start.to_display_point(display_snapshot);
11529 let end = range.end.to_display_point(display_snapshot);
11530 results.push((start..end, color))
11531 }
11532 }
11533 results
11534 }
11535
11536 pub fn background_highlight_row_ranges<T: 'static>(
11537 &self,
11538 search_range: Range<Anchor>,
11539 display_snapshot: &DisplaySnapshot,
11540 count: usize,
11541 ) -> Vec<RangeInclusive<DisplayPoint>> {
11542 let mut results = Vec::new();
11543 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11544 return vec![];
11545 };
11546
11547 let start_ix = match ranges.binary_search_by(|probe| {
11548 let cmp = probe
11549 .end
11550 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11551 if cmp.is_gt() {
11552 Ordering::Greater
11553 } else {
11554 Ordering::Less
11555 }
11556 }) {
11557 Ok(i) | Err(i) => i,
11558 };
11559 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11560 if let (Some(start_display), Some(end_display)) = (start, end) {
11561 results.push(
11562 start_display.to_display_point(display_snapshot)
11563 ..=end_display.to_display_point(display_snapshot),
11564 );
11565 }
11566 };
11567 let mut start_row: Option<Point> = None;
11568 let mut end_row: Option<Point> = None;
11569 if ranges.len() > count {
11570 return Vec::new();
11571 }
11572 for range in &ranges[start_ix..] {
11573 if range
11574 .start
11575 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11576 .is_ge()
11577 {
11578 break;
11579 }
11580 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11581 if let Some(current_row) = &end_row {
11582 if end.row == current_row.row {
11583 continue;
11584 }
11585 }
11586 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11587 if start_row.is_none() {
11588 assert_eq!(end_row, None);
11589 start_row = Some(start);
11590 end_row = Some(end);
11591 continue;
11592 }
11593 if let Some(current_end) = end_row.as_mut() {
11594 if start.row > current_end.row + 1 {
11595 push_region(start_row, end_row);
11596 start_row = Some(start);
11597 end_row = Some(end);
11598 } else {
11599 // Merge two hunks.
11600 *current_end = end;
11601 }
11602 } else {
11603 unreachable!();
11604 }
11605 }
11606 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11607 push_region(start_row, end_row);
11608 results
11609 }
11610
11611 pub fn gutter_highlights_in_range(
11612 &self,
11613 search_range: Range<Anchor>,
11614 display_snapshot: &DisplaySnapshot,
11615 cx: &AppContext,
11616 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11617 let mut results = Vec::new();
11618 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11619 let color = color_fetcher(cx);
11620 let start_ix = match ranges.binary_search_by(|probe| {
11621 let cmp = probe
11622 .end
11623 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11624 if cmp.is_gt() {
11625 Ordering::Greater
11626 } else {
11627 Ordering::Less
11628 }
11629 }) {
11630 Ok(i) | Err(i) => i,
11631 };
11632 for range in &ranges[start_ix..] {
11633 if range
11634 .start
11635 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11636 .is_ge()
11637 {
11638 break;
11639 }
11640
11641 let start = range.start.to_display_point(display_snapshot);
11642 let end = range.end.to_display_point(display_snapshot);
11643 results.push((start..end, color))
11644 }
11645 }
11646 results
11647 }
11648
11649 /// Get the text ranges corresponding to the redaction query
11650 pub fn redacted_ranges(
11651 &self,
11652 search_range: Range<Anchor>,
11653 display_snapshot: &DisplaySnapshot,
11654 cx: &WindowContext,
11655 ) -> Vec<Range<DisplayPoint>> {
11656 display_snapshot
11657 .buffer_snapshot
11658 .redacted_ranges(search_range, |file| {
11659 if let Some(file) = file {
11660 file.is_private()
11661 && EditorSettings::get(
11662 Some(SettingsLocation {
11663 worktree_id: file.worktree_id(cx),
11664 path: file.path().as_ref(),
11665 }),
11666 cx,
11667 )
11668 .redact_private_values
11669 } else {
11670 false
11671 }
11672 })
11673 .map(|range| {
11674 range.start.to_display_point(display_snapshot)
11675 ..range.end.to_display_point(display_snapshot)
11676 })
11677 .collect()
11678 }
11679
11680 pub fn highlight_text<T: 'static>(
11681 &mut self,
11682 ranges: Vec<Range<Anchor>>,
11683 style: HighlightStyle,
11684 cx: &mut ViewContext<Self>,
11685 ) {
11686 self.display_map.update(cx, |map, _| {
11687 map.highlight_text(TypeId::of::<T>(), ranges, style)
11688 });
11689 cx.notify();
11690 }
11691
11692 pub(crate) fn highlight_inlays<T: 'static>(
11693 &mut self,
11694 highlights: Vec<InlayHighlight>,
11695 style: HighlightStyle,
11696 cx: &mut ViewContext<Self>,
11697 ) {
11698 self.display_map.update(cx, |map, _| {
11699 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11700 });
11701 cx.notify();
11702 }
11703
11704 pub fn text_highlights<'a, T: 'static>(
11705 &'a self,
11706 cx: &'a AppContext,
11707 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11708 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11709 }
11710
11711 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11712 let cleared = self
11713 .display_map
11714 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11715 if cleared {
11716 cx.notify();
11717 }
11718 }
11719
11720 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11721 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11722 && self.focus_handle.is_focused(cx)
11723 }
11724
11725 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11726 self.show_cursor_when_unfocused = is_enabled;
11727 cx.notify();
11728 }
11729
11730 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11731 cx.notify();
11732 }
11733
11734 fn on_buffer_event(
11735 &mut self,
11736 multibuffer: Model<MultiBuffer>,
11737 event: &multi_buffer::Event,
11738 cx: &mut ViewContext<Self>,
11739 ) {
11740 match event {
11741 multi_buffer::Event::Edited {
11742 singleton_buffer_edited,
11743 } => {
11744 self.scrollbar_marker_state.dirty = true;
11745 self.active_indent_guides_state.dirty = true;
11746 self.refresh_active_diagnostics(cx);
11747 self.refresh_code_actions(cx);
11748 if self.has_active_inline_completion(cx) {
11749 self.update_visible_inline_completion(cx);
11750 }
11751 cx.emit(EditorEvent::BufferEdited);
11752 cx.emit(SearchEvent::MatchesInvalidated);
11753 if *singleton_buffer_edited {
11754 if let Some(project) = &self.project {
11755 let project = project.read(cx);
11756 #[allow(clippy::mutable_key_type)]
11757 let languages_affected = multibuffer
11758 .read(cx)
11759 .all_buffers()
11760 .into_iter()
11761 .filter_map(|buffer| {
11762 let buffer = buffer.read(cx);
11763 let language = buffer.language()?;
11764 if project.is_local_or_ssh()
11765 && project.language_servers_for_buffer(buffer, cx).count() == 0
11766 {
11767 None
11768 } else {
11769 Some(language)
11770 }
11771 })
11772 .cloned()
11773 .collect::<HashSet<_>>();
11774 if !languages_affected.is_empty() {
11775 self.refresh_inlay_hints(
11776 InlayHintRefreshReason::BufferEdited(languages_affected),
11777 cx,
11778 );
11779 }
11780 }
11781 }
11782
11783 let Some(project) = &self.project else { return };
11784 let telemetry = project.read(cx).client().telemetry().clone();
11785 refresh_linked_ranges(self, cx);
11786 telemetry.log_edit_event("editor");
11787 }
11788 multi_buffer::Event::ExcerptsAdded {
11789 buffer,
11790 predecessor,
11791 excerpts,
11792 } => {
11793 self.tasks_update_task = Some(self.refresh_runnables(cx));
11794 cx.emit(EditorEvent::ExcerptsAdded {
11795 buffer: buffer.clone(),
11796 predecessor: *predecessor,
11797 excerpts: excerpts.clone(),
11798 });
11799 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11800 }
11801 multi_buffer::Event::ExcerptsRemoved { ids } => {
11802 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11803 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11804 }
11805 multi_buffer::Event::ExcerptsEdited { ids } => {
11806 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11807 }
11808 multi_buffer::Event::ExcerptsExpanded { ids } => {
11809 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11810 }
11811 multi_buffer::Event::Reparsed(buffer_id) => {
11812 self.tasks_update_task = Some(self.refresh_runnables(cx));
11813
11814 cx.emit(EditorEvent::Reparsed(*buffer_id));
11815 }
11816 multi_buffer::Event::LanguageChanged(buffer_id) => {
11817 linked_editing_ranges::refresh_linked_ranges(self, cx);
11818 cx.emit(EditorEvent::Reparsed(*buffer_id));
11819 cx.notify();
11820 }
11821 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11822 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11823 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11824 cx.emit(EditorEvent::TitleChanged)
11825 }
11826 multi_buffer::Event::DiffBaseChanged => {
11827 self.scrollbar_marker_state.dirty = true;
11828 cx.emit(EditorEvent::DiffBaseChanged);
11829 cx.notify();
11830 }
11831 multi_buffer::Event::DiffUpdated { buffer } => {
11832 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11833 cx.notify();
11834 }
11835 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11836 multi_buffer::Event::DiagnosticsUpdated => {
11837 self.refresh_active_diagnostics(cx);
11838 self.scrollbar_marker_state.dirty = true;
11839 cx.notify();
11840 }
11841 _ => {}
11842 };
11843 }
11844
11845 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11846 cx.notify();
11847 }
11848
11849 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11850 self.tasks_update_task = Some(self.refresh_runnables(cx));
11851 self.refresh_inline_completion(true, false, cx);
11852 self.refresh_inlay_hints(
11853 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11854 self.selections.newest_anchor().head(),
11855 &self.buffer.read(cx).snapshot(cx),
11856 cx,
11857 )),
11858 cx,
11859 );
11860 let editor_settings = EditorSettings::get_global(cx);
11861 if let Some(cursor_shape) = editor_settings.cursor_shape {
11862 self.cursor_shape = cursor_shape;
11863 }
11864 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11865 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11866
11867 let project_settings = ProjectSettings::get_global(cx);
11868 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11869
11870 if self.mode == EditorMode::Full {
11871 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11872 if self.git_blame_inline_enabled != inline_blame_enabled {
11873 self.toggle_git_blame_inline_internal(false, cx);
11874 }
11875 }
11876
11877 cx.notify();
11878 }
11879
11880 pub fn set_searchable(&mut self, searchable: bool) {
11881 self.searchable = searchable;
11882 }
11883
11884 pub fn searchable(&self) -> bool {
11885 self.searchable
11886 }
11887
11888 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11889 self.open_excerpts_common(true, cx)
11890 }
11891
11892 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11893 self.open_excerpts_common(false, cx)
11894 }
11895
11896 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11897 let buffer = self.buffer.read(cx);
11898 if buffer.is_singleton() {
11899 cx.propagate();
11900 return;
11901 }
11902
11903 let Some(workspace) = self.workspace() else {
11904 cx.propagate();
11905 return;
11906 };
11907
11908 let mut new_selections_by_buffer = HashMap::default();
11909 for selection in self.selections.all::<usize>(cx) {
11910 for (buffer, mut range, _) in
11911 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11912 {
11913 if selection.reversed {
11914 mem::swap(&mut range.start, &mut range.end);
11915 }
11916 new_selections_by_buffer
11917 .entry(buffer)
11918 .or_insert(Vec::new())
11919 .push(range)
11920 }
11921 }
11922
11923 // We defer the pane interaction because we ourselves are a workspace item
11924 // and activating a new item causes the pane to call a method on us reentrantly,
11925 // which panics if we're on the stack.
11926 cx.window_context().defer(move |cx| {
11927 workspace.update(cx, |workspace, cx| {
11928 let pane = if split {
11929 workspace.adjacent_pane(cx)
11930 } else {
11931 workspace.active_pane().clone()
11932 };
11933
11934 for (buffer, ranges) in new_selections_by_buffer {
11935 let editor =
11936 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11937 editor.update(cx, |editor, cx| {
11938 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11939 s.select_ranges(ranges);
11940 });
11941 });
11942 }
11943 })
11944 });
11945 }
11946
11947 fn jump(
11948 &mut self,
11949 path: ProjectPath,
11950 position: Point,
11951 anchor: language::Anchor,
11952 offset_from_top: u32,
11953 cx: &mut ViewContext<Self>,
11954 ) {
11955 let workspace = self.workspace();
11956 cx.spawn(|_, mut cx| async move {
11957 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
11958 let editor = workspace.update(&mut cx, |workspace, cx| {
11959 // Reset the preview item id before opening the new item
11960 workspace.active_pane().update(cx, |pane, cx| {
11961 pane.set_preview_item_id(None, cx);
11962 });
11963 workspace.open_path_preview(path, None, true, true, cx)
11964 })?;
11965 let editor = editor
11966 .await?
11967 .downcast::<Editor>()
11968 .ok_or_else(|| anyhow!("opened item was not an editor"))?
11969 .downgrade();
11970 editor.update(&mut cx, |editor, cx| {
11971 let buffer = editor
11972 .buffer()
11973 .read(cx)
11974 .as_singleton()
11975 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
11976 let buffer = buffer.read(cx);
11977 let cursor = if buffer.can_resolve(&anchor) {
11978 language::ToPoint::to_point(&anchor, buffer)
11979 } else {
11980 buffer.clip_point(position, Bias::Left)
11981 };
11982
11983 let nav_history = editor.nav_history.take();
11984 editor.change_selections(
11985 Some(Autoscroll::top_relative(offset_from_top as usize)),
11986 cx,
11987 |s| {
11988 s.select_ranges([cursor..cursor]);
11989 },
11990 );
11991 editor.nav_history = nav_history;
11992
11993 anyhow::Ok(())
11994 })??;
11995
11996 anyhow::Ok(())
11997 })
11998 .detach_and_log_err(cx);
11999 }
12000
12001 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12002 let snapshot = self.buffer.read(cx).read(cx);
12003 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12004 Some(
12005 ranges
12006 .iter()
12007 .map(move |range| {
12008 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12009 })
12010 .collect(),
12011 )
12012 }
12013
12014 fn selection_replacement_ranges(
12015 &self,
12016 range: Range<OffsetUtf16>,
12017 cx: &AppContext,
12018 ) -> Vec<Range<OffsetUtf16>> {
12019 let selections = self.selections.all::<OffsetUtf16>(cx);
12020 let newest_selection = selections
12021 .iter()
12022 .max_by_key(|selection| selection.id)
12023 .unwrap();
12024 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12025 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12026 let snapshot = self.buffer.read(cx).read(cx);
12027 selections
12028 .into_iter()
12029 .map(|mut selection| {
12030 selection.start.0 =
12031 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12032 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12033 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12034 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12035 })
12036 .collect()
12037 }
12038
12039 fn report_editor_event(
12040 &self,
12041 operation: &'static str,
12042 file_extension: Option<String>,
12043 cx: &AppContext,
12044 ) {
12045 if cfg!(any(test, feature = "test-support")) {
12046 return;
12047 }
12048
12049 let Some(project) = &self.project else { return };
12050
12051 // If None, we are in a file without an extension
12052 let file = self
12053 .buffer
12054 .read(cx)
12055 .as_singleton()
12056 .and_then(|b| b.read(cx).file());
12057 let file_extension = file_extension.or(file
12058 .as_ref()
12059 .and_then(|file| Path::new(file.file_name(cx)).extension())
12060 .and_then(|e| e.to_str())
12061 .map(|a| a.to_string()));
12062
12063 let vim_mode = cx
12064 .global::<SettingsStore>()
12065 .raw_user_settings()
12066 .get("vim_mode")
12067 == Some(&serde_json::Value::Bool(true));
12068
12069 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12070 == language::language_settings::InlineCompletionProvider::Copilot;
12071 let copilot_enabled_for_language = self
12072 .buffer
12073 .read(cx)
12074 .settings_at(0, cx)
12075 .show_inline_completions;
12076
12077 let telemetry = project.read(cx).client().telemetry().clone();
12078 telemetry.report_editor_event(
12079 file_extension,
12080 vim_mode,
12081 operation,
12082 copilot_enabled,
12083 copilot_enabled_for_language,
12084 )
12085 }
12086
12087 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12088 /// with each line being an array of {text, highlight} objects.
12089 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12090 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12091 return;
12092 };
12093
12094 #[derive(Serialize)]
12095 struct Chunk<'a> {
12096 text: String,
12097 highlight: Option<&'a str>,
12098 }
12099
12100 let snapshot = buffer.read(cx).snapshot();
12101 let range = self
12102 .selected_text_range(false, cx)
12103 .and_then(|selection| {
12104 if selection.range.is_empty() {
12105 None
12106 } else {
12107 Some(selection.range)
12108 }
12109 })
12110 .unwrap_or_else(|| 0..snapshot.len());
12111
12112 let chunks = snapshot.chunks(range, true);
12113 let mut lines = Vec::new();
12114 let mut line: VecDeque<Chunk> = VecDeque::new();
12115
12116 let Some(style) = self.style.as_ref() else {
12117 return;
12118 };
12119
12120 for chunk in chunks {
12121 let highlight = chunk
12122 .syntax_highlight_id
12123 .and_then(|id| id.name(&style.syntax));
12124 let mut chunk_lines = chunk.text.split('\n').peekable();
12125 while let Some(text) = chunk_lines.next() {
12126 let mut merged_with_last_token = false;
12127 if let Some(last_token) = line.back_mut() {
12128 if last_token.highlight == highlight {
12129 last_token.text.push_str(text);
12130 merged_with_last_token = true;
12131 }
12132 }
12133
12134 if !merged_with_last_token {
12135 line.push_back(Chunk {
12136 text: text.into(),
12137 highlight,
12138 });
12139 }
12140
12141 if chunk_lines.peek().is_some() {
12142 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12143 line.pop_front();
12144 }
12145 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12146 line.pop_back();
12147 }
12148
12149 lines.push(mem::take(&mut line));
12150 }
12151 }
12152 }
12153
12154 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12155 return;
12156 };
12157 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12158 }
12159
12160 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12161 &self.inlay_hint_cache
12162 }
12163
12164 pub fn replay_insert_event(
12165 &mut self,
12166 text: &str,
12167 relative_utf16_range: Option<Range<isize>>,
12168 cx: &mut ViewContext<Self>,
12169 ) {
12170 if !self.input_enabled {
12171 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12172 return;
12173 }
12174 if let Some(relative_utf16_range) = relative_utf16_range {
12175 let selections = self.selections.all::<OffsetUtf16>(cx);
12176 self.change_selections(None, cx, |s| {
12177 let new_ranges = selections.into_iter().map(|range| {
12178 let start = OffsetUtf16(
12179 range
12180 .head()
12181 .0
12182 .saturating_add_signed(relative_utf16_range.start),
12183 );
12184 let end = OffsetUtf16(
12185 range
12186 .head()
12187 .0
12188 .saturating_add_signed(relative_utf16_range.end),
12189 );
12190 start..end
12191 });
12192 s.select_ranges(new_ranges);
12193 });
12194 }
12195
12196 self.handle_input(text, cx);
12197 }
12198
12199 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12200 let Some(project) = self.project.as_ref() else {
12201 return false;
12202 };
12203 let project = project.read(cx);
12204
12205 let mut supports = false;
12206 self.buffer().read(cx).for_each_buffer(|buffer| {
12207 if !supports {
12208 supports = project
12209 .language_servers_for_buffer(buffer.read(cx), cx)
12210 .any(
12211 |(_, server)| match server.capabilities().inlay_hint_provider {
12212 Some(lsp::OneOf::Left(enabled)) => enabled,
12213 Some(lsp::OneOf::Right(_)) => true,
12214 None => false,
12215 },
12216 )
12217 }
12218 });
12219 supports
12220 }
12221
12222 pub fn focus(&self, cx: &mut WindowContext) {
12223 cx.focus(&self.focus_handle)
12224 }
12225
12226 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12227 self.focus_handle.is_focused(cx)
12228 }
12229
12230 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12231 cx.emit(EditorEvent::Focused);
12232
12233 if let Some(descendant) = self
12234 .last_focused_descendant
12235 .take()
12236 .and_then(|descendant| descendant.upgrade())
12237 {
12238 cx.focus(&descendant);
12239 } else {
12240 if let Some(blame) = self.blame.as_ref() {
12241 blame.update(cx, GitBlame::focus)
12242 }
12243
12244 self.blink_manager.update(cx, BlinkManager::enable);
12245 self.show_cursor_names(cx);
12246 self.buffer.update(cx, |buffer, cx| {
12247 buffer.finalize_last_transaction(cx);
12248 if self.leader_peer_id.is_none() {
12249 buffer.set_active_selections(
12250 &self.selections.disjoint_anchors(),
12251 self.selections.line_mode,
12252 self.cursor_shape,
12253 cx,
12254 );
12255 }
12256 });
12257 }
12258 }
12259
12260 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12261 cx.emit(EditorEvent::FocusedIn)
12262 }
12263
12264 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12265 if event.blurred != self.focus_handle {
12266 self.last_focused_descendant = Some(event.blurred);
12267 }
12268 }
12269
12270 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12271 self.blink_manager.update(cx, BlinkManager::disable);
12272 self.buffer
12273 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12274
12275 if let Some(blame) = self.blame.as_ref() {
12276 blame.update(cx, GitBlame::blur)
12277 }
12278 if !self.hover_state.focused(cx) {
12279 hide_hover(self, cx);
12280 }
12281
12282 self.hide_context_menu(cx);
12283 cx.emit(EditorEvent::Blurred);
12284 cx.notify();
12285 }
12286
12287 pub fn register_action<A: Action>(
12288 &mut self,
12289 listener: impl Fn(&A, &mut WindowContext) + 'static,
12290 ) -> Subscription {
12291 let id = self.next_editor_action_id.post_inc();
12292 let listener = Arc::new(listener);
12293 self.editor_actions.borrow_mut().insert(
12294 id,
12295 Box::new(move |cx| {
12296 let cx = cx.window_context();
12297 let listener = listener.clone();
12298 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12299 let action = action.downcast_ref().unwrap();
12300 if phase == DispatchPhase::Bubble {
12301 listener(action, cx)
12302 }
12303 })
12304 }),
12305 );
12306
12307 let editor_actions = self.editor_actions.clone();
12308 Subscription::new(move || {
12309 editor_actions.borrow_mut().remove(&id);
12310 })
12311 }
12312
12313 pub fn file_header_size(&self) -> u32 {
12314 self.file_header_size
12315 }
12316
12317 pub fn revert(
12318 &mut self,
12319 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12320 cx: &mut ViewContext<Self>,
12321 ) {
12322 self.buffer().update(cx, |multi_buffer, cx| {
12323 for (buffer_id, changes) in revert_changes {
12324 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12325 buffer.update(cx, |buffer, cx| {
12326 buffer.edit(
12327 changes.into_iter().map(|(range, text)| {
12328 (range, text.to_string().map(Arc::<str>::from))
12329 }),
12330 None,
12331 cx,
12332 );
12333 });
12334 }
12335 }
12336 });
12337 self.change_selections(None, cx, |selections| selections.refresh());
12338 }
12339
12340 pub fn to_pixel_point(
12341 &mut self,
12342 source: multi_buffer::Anchor,
12343 editor_snapshot: &EditorSnapshot,
12344 cx: &mut ViewContext<Self>,
12345 ) -> Option<gpui::Point<Pixels>> {
12346 let source_point = source.to_display_point(editor_snapshot);
12347 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12348 }
12349
12350 pub fn display_to_pixel_point(
12351 &mut self,
12352 source: DisplayPoint,
12353 editor_snapshot: &EditorSnapshot,
12354 cx: &mut ViewContext<Self>,
12355 ) -> Option<gpui::Point<Pixels>> {
12356 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12357 let text_layout_details = self.text_layout_details(cx);
12358 let scroll_top = text_layout_details
12359 .scroll_anchor
12360 .scroll_position(editor_snapshot)
12361 .y;
12362
12363 if source.row().as_f32() < scroll_top.floor() {
12364 return None;
12365 }
12366 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12367 let source_y = line_height * (source.row().as_f32() - scroll_top);
12368 Some(gpui::Point::new(source_x, source_y))
12369 }
12370
12371 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12372 let bounds = self.last_bounds?;
12373 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12374 }
12375
12376 pub fn has_active_completions_menu(&self) -> bool {
12377 self.context_menu.read().as_ref().map_or(false, |menu| {
12378 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12379 })
12380 }
12381
12382 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12383 self.addons
12384 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12385 }
12386
12387 pub fn unregister_addon<T: Addon>(&mut self) {
12388 self.addons.remove(&std::any::TypeId::of::<T>());
12389 }
12390
12391 pub fn addon<T: Addon>(&self) -> Option<&T> {
12392 let type_id = std::any::TypeId::of::<T>();
12393 self.addons
12394 .get(&type_id)
12395 .and_then(|item| item.to_any().downcast_ref::<T>())
12396 }
12397}
12398
12399fn hunks_for_selections(
12400 multi_buffer_snapshot: &MultiBufferSnapshot,
12401 selections: &[Selection<Anchor>],
12402) -> Vec<DiffHunk<MultiBufferRow>> {
12403 let buffer_rows_for_selections = selections.iter().map(|selection| {
12404 let head = selection.head();
12405 let tail = selection.tail();
12406 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12407 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12408 if start > end {
12409 end..start
12410 } else {
12411 start..end
12412 }
12413 });
12414
12415 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12416}
12417
12418pub fn hunks_for_rows(
12419 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12420 multi_buffer_snapshot: &MultiBufferSnapshot,
12421) -> Vec<DiffHunk<MultiBufferRow>> {
12422 let mut hunks = Vec::new();
12423 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12424 HashMap::default();
12425 for selected_multi_buffer_rows in rows {
12426 let query_rows =
12427 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12428 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12429 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12430 // when the caret is just above or just below the deleted hunk.
12431 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12432 let related_to_selection = if allow_adjacent {
12433 hunk.associated_range.overlaps(&query_rows)
12434 || hunk.associated_range.start == query_rows.end
12435 || hunk.associated_range.end == query_rows.start
12436 } else {
12437 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12438 // `hunk.associated_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12439 hunk.associated_range.overlaps(&selected_multi_buffer_rows)
12440 || selected_multi_buffer_rows.end == hunk.associated_range.start
12441 };
12442 if related_to_selection {
12443 if !processed_buffer_rows
12444 .entry(hunk.buffer_id)
12445 .or_default()
12446 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12447 {
12448 continue;
12449 }
12450 hunks.push(hunk);
12451 }
12452 }
12453 }
12454
12455 hunks
12456}
12457
12458pub trait CollaborationHub {
12459 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12460 fn user_participant_indices<'a>(
12461 &self,
12462 cx: &'a AppContext,
12463 ) -> &'a HashMap<u64, ParticipantIndex>;
12464 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12465}
12466
12467impl CollaborationHub for Model<Project> {
12468 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12469 self.read(cx).collaborators()
12470 }
12471
12472 fn user_participant_indices<'a>(
12473 &self,
12474 cx: &'a AppContext,
12475 ) -> &'a HashMap<u64, ParticipantIndex> {
12476 self.read(cx).user_store().read(cx).participant_indices()
12477 }
12478
12479 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12480 let this = self.read(cx);
12481 let user_ids = this.collaborators().values().map(|c| c.user_id);
12482 this.user_store().read_with(cx, |user_store, cx| {
12483 user_store.participant_names(user_ids, cx)
12484 })
12485 }
12486}
12487
12488pub trait CompletionProvider {
12489 fn completions(
12490 &self,
12491 buffer: &Model<Buffer>,
12492 buffer_position: text::Anchor,
12493 trigger: CompletionContext,
12494 cx: &mut ViewContext<Editor>,
12495 ) -> Task<Result<Vec<Completion>>>;
12496
12497 fn resolve_completions(
12498 &self,
12499 buffer: Model<Buffer>,
12500 completion_indices: Vec<usize>,
12501 completions: Arc<RwLock<Box<[Completion]>>>,
12502 cx: &mut ViewContext<Editor>,
12503 ) -> Task<Result<bool>>;
12504
12505 fn apply_additional_edits_for_completion(
12506 &self,
12507 buffer: Model<Buffer>,
12508 completion: Completion,
12509 push_to_history: bool,
12510 cx: &mut ViewContext<Editor>,
12511 ) -> Task<Result<Option<language::Transaction>>>;
12512
12513 fn is_completion_trigger(
12514 &self,
12515 buffer: &Model<Buffer>,
12516 position: language::Anchor,
12517 text: &str,
12518 trigger_in_words: bool,
12519 cx: &mut ViewContext<Editor>,
12520 ) -> bool;
12521
12522 fn sort_completions(&self) -> bool {
12523 true
12524 }
12525}
12526
12527fn snippet_completions(
12528 project: &Project,
12529 buffer: &Model<Buffer>,
12530 buffer_position: text::Anchor,
12531 cx: &mut AppContext,
12532) -> Vec<Completion> {
12533 let language = buffer.read(cx).language_at(buffer_position);
12534 let language_name = language.as_ref().map(|language| language.lsp_id());
12535 let snippet_store = project.snippets().read(cx);
12536 let snippets = snippet_store.snippets_for(language_name, cx);
12537
12538 if snippets.is_empty() {
12539 return vec![];
12540 }
12541 let snapshot = buffer.read(cx).text_snapshot();
12542 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12543
12544 let mut lines = chunks.lines();
12545 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12546 return vec![];
12547 };
12548
12549 let scope = language.map(|language| language.default_scope());
12550 let classifier = CharClassifier::new(scope).for_completion(true);
12551 let mut last_word = line_at
12552 .chars()
12553 .rev()
12554 .take_while(|c| classifier.is_word(*c))
12555 .collect::<String>();
12556 last_word = last_word.chars().rev().collect();
12557 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12558 let to_lsp = |point: &text::Anchor| {
12559 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12560 point_to_lsp(end)
12561 };
12562 let lsp_end = to_lsp(&buffer_position);
12563 snippets
12564 .into_iter()
12565 .filter_map(|snippet| {
12566 let matching_prefix = snippet
12567 .prefix
12568 .iter()
12569 .find(|prefix| prefix.starts_with(&last_word))?;
12570 let start = as_offset - last_word.len();
12571 let start = snapshot.anchor_before(start);
12572 let range = start..buffer_position;
12573 let lsp_start = to_lsp(&start);
12574 let lsp_range = lsp::Range {
12575 start: lsp_start,
12576 end: lsp_end,
12577 };
12578 Some(Completion {
12579 old_range: range,
12580 new_text: snippet.body.clone(),
12581 label: CodeLabel {
12582 text: matching_prefix.clone(),
12583 runs: vec![],
12584 filter_range: 0..matching_prefix.len(),
12585 },
12586 server_id: LanguageServerId(usize::MAX),
12587 documentation: snippet.description.clone().map(Documentation::SingleLine),
12588 lsp_completion: lsp::CompletionItem {
12589 label: snippet.prefix.first().unwrap().clone(),
12590 kind: Some(CompletionItemKind::SNIPPET),
12591 label_details: snippet.description.as_ref().map(|description| {
12592 lsp::CompletionItemLabelDetails {
12593 detail: Some(description.clone()),
12594 description: None,
12595 }
12596 }),
12597 insert_text_format: Some(InsertTextFormat::SNIPPET),
12598 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12599 lsp::InsertReplaceEdit {
12600 new_text: snippet.body.clone(),
12601 insert: lsp_range,
12602 replace: lsp_range,
12603 },
12604 )),
12605 filter_text: Some(snippet.body.clone()),
12606 sort_text: Some(char::MAX.to_string()),
12607 ..Default::default()
12608 },
12609 confirm: None,
12610 })
12611 })
12612 .collect()
12613}
12614
12615impl CompletionProvider for Model<Project> {
12616 fn completions(
12617 &self,
12618 buffer: &Model<Buffer>,
12619 buffer_position: text::Anchor,
12620 options: CompletionContext,
12621 cx: &mut ViewContext<Editor>,
12622 ) -> Task<Result<Vec<Completion>>> {
12623 self.update(cx, |project, cx| {
12624 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12625 let project_completions = project.completions(buffer, buffer_position, options, cx);
12626 cx.background_executor().spawn(async move {
12627 let mut completions = project_completions.await?;
12628 //let snippets = snippets.into_iter().;
12629 completions.extend(snippets);
12630 Ok(completions)
12631 })
12632 })
12633 }
12634
12635 fn resolve_completions(
12636 &self,
12637 buffer: Model<Buffer>,
12638 completion_indices: Vec<usize>,
12639 completions: Arc<RwLock<Box<[Completion]>>>,
12640 cx: &mut ViewContext<Editor>,
12641 ) -> Task<Result<bool>> {
12642 self.update(cx, |project, cx| {
12643 project.resolve_completions(buffer, completion_indices, completions, cx)
12644 })
12645 }
12646
12647 fn apply_additional_edits_for_completion(
12648 &self,
12649 buffer: Model<Buffer>,
12650 completion: Completion,
12651 push_to_history: bool,
12652 cx: &mut ViewContext<Editor>,
12653 ) -> Task<Result<Option<language::Transaction>>> {
12654 self.update(cx, |project, cx| {
12655 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12656 })
12657 }
12658
12659 fn is_completion_trigger(
12660 &self,
12661 buffer: &Model<Buffer>,
12662 position: language::Anchor,
12663 text: &str,
12664 trigger_in_words: bool,
12665 cx: &mut ViewContext<Editor>,
12666 ) -> bool {
12667 if !EditorSettings::get_global(cx).show_completions_on_input {
12668 return false;
12669 }
12670
12671 let mut chars = text.chars();
12672 let char = if let Some(char) = chars.next() {
12673 char
12674 } else {
12675 return false;
12676 };
12677 if chars.next().is_some() {
12678 return false;
12679 }
12680
12681 let buffer = buffer.read(cx);
12682 let classifier = buffer
12683 .snapshot()
12684 .char_classifier_at(position)
12685 .for_completion(true);
12686 if trigger_in_words && classifier.is_word(char) {
12687 return true;
12688 }
12689
12690 buffer
12691 .completion_triggers()
12692 .iter()
12693 .any(|string| string == text)
12694 }
12695}
12696
12697fn inlay_hint_settings(
12698 location: Anchor,
12699 snapshot: &MultiBufferSnapshot,
12700 cx: &mut ViewContext<'_, Editor>,
12701) -> InlayHintSettings {
12702 let file = snapshot.file_at(location);
12703 let language = snapshot.language_at(location);
12704 let settings = all_language_settings(file, cx);
12705 settings
12706 .language(language.map(|l| l.name()).as_ref())
12707 .inlay_hints
12708}
12709
12710fn consume_contiguous_rows(
12711 contiguous_row_selections: &mut Vec<Selection<Point>>,
12712 selection: &Selection<Point>,
12713 display_map: &DisplaySnapshot,
12714 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12715) -> (MultiBufferRow, MultiBufferRow) {
12716 contiguous_row_selections.push(selection.clone());
12717 let start_row = MultiBufferRow(selection.start.row);
12718 let mut end_row = ending_row(selection, display_map);
12719
12720 while let Some(next_selection) = selections.peek() {
12721 if next_selection.start.row <= end_row.0 {
12722 end_row = ending_row(next_selection, display_map);
12723 contiguous_row_selections.push(selections.next().unwrap().clone());
12724 } else {
12725 break;
12726 }
12727 }
12728 (start_row, end_row)
12729}
12730
12731fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12732 if next_selection.end.column > 0 || next_selection.is_empty() {
12733 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12734 } else {
12735 MultiBufferRow(next_selection.end.row)
12736 }
12737}
12738
12739impl EditorSnapshot {
12740 pub fn remote_selections_in_range<'a>(
12741 &'a self,
12742 range: &'a Range<Anchor>,
12743 collaboration_hub: &dyn CollaborationHub,
12744 cx: &'a AppContext,
12745 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12746 let participant_names = collaboration_hub.user_names(cx);
12747 let participant_indices = collaboration_hub.user_participant_indices(cx);
12748 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12749 let collaborators_by_replica_id = collaborators_by_peer_id
12750 .iter()
12751 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12752 .collect::<HashMap<_, _>>();
12753 self.buffer_snapshot
12754 .selections_in_range(range, false)
12755 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12756 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12757 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12758 let user_name = participant_names.get(&collaborator.user_id).cloned();
12759 Some(RemoteSelection {
12760 replica_id,
12761 selection,
12762 cursor_shape,
12763 line_mode,
12764 participant_index,
12765 peer_id: collaborator.peer_id,
12766 user_name,
12767 })
12768 })
12769 }
12770
12771 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12772 self.display_snapshot.buffer_snapshot.language_at(position)
12773 }
12774
12775 pub fn is_focused(&self) -> bool {
12776 self.is_focused
12777 }
12778
12779 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12780 self.placeholder_text.as_ref()
12781 }
12782
12783 pub fn scroll_position(&self) -> gpui::Point<f32> {
12784 self.scroll_anchor.scroll_position(&self.display_snapshot)
12785 }
12786
12787 fn gutter_dimensions(
12788 &self,
12789 font_id: FontId,
12790 font_size: Pixels,
12791 em_width: Pixels,
12792 max_line_number_width: Pixels,
12793 cx: &AppContext,
12794 ) -> GutterDimensions {
12795 if !self.show_gutter {
12796 return GutterDimensions::default();
12797 }
12798 let descent = cx.text_system().descent(font_id, font_size);
12799
12800 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12801 matches!(
12802 ProjectSettings::get_global(cx).git.git_gutter,
12803 Some(GitGutterSetting::TrackedFiles)
12804 )
12805 });
12806 let gutter_settings = EditorSettings::get_global(cx).gutter;
12807 let show_line_numbers = self
12808 .show_line_numbers
12809 .unwrap_or(gutter_settings.line_numbers);
12810 let line_gutter_width = if show_line_numbers {
12811 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12812 let min_width_for_number_on_gutter = em_width * 4.0;
12813 max_line_number_width.max(min_width_for_number_on_gutter)
12814 } else {
12815 0.0.into()
12816 };
12817
12818 let show_code_actions = self
12819 .show_code_actions
12820 .unwrap_or(gutter_settings.code_actions);
12821
12822 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12823
12824 let git_blame_entries_width = self
12825 .render_git_blame_gutter
12826 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12827
12828 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12829 left_padding += if show_code_actions || show_runnables {
12830 em_width * 3.0
12831 } else if show_git_gutter && show_line_numbers {
12832 em_width * 2.0
12833 } else if show_git_gutter || show_line_numbers {
12834 em_width
12835 } else {
12836 px(0.)
12837 };
12838
12839 let right_padding = if gutter_settings.folds && show_line_numbers {
12840 em_width * 4.0
12841 } else if gutter_settings.folds {
12842 em_width * 3.0
12843 } else if show_line_numbers {
12844 em_width
12845 } else {
12846 px(0.)
12847 };
12848
12849 GutterDimensions {
12850 left_padding,
12851 right_padding,
12852 width: line_gutter_width + left_padding + right_padding,
12853 margin: -descent,
12854 git_blame_entries_width,
12855 }
12856 }
12857
12858 pub fn render_fold_toggle(
12859 &self,
12860 buffer_row: MultiBufferRow,
12861 row_contains_cursor: bool,
12862 editor: View<Editor>,
12863 cx: &mut WindowContext,
12864 ) -> Option<AnyElement> {
12865 let folded = self.is_line_folded(buffer_row);
12866
12867 if let Some(crease) = self
12868 .crease_snapshot
12869 .query_row(buffer_row, &self.buffer_snapshot)
12870 {
12871 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12872 if folded {
12873 editor.update(cx, |editor, cx| {
12874 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12875 });
12876 } else {
12877 editor.update(cx, |editor, cx| {
12878 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12879 });
12880 }
12881 });
12882
12883 Some((crease.render_toggle)(
12884 buffer_row,
12885 folded,
12886 toggle_callback,
12887 cx,
12888 ))
12889 } else if folded
12890 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12891 {
12892 Some(
12893 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12894 .selected(folded)
12895 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12896 if folded {
12897 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12898 } else {
12899 this.fold_at(&FoldAt { buffer_row }, cx);
12900 }
12901 }))
12902 .into_any_element(),
12903 )
12904 } else {
12905 None
12906 }
12907 }
12908
12909 pub fn render_crease_trailer(
12910 &self,
12911 buffer_row: MultiBufferRow,
12912 cx: &mut WindowContext,
12913 ) -> Option<AnyElement> {
12914 let folded = self.is_line_folded(buffer_row);
12915 let crease = self
12916 .crease_snapshot
12917 .query_row(buffer_row, &self.buffer_snapshot)?;
12918 Some((crease.render_trailer)(buffer_row, folded, cx))
12919 }
12920}
12921
12922impl Deref for EditorSnapshot {
12923 type Target = DisplaySnapshot;
12924
12925 fn deref(&self) -> &Self::Target {
12926 &self.display_snapshot
12927 }
12928}
12929
12930#[derive(Clone, Debug, PartialEq, Eq)]
12931pub enum EditorEvent {
12932 InputIgnored {
12933 text: Arc<str>,
12934 },
12935 InputHandled {
12936 utf16_range_to_replace: Option<Range<isize>>,
12937 text: Arc<str>,
12938 },
12939 ExcerptsAdded {
12940 buffer: Model<Buffer>,
12941 predecessor: ExcerptId,
12942 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12943 },
12944 ExcerptsRemoved {
12945 ids: Vec<ExcerptId>,
12946 },
12947 ExcerptsEdited {
12948 ids: Vec<ExcerptId>,
12949 },
12950 ExcerptsExpanded {
12951 ids: Vec<ExcerptId>,
12952 },
12953 BufferEdited,
12954 Edited {
12955 transaction_id: clock::Lamport,
12956 },
12957 Reparsed(BufferId),
12958 Focused,
12959 FocusedIn,
12960 Blurred,
12961 DirtyChanged,
12962 Saved,
12963 TitleChanged,
12964 DiffBaseChanged,
12965 SelectionsChanged {
12966 local: bool,
12967 },
12968 ScrollPositionChanged {
12969 local: bool,
12970 autoscroll: bool,
12971 },
12972 Closed,
12973 TransactionUndone {
12974 transaction_id: clock::Lamport,
12975 },
12976 TransactionBegun {
12977 transaction_id: clock::Lamport,
12978 },
12979}
12980
12981impl EventEmitter<EditorEvent> for Editor {}
12982
12983impl FocusableView for Editor {
12984 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
12985 self.focus_handle.clone()
12986 }
12987}
12988
12989impl Render for Editor {
12990 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
12991 let settings = ThemeSettings::get_global(cx);
12992
12993 let text_style = match self.mode {
12994 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
12995 color: cx.theme().colors().editor_foreground,
12996 font_family: settings.ui_font.family.clone(),
12997 font_features: settings.ui_font.features.clone(),
12998 font_fallbacks: settings.ui_font.fallbacks.clone(),
12999 font_size: rems(0.875).into(),
13000 font_weight: settings.ui_font.weight,
13001 line_height: relative(settings.buffer_line_height.value()),
13002 ..Default::default()
13003 },
13004 EditorMode::Full => TextStyle {
13005 color: cx.theme().colors().editor_foreground,
13006 font_family: settings.buffer_font.family.clone(),
13007 font_features: settings.buffer_font.features.clone(),
13008 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13009 font_size: settings.buffer_font_size(cx).into(),
13010 font_weight: settings.buffer_font.weight,
13011 line_height: relative(settings.buffer_line_height.value()),
13012 ..Default::default()
13013 },
13014 };
13015
13016 let background = match self.mode {
13017 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13018 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13019 EditorMode::Full => cx.theme().colors().editor_background,
13020 };
13021
13022 EditorElement::new(
13023 cx.view(),
13024 EditorStyle {
13025 background,
13026 local_player: cx.theme().players().local(),
13027 text: text_style,
13028 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13029 syntax: cx.theme().syntax().clone(),
13030 status: cx.theme().status().clone(),
13031 inlay_hints_style: make_inlay_hints_style(cx),
13032 suggestions_style: HighlightStyle {
13033 color: Some(cx.theme().status().predictive),
13034 ..HighlightStyle::default()
13035 },
13036 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13037 },
13038 )
13039 }
13040}
13041
13042impl ViewInputHandler for Editor {
13043 fn text_for_range(
13044 &mut self,
13045 range_utf16: Range<usize>,
13046 cx: &mut ViewContext<Self>,
13047 ) -> Option<String> {
13048 Some(
13049 self.buffer
13050 .read(cx)
13051 .read(cx)
13052 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13053 .collect(),
13054 )
13055 }
13056
13057 fn selected_text_range(
13058 &mut self,
13059 ignore_disabled_input: bool,
13060 cx: &mut ViewContext<Self>,
13061 ) -> Option<UTF16Selection> {
13062 // Prevent the IME menu from appearing when holding down an alphabetic key
13063 // while input is disabled.
13064 if !ignore_disabled_input && !self.input_enabled {
13065 return None;
13066 }
13067
13068 let selection = self.selections.newest::<OffsetUtf16>(cx);
13069 let range = selection.range();
13070
13071 Some(UTF16Selection {
13072 range: range.start.0..range.end.0,
13073 reversed: selection.reversed,
13074 })
13075 }
13076
13077 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13078 let snapshot = self.buffer.read(cx).read(cx);
13079 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13080 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13081 }
13082
13083 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13084 self.clear_highlights::<InputComposition>(cx);
13085 self.ime_transaction.take();
13086 }
13087
13088 fn replace_text_in_range(
13089 &mut self,
13090 range_utf16: Option<Range<usize>>,
13091 text: &str,
13092 cx: &mut ViewContext<Self>,
13093 ) {
13094 if !self.input_enabled {
13095 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13096 return;
13097 }
13098
13099 self.transact(cx, |this, cx| {
13100 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13101 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13102 Some(this.selection_replacement_ranges(range_utf16, cx))
13103 } else {
13104 this.marked_text_ranges(cx)
13105 };
13106
13107 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13108 let newest_selection_id = this.selections.newest_anchor().id;
13109 this.selections
13110 .all::<OffsetUtf16>(cx)
13111 .iter()
13112 .zip(ranges_to_replace.iter())
13113 .find_map(|(selection, range)| {
13114 if selection.id == newest_selection_id {
13115 Some(
13116 (range.start.0 as isize - selection.head().0 as isize)
13117 ..(range.end.0 as isize - selection.head().0 as isize),
13118 )
13119 } else {
13120 None
13121 }
13122 })
13123 });
13124
13125 cx.emit(EditorEvent::InputHandled {
13126 utf16_range_to_replace: range_to_replace,
13127 text: text.into(),
13128 });
13129
13130 if let Some(new_selected_ranges) = new_selected_ranges {
13131 this.change_selections(None, cx, |selections| {
13132 selections.select_ranges(new_selected_ranges)
13133 });
13134 this.backspace(&Default::default(), cx);
13135 }
13136
13137 this.handle_input(text, cx);
13138 });
13139
13140 if let Some(transaction) = self.ime_transaction {
13141 self.buffer.update(cx, |buffer, cx| {
13142 buffer.group_until_transaction(transaction, cx);
13143 });
13144 }
13145
13146 self.unmark_text(cx);
13147 }
13148
13149 fn replace_and_mark_text_in_range(
13150 &mut self,
13151 range_utf16: Option<Range<usize>>,
13152 text: &str,
13153 new_selected_range_utf16: Option<Range<usize>>,
13154 cx: &mut ViewContext<Self>,
13155 ) {
13156 if !self.input_enabled {
13157 return;
13158 }
13159
13160 let transaction = self.transact(cx, |this, cx| {
13161 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13162 let snapshot = this.buffer.read(cx).read(cx);
13163 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13164 for marked_range in &mut marked_ranges {
13165 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13166 marked_range.start.0 += relative_range_utf16.start;
13167 marked_range.start =
13168 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13169 marked_range.end =
13170 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13171 }
13172 }
13173 Some(marked_ranges)
13174 } else if let Some(range_utf16) = range_utf16 {
13175 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13176 Some(this.selection_replacement_ranges(range_utf16, cx))
13177 } else {
13178 None
13179 };
13180
13181 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13182 let newest_selection_id = this.selections.newest_anchor().id;
13183 this.selections
13184 .all::<OffsetUtf16>(cx)
13185 .iter()
13186 .zip(ranges_to_replace.iter())
13187 .find_map(|(selection, range)| {
13188 if selection.id == newest_selection_id {
13189 Some(
13190 (range.start.0 as isize - selection.head().0 as isize)
13191 ..(range.end.0 as isize - selection.head().0 as isize),
13192 )
13193 } else {
13194 None
13195 }
13196 })
13197 });
13198
13199 cx.emit(EditorEvent::InputHandled {
13200 utf16_range_to_replace: range_to_replace,
13201 text: text.into(),
13202 });
13203
13204 if let Some(ranges) = ranges_to_replace {
13205 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13206 }
13207
13208 let marked_ranges = {
13209 let snapshot = this.buffer.read(cx).read(cx);
13210 this.selections
13211 .disjoint_anchors()
13212 .iter()
13213 .map(|selection| {
13214 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13215 })
13216 .collect::<Vec<_>>()
13217 };
13218
13219 if text.is_empty() {
13220 this.unmark_text(cx);
13221 } else {
13222 this.highlight_text::<InputComposition>(
13223 marked_ranges.clone(),
13224 HighlightStyle {
13225 underline: Some(UnderlineStyle {
13226 thickness: px(1.),
13227 color: None,
13228 wavy: false,
13229 }),
13230 ..Default::default()
13231 },
13232 cx,
13233 );
13234 }
13235
13236 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13237 let use_autoclose = this.use_autoclose;
13238 let use_auto_surround = this.use_auto_surround;
13239 this.set_use_autoclose(false);
13240 this.set_use_auto_surround(false);
13241 this.handle_input(text, cx);
13242 this.set_use_autoclose(use_autoclose);
13243 this.set_use_auto_surround(use_auto_surround);
13244
13245 if let Some(new_selected_range) = new_selected_range_utf16 {
13246 let snapshot = this.buffer.read(cx).read(cx);
13247 let new_selected_ranges = marked_ranges
13248 .into_iter()
13249 .map(|marked_range| {
13250 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13251 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13252 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13253 snapshot.clip_offset_utf16(new_start, Bias::Left)
13254 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13255 })
13256 .collect::<Vec<_>>();
13257
13258 drop(snapshot);
13259 this.change_selections(None, cx, |selections| {
13260 selections.select_ranges(new_selected_ranges)
13261 });
13262 }
13263 });
13264
13265 self.ime_transaction = self.ime_transaction.or(transaction);
13266 if let Some(transaction) = self.ime_transaction {
13267 self.buffer.update(cx, |buffer, cx| {
13268 buffer.group_until_transaction(transaction, cx);
13269 });
13270 }
13271
13272 if self.text_highlights::<InputComposition>(cx).is_none() {
13273 self.ime_transaction.take();
13274 }
13275 }
13276
13277 fn bounds_for_range(
13278 &mut self,
13279 range_utf16: Range<usize>,
13280 element_bounds: gpui::Bounds<Pixels>,
13281 cx: &mut ViewContext<Self>,
13282 ) -> Option<gpui::Bounds<Pixels>> {
13283 let text_layout_details = self.text_layout_details(cx);
13284 let style = &text_layout_details.editor_style;
13285 let font_id = cx.text_system().resolve_font(&style.text.font());
13286 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13287 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13288
13289 let em_width = cx
13290 .text_system()
13291 .typographic_bounds(font_id, font_size, 'm')
13292 .unwrap()
13293 .size
13294 .width;
13295
13296 let snapshot = self.snapshot(cx);
13297 let scroll_position = snapshot.scroll_position();
13298 let scroll_left = scroll_position.x * em_width;
13299
13300 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13301 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13302 + self.gutter_dimensions.width;
13303 let y = line_height * (start.row().as_f32() - scroll_position.y);
13304
13305 Some(Bounds {
13306 origin: element_bounds.origin + point(x, y),
13307 size: size(em_width, line_height),
13308 })
13309 }
13310}
13311
13312trait SelectionExt {
13313 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13314 fn spanned_rows(
13315 &self,
13316 include_end_if_at_line_start: bool,
13317 map: &DisplaySnapshot,
13318 ) -> Range<MultiBufferRow>;
13319}
13320
13321impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13322 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13323 let start = self
13324 .start
13325 .to_point(&map.buffer_snapshot)
13326 .to_display_point(map);
13327 let end = self
13328 .end
13329 .to_point(&map.buffer_snapshot)
13330 .to_display_point(map);
13331 if self.reversed {
13332 end..start
13333 } else {
13334 start..end
13335 }
13336 }
13337
13338 fn spanned_rows(
13339 &self,
13340 include_end_if_at_line_start: bool,
13341 map: &DisplaySnapshot,
13342 ) -> Range<MultiBufferRow> {
13343 let start = self.start.to_point(&map.buffer_snapshot);
13344 let mut end = self.end.to_point(&map.buffer_snapshot);
13345 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13346 end.row -= 1;
13347 }
13348
13349 let buffer_start = map.prev_line_boundary(start).0;
13350 let buffer_end = map.next_line_boundary(end).0;
13351 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13352 }
13353}
13354
13355impl<T: InvalidationRegion> InvalidationStack<T> {
13356 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13357 where
13358 S: Clone + ToOffset,
13359 {
13360 while let Some(region) = self.last() {
13361 let all_selections_inside_invalidation_ranges =
13362 if selections.len() == region.ranges().len() {
13363 selections
13364 .iter()
13365 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13366 .all(|(selection, invalidation_range)| {
13367 let head = selection.head().to_offset(buffer);
13368 invalidation_range.start <= head && invalidation_range.end >= head
13369 })
13370 } else {
13371 false
13372 };
13373
13374 if all_selections_inside_invalidation_ranges {
13375 break;
13376 } else {
13377 self.pop();
13378 }
13379 }
13380 }
13381}
13382
13383impl<T> Default for InvalidationStack<T> {
13384 fn default() -> Self {
13385 Self(Default::default())
13386 }
13387}
13388
13389impl<T> Deref for InvalidationStack<T> {
13390 type Target = Vec<T>;
13391
13392 fn deref(&self) -> &Self::Target {
13393 &self.0
13394 }
13395}
13396
13397impl<T> DerefMut for InvalidationStack<T> {
13398 fn deref_mut(&mut self) -> &mut Self::Target {
13399 &mut self.0
13400 }
13401}
13402
13403impl InvalidationRegion for SnippetState {
13404 fn ranges(&self) -> &[Range<Anchor>] {
13405 &self.ranges[self.active_index]
13406 }
13407}
13408
13409pub fn diagnostic_block_renderer(
13410 diagnostic: Diagnostic,
13411 max_message_rows: Option<u8>,
13412 allow_closing: bool,
13413 _is_valid: bool,
13414) -> RenderBlock {
13415 let (text_without_backticks, code_ranges) =
13416 highlight_diagnostic_message(&diagnostic, max_message_rows);
13417
13418 Box::new(move |cx: &mut BlockContext| {
13419 let group_id: SharedString = cx.block_id.to_string().into();
13420
13421 let mut text_style = cx.text_style().clone();
13422 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13423 let theme_settings = ThemeSettings::get_global(cx);
13424 text_style.font_family = theme_settings.buffer_font.family.clone();
13425 text_style.font_style = theme_settings.buffer_font.style;
13426 text_style.font_features = theme_settings.buffer_font.features.clone();
13427 text_style.font_weight = theme_settings.buffer_font.weight;
13428
13429 let multi_line_diagnostic = diagnostic.message.contains('\n');
13430
13431 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13432 if multi_line_diagnostic {
13433 v_flex()
13434 } else {
13435 h_flex()
13436 }
13437 .when(allow_closing, |div| {
13438 div.children(diagnostic.is_primary.then(|| {
13439 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13440 .icon_color(Color::Muted)
13441 .size(ButtonSize::Compact)
13442 .style(ButtonStyle::Transparent)
13443 .visible_on_hover(group_id.clone())
13444 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13445 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13446 }))
13447 })
13448 .child(
13449 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13450 .icon_color(Color::Muted)
13451 .size(ButtonSize::Compact)
13452 .style(ButtonStyle::Transparent)
13453 .visible_on_hover(group_id.clone())
13454 .on_click({
13455 let message = diagnostic.message.clone();
13456 move |_click, cx| {
13457 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13458 }
13459 })
13460 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13461 )
13462 };
13463
13464 let icon_size = buttons(&diagnostic, cx.block_id)
13465 .into_any_element()
13466 .layout_as_root(AvailableSpace::min_size(), cx);
13467
13468 h_flex()
13469 .id(cx.block_id)
13470 .group(group_id.clone())
13471 .relative()
13472 .size_full()
13473 .pl(cx.gutter_dimensions.width)
13474 .w(cx.max_width + cx.gutter_dimensions.width)
13475 .child(
13476 div()
13477 .flex()
13478 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13479 .flex_shrink(),
13480 )
13481 .child(buttons(&diagnostic, cx.block_id))
13482 .child(div().flex().flex_shrink_0().child(
13483 StyledText::new(text_without_backticks.clone()).with_highlights(
13484 &text_style,
13485 code_ranges.iter().map(|range| {
13486 (
13487 range.clone(),
13488 HighlightStyle {
13489 font_weight: Some(FontWeight::BOLD),
13490 ..Default::default()
13491 },
13492 )
13493 }),
13494 ),
13495 ))
13496 .into_any_element()
13497 })
13498}
13499
13500pub fn highlight_diagnostic_message(
13501 diagnostic: &Diagnostic,
13502 mut max_message_rows: Option<u8>,
13503) -> (SharedString, Vec<Range<usize>>) {
13504 let mut text_without_backticks = String::new();
13505 let mut code_ranges = Vec::new();
13506
13507 if let Some(source) = &diagnostic.source {
13508 text_without_backticks.push_str(source);
13509 code_ranges.push(0..source.len());
13510 text_without_backticks.push_str(": ");
13511 }
13512
13513 let mut prev_offset = 0;
13514 let mut in_code_block = false;
13515 let has_row_limit = max_message_rows.is_some();
13516 let mut newline_indices = diagnostic
13517 .message
13518 .match_indices('\n')
13519 .filter(|_| has_row_limit)
13520 .map(|(ix, _)| ix)
13521 .fuse()
13522 .peekable();
13523
13524 for (quote_ix, _) in diagnostic
13525 .message
13526 .match_indices('`')
13527 .chain([(diagnostic.message.len(), "")])
13528 {
13529 let mut first_newline_ix = None;
13530 let mut last_newline_ix = None;
13531 while let Some(newline_ix) = newline_indices.peek() {
13532 if *newline_ix < quote_ix {
13533 if first_newline_ix.is_none() {
13534 first_newline_ix = Some(*newline_ix);
13535 }
13536 last_newline_ix = Some(*newline_ix);
13537
13538 if let Some(rows_left) = &mut max_message_rows {
13539 if *rows_left == 0 {
13540 break;
13541 } else {
13542 *rows_left -= 1;
13543 }
13544 }
13545 let _ = newline_indices.next();
13546 } else {
13547 break;
13548 }
13549 }
13550 let prev_len = text_without_backticks.len();
13551 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13552 text_without_backticks.push_str(new_text);
13553 if in_code_block {
13554 code_ranges.push(prev_len..text_without_backticks.len());
13555 }
13556 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13557 in_code_block = !in_code_block;
13558 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13559 text_without_backticks.push_str("...");
13560 break;
13561 }
13562 }
13563
13564 (text_without_backticks.into(), code_ranges)
13565}
13566
13567fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13568 match severity {
13569 DiagnosticSeverity::ERROR => colors.error,
13570 DiagnosticSeverity::WARNING => colors.warning,
13571 DiagnosticSeverity::INFORMATION => colors.info,
13572 DiagnosticSeverity::HINT => colors.info,
13573 _ => colors.ignored,
13574 }
13575}
13576
13577pub fn styled_runs_for_code_label<'a>(
13578 label: &'a CodeLabel,
13579 syntax_theme: &'a theme::SyntaxTheme,
13580) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13581 let fade_out = HighlightStyle {
13582 fade_out: Some(0.35),
13583 ..Default::default()
13584 };
13585
13586 let mut prev_end = label.filter_range.end;
13587 label
13588 .runs
13589 .iter()
13590 .enumerate()
13591 .flat_map(move |(ix, (range, highlight_id))| {
13592 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13593 style
13594 } else {
13595 return Default::default();
13596 };
13597 let mut muted_style = style;
13598 muted_style.highlight(fade_out);
13599
13600 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13601 if range.start >= label.filter_range.end {
13602 if range.start > prev_end {
13603 runs.push((prev_end..range.start, fade_out));
13604 }
13605 runs.push((range.clone(), muted_style));
13606 } else if range.end <= label.filter_range.end {
13607 runs.push((range.clone(), style));
13608 } else {
13609 runs.push((range.start..label.filter_range.end, style));
13610 runs.push((label.filter_range.end..range.end, muted_style));
13611 }
13612 prev_end = cmp::max(prev_end, range.end);
13613
13614 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13615 runs.push((prev_end..label.text.len(), fade_out));
13616 }
13617
13618 runs
13619 })
13620}
13621
13622pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13623 let mut prev_index = 0;
13624 let mut prev_codepoint: Option<char> = None;
13625 text.char_indices()
13626 .chain([(text.len(), '\0')])
13627 .filter_map(move |(index, codepoint)| {
13628 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13629 let is_boundary = index == text.len()
13630 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13631 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13632 if is_boundary {
13633 let chunk = &text[prev_index..index];
13634 prev_index = index;
13635 Some(chunk)
13636 } else {
13637 None
13638 }
13639 })
13640}
13641
13642pub trait RangeToAnchorExt: Sized {
13643 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13644
13645 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13646 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13647 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
13648 }
13649}
13650
13651impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13652 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13653 let start_offset = self.start.to_offset(snapshot);
13654 let end_offset = self.end.to_offset(snapshot);
13655 if start_offset == end_offset {
13656 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13657 } else {
13658 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13659 }
13660 }
13661}
13662
13663pub trait RowExt {
13664 fn as_f32(&self) -> f32;
13665
13666 fn next_row(&self) -> Self;
13667
13668 fn previous_row(&self) -> Self;
13669
13670 fn minus(&self, other: Self) -> u32;
13671}
13672
13673impl RowExt for DisplayRow {
13674 fn as_f32(&self) -> f32 {
13675 self.0 as f32
13676 }
13677
13678 fn next_row(&self) -> Self {
13679 Self(self.0 + 1)
13680 }
13681
13682 fn previous_row(&self) -> Self {
13683 Self(self.0.saturating_sub(1))
13684 }
13685
13686 fn minus(&self, other: Self) -> u32 {
13687 self.0 - other.0
13688 }
13689}
13690
13691impl RowExt for MultiBufferRow {
13692 fn as_f32(&self) -> f32 {
13693 self.0 as f32
13694 }
13695
13696 fn next_row(&self) -> Self {
13697 Self(self.0 + 1)
13698 }
13699
13700 fn previous_row(&self) -> Self {
13701 Self(self.0.saturating_sub(1))
13702 }
13703
13704 fn minus(&self, other: Self) -> u32 {
13705 self.0 - other.0
13706 }
13707}
13708
13709trait RowRangeExt {
13710 type Row;
13711
13712 fn len(&self) -> usize;
13713
13714 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13715}
13716
13717impl RowRangeExt for Range<MultiBufferRow> {
13718 type Row = MultiBufferRow;
13719
13720 fn len(&self) -> usize {
13721 (self.end.0 - self.start.0) as usize
13722 }
13723
13724 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13725 (self.start.0..self.end.0).map(MultiBufferRow)
13726 }
13727}
13728
13729impl RowRangeExt for Range<DisplayRow> {
13730 type Row = DisplayRow;
13731
13732 fn len(&self) -> usize {
13733 (self.end.0 - self.start.0) as usize
13734 }
13735
13736 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13737 (self.start.0..self.end.0).map(DisplayRow)
13738 }
13739}
13740
13741fn hunk_status(hunk: &DiffHunk<MultiBufferRow>) -> DiffHunkStatus {
13742 if hunk.diff_base_byte_range.is_empty() {
13743 DiffHunkStatus::Added
13744 } else if hunk.associated_range.is_empty() {
13745 DiffHunkStatus::Removed
13746 } else {
13747 DiffHunkStatus::Modified
13748 }
13749}
13750
13751/// If select range has more than one line, we
13752/// just point the cursor to range.start.
13753fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13754 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13755 range
13756 } else {
13757 range.start..range.start
13758 }
13759}