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