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