1#![allow(rustdoc::private_intra_doc_links)]
2//! This is the place where everything editor-related is stored (data-wise) and displayed (ui-wise).
3//! The main point of interest in this crate is [`Editor`] type, which is used in every other Zed part as a user input element.
4//! It comes in different flavors: single line, multiline and a fixed height one.
5//!
6//! Editor contains of multiple large submodules:
7//! * [`element`] — the place where all rendering happens
8//! * [`display_map`] - chunks up text in the editor into the logical blocks, establishes coordinates and mapping between each of them.
9//! Contains all metadata related to text transformations (folds, fake inlay text insertions, soft wraps, tab markup, etc.).
10//! * [`inlay_hint_cache`] - is a storage of inlay hints out of LSP requests, responsible for querying LSP and updating `display_map`'s state accordingly.
11//!
12//! All other submodules and structs are mostly concerned with holding editor data about the way it displays current buffer region(s).
13//!
14//! If you're looking to improve Vim mode, you should check out Vim crate that wraps Editor and overrides its behavior.
15pub mod actions;
16mod blame_entry_tooltip;
17mod blink_manager;
18mod clangd_ext;
19mod debounced_delay;
20pub mod display_map;
21mod editor_settings;
22mod editor_settings_controls;
23mod element;
24mod git;
25mod highlight_matching_bracket;
26mod hover_links;
27mod hover_popover;
28mod hunk_diff;
29mod indent_guides;
30mod inlay_hint_cache;
31mod inline_completion_provider;
32pub mod items;
33mod linked_editing_ranges;
34mod lsp_ext;
35mod mouse_context_menu;
36pub mod movement;
37mod persistence;
38mod proposed_changes_editor;
39mod rust_analyzer_ext;
40pub mod scroll;
41mod selections_collection;
42pub mod tasks;
43
44#[cfg(test)]
45mod editor_tests;
46mod signature_help;
47#[cfg(any(test, feature = "test-support"))]
48pub mod test;
49
50use ::git::diff::DiffHunkStatus;
51use ::git::{parse_git_remote_url, BuildPermalinkParams, GitHostingProviderRegistry};
52pub(crate) use actions::*;
53use aho_corasick::AhoCorasick;
54use anyhow::{anyhow, Context as _, Result};
55use blink_manager::BlinkManager;
56use client::{Collaborator, ParticipantIndex};
57use clock::ReplicaId;
58use collections::{BTreeMap, Bound, HashMap, HashSet, VecDeque};
59use convert_case::{Case, Casing};
60use debounced_delay::DebouncedDelay;
61use display_map::*;
62pub use display_map::{DisplayPoint, FoldPlaceholder};
63pub use editor_settings::{
64 CurrentLineHighlight, EditorSettings, ScrollBeyondLastLine, SearchSettings,
65};
66pub use editor_settings_controls::*;
67use element::LineWithInvisibles;
68pub use element::{
69 CursorLayout, EditorElement, HighlightedRange, HighlightedRangeLine, PointForPosition,
70};
71use futures::FutureExt;
72use fuzzy::{StringMatch, StringMatchCandidate};
73use git::blame::GitBlame;
74use git::diff_hunk_to_display;
75use gpui::{
76 div, impl_actions, point, prelude::*, px, relative, size, uniform_list, Action, AnyElement,
77 AppContext, AsyncWindowContext, AvailableSpace, BackgroundExecutor, Bounds, ClipboardEntry,
78 ClipboardItem, Context, DispatchPhase, ElementId, EntityId, EventEmitter, FocusHandle,
79 FocusOutEvent, FocusableView, FontId, FontWeight, HighlightStyle, Hsla, InteractiveText,
80 KeyContext, ListSizingBehavior, Model, MouseButton, PaintQuad, ParentElement, Pixels, Render,
81 SharedString, Size, StrikethroughStyle, Styled, StyledText, Subscription, Task, TextStyle,
82 UTF16Selection, UnderlineStyle, UniformListScrollHandle, View, ViewContext, ViewInputHandler,
83 VisualContext, WeakFocusHandle, WeakView, WindowContext,
84};
85use highlight_matching_bracket::refresh_matching_bracket_highlights;
86use hover_popover::{hide_hover, HoverState};
87use hunk_diff::ExpandedHunks;
88pub(crate) use hunk_diff::HoveredHunk;
89use indent_guides::ActiveIndentGuidesState;
90use inlay_hint_cache::{InlayHintCache, InlaySplice, InvalidationStrategy};
91pub use inline_completion_provider::*;
92pub use items::MAX_TAB_TITLE_LEN;
93use itertools::Itertools;
94use language::{
95 language_settings::{self, all_language_settings, InlayHintSettings},
96 markdown, point_from_lsp, AutoindentMode, BracketPair, Buffer, Capability, CharKind, CodeLabel,
97 CursorShape, Diagnostic, Documentation, IndentKind, IndentSize, Language, OffsetRangeExt,
98 Point, Selection, SelectionGoal, TransactionId,
99};
100use language::{point_to_lsp, BufferRow, CharClassifier, Runnable, RunnableRange};
101use linked_editing_ranges::refresh_linked_ranges;
102use proposed_changes_editor::{ProposedChangesBuffer, ProposedChangesEditor};
103use similar::{ChangeTag, TextDiff};
104use task::{ResolvedTask, TaskTemplate, TaskVariables};
105
106use hover_links::{find_file, HoverLink, HoveredLinkState, InlayHighlight};
107pub use lsp::CompletionContext;
108use lsp::{
109 CompletionItemKind, CompletionTriggerKind, DiagnosticSeverity, InsertTextFormat,
110 LanguageServerId,
111};
112use mouse_context_menu::MouseContextMenu;
113use movement::TextLayoutDetails;
114pub use multi_buffer::{
115 Anchor, AnchorRangeExt, ExcerptId, ExcerptRange, MultiBuffer, MultiBufferSnapshot, ToOffset,
116 ToPoint,
117};
118use multi_buffer::{
119 ExpandExcerptDirection, MultiBufferDiffHunk, MultiBufferPoint, MultiBufferRow, ToOffsetUtf16,
120};
121use ordered_float::OrderedFloat;
122use parking_lot::{Mutex, RwLock};
123use project::project_settings::{GitGutterSetting, ProjectSettings};
124use project::{
125 CodeAction, Completion, CompletionIntent, FormatTrigger, Item, Location, Project, ProjectPath,
126 ProjectTransaction, TaskSourceKind,
127};
128use rand::prelude::*;
129use rpc::{proto::*, ErrorExt};
130use scroll::{Autoscroll, OngoingScroll, ScrollAnchor, ScrollManager, ScrollbarAutoHide};
131use selections_collection::{resolve_multiple, MutableSelectionsCollection, SelectionsCollection};
132use serde::{Deserialize, Serialize};
133use settings::{update_settings_file, Settings, SettingsLocation, SettingsStore};
134use smallvec::SmallVec;
135use snippet::Snippet;
136use std::{
137 any::TypeId,
138 borrow::Cow,
139 cell::RefCell,
140 cmp::{self, Ordering, Reverse},
141 mem,
142 num::NonZeroU32,
143 ops::{ControlFlow, Deref, DerefMut, Not as _, Range, RangeInclusive},
144 path::{Path, PathBuf},
145 rc::Rc,
146 sync::Arc,
147 time::{Duration, Instant},
148};
149pub use sum_tree::Bias;
150use sum_tree::TreeMap;
151use text::{BufferId, OffsetUtf16, Rope};
152use theme::{
153 observe_buffer_font_size_adjustment, ActiveTheme, PlayerColor, StatusColors, SyntaxTheme,
154 ThemeColors, ThemeSettings,
155};
156use ui::{
157 h_flex, prelude::*, ButtonSize, ButtonStyle, Disclosure, IconButton, IconName, IconSize,
158 ListItem, Popover, Tooltip,
159};
160use util::{defer, maybe, post_inc, RangeExt, ResultExt, TryFutureExt};
161use workspace::item::{ItemHandle, PreviewTabsSettings};
162use workspace::notifications::{DetachAndPromptErr, NotificationId};
163use workspace::{
164 searchable::SearchEvent, ItemNavHistory, SplitDirection, ViewId, Workspace, WorkspaceId,
165};
166use workspace::{OpenInTerminal, OpenTerminal, TabBarSettings, Toast};
167
168use crate::hover_links::find_url;
169use crate::signature_help::{SignatureHelpHiddenBy, SignatureHelpState};
170
171pub const FILE_HEADER_HEIGHT: u32 = 1;
172pub const MULTI_BUFFER_EXCERPT_HEADER_HEIGHT: u32 = 1;
173pub const MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT: u32 = 1;
174pub const DEFAULT_MULTIBUFFER_CONTEXT: u32 = 2;
175const CURSOR_BLINK_INTERVAL: Duration = Duration::from_millis(500);
176const MAX_LINE_LEN: usize = 1024;
177const MIN_NAVIGATION_HISTORY_ROW_DELTA: i64 = 10;
178const MAX_SELECTION_HISTORY_LEN: usize = 1024;
179pub(crate) const CURSORS_VISIBLE_FOR: Duration = Duration::from_millis(2000);
180#[doc(hidden)]
181pub const CODE_ACTIONS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(250);
182#[doc(hidden)]
183pub const DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT: Duration = Duration::from_millis(75);
184
185pub(crate) const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
186pub(crate) const SCROLL_CENTER_TOP_BOTTOM_DEBOUNCE_TIMEOUT: Duration = Duration::from_secs(1);
187
188pub fn render_parsed_markdown(
189 element_id: impl Into<ElementId>,
190 parsed: &language::ParsedMarkdown,
191 editor_style: &EditorStyle,
192 workspace: Option<WeakView<Workspace>>,
193 cx: &mut WindowContext,
194) -> InteractiveText {
195 let code_span_background_color = cx
196 .theme()
197 .colors()
198 .editor_document_highlight_read_background;
199
200 let highlights = gpui::combine_highlights(
201 parsed.highlights.iter().filter_map(|(range, highlight)| {
202 let highlight = highlight.to_highlight_style(&editor_style.syntax)?;
203 Some((range.clone(), highlight))
204 }),
205 parsed
206 .regions
207 .iter()
208 .zip(&parsed.region_ranges)
209 .filter_map(|(region, range)| {
210 if region.code {
211 Some((
212 range.clone(),
213 HighlightStyle {
214 background_color: Some(code_span_background_color),
215 ..Default::default()
216 },
217 ))
218 } else {
219 None
220 }
221 }),
222 );
223
224 let mut links = Vec::new();
225 let mut link_ranges = Vec::new();
226 for (range, region) in parsed.region_ranges.iter().zip(&parsed.regions) {
227 if let Some(link) = region.link.clone() {
228 links.push(link);
229 link_ranges.push(range.clone());
230 }
231 }
232
233 InteractiveText::new(
234 element_id,
235 StyledText::new(parsed.text.clone()).with_highlights(&editor_style.text, highlights),
236 )
237 .on_click(link_ranges, move |clicked_range_ix, cx| {
238 match &links[clicked_range_ix] {
239 markdown::Link::Web { url } => cx.open_url(url),
240 markdown::Link::Path { path } => {
241 if let Some(workspace) = &workspace {
242 _ = workspace.update(cx, |workspace, cx| {
243 workspace.open_abs_path(path.clone(), false, cx).detach();
244 });
245 }
246 }
247 }
248 })
249}
250
251#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
252pub(crate) enum InlayId {
253 Suggestion(usize),
254 Hint(usize),
255}
256
257impl InlayId {
258 fn id(&self) -> usize {
259 match self {
260 Self::Suggestion(id) => *id,
261 Self::Hint(id) => *id,
262 }
263 }
264}
265
266enum DiffRowHighlight {}
267enum DocumentHighlightRead {}
268enum DocumentHighlightWrite {}
269enum InputComposition {}
270
271#[derive(Copy, Clone, PartialEq, Eq)]
272pub enum Direction {
273 Prev,
274 Next,
275}
276
277#[derive(Debug, Copy, Clone, PartialEq, Eq)]
278pub enum Navigated {
279 Yes,
280 No,
281}
282
283impl Navigated {
284 pub fn from_bool(yes: bool) -> Navigated {
285 if yes {
286 Navigated::Yes
287 } else {
288 Navigated::No
289 }
290 }
291}
292
293pub fn init_settings(cx: &mut AppContext) {
294 EditorSettings::register(cx);
295}
296
297pub fn init(cx: &mut AppContext) {
298 init_settings(cx);
299
300 workspace::register_project_item::<Editor>(cx);
301 workspace::FollowableViewRegistry::register::<Editor>(cx);
302 workspace::register_serializable_item::<Editor>(cx);
303
304 cx.observe_new_views(
305 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
306 workspace.register_action(Editor::new_file);
307 workspace.register_action(Editor::new_file_vertical);
308 workspace.register_action(Editor::new_file_horizontal);
309 },
310 )
311 .detach();
312
313 cx.on_action(move |_: &workspace::NewFile, cx| {
314 let app_state = workspace::AppState::global(cx);
315 if let Some(app_state) = app_state.upgrade() {
316 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
317 Editor::new_file(workspace, &Default::default(), cx)
318 })
319 .detach();
320 }
321 });
322 cx.on_action(move |_: &workspace::NewWindow, cx| {
323 let app_state = workspace::AppState::global(cx);
324 if let Some(app_state) = app_state.upgrade() {
325 workspace::open_new(Default::default(), app_state, cx, |workspace, cx| {
326 Editor::new_file(workspace, &Default::default(), cx)
327 })
328 .detach();
329 }
330 });
331}
332
333pub struct SearchWithinRange;
334
335trait InvalidationRegion {
336 fn ranges(&self) -> &[Range<Anchor>];
337}
338
339#[derive(Clone, Debug, PartialEq)]
340pub enum SelectPhase {
341 Begin {
342 position: DisplayPoint,
343 add: bool,
344 click_count: usize,
345 },
346 BeginColumnar {
347 position: DisplayPoint,
348 reset: bool,
349 goal_column: u32,
350 },
351 Extend {
352 position: DisplayPoint,
353 click_count: usize,
354 },
355 Update {
356 position: DisplayPoint,
357 goal_column: u32,
358 scroll_delta: gpui::Point<f32>,
359 },
360 End,
361}
362
363#[derive(Clone, Debug)]
364pub enum SelectMode {
365 Character,
366 Word(Range<Anchor>),
367 Line(Range<Anchor>),
368 All,
369}
370
371#[derive(Copy, Clone, PartialEq, Eq, Debug)]
372pub enum EditorMode {
373 SingleLine { auto_width: bool },
374 AutoHeight { max_lines: usize },
375 Full,
376}
377
378#[derive(Clone, Debug)]
379pub enum SoftWrap {
380 None,
381 PreferLine,
382 EditorWidth,
383 Column(u32),
384 Bounded(u32),
385}
386
387#[derive(Clone)]
388pub struct EditorStyle {
389 pub background: Hsla,
390 pub local_player: PlayerColor,
391 pub text: TextStyle,
392 pub scrollbar_width: Pixels,
393 pub syntax: Arc<SyntaxTheme>,
394 pub status: StatusColors,
395 pub inlay_hints_style: HighlightStyle,
396 pub suggestions_style: HighlightStyle,
397 pub unnecessary_code_fade: f32,
398}
399
400impl Default for EditorStyle {
401 fn default() -> Self {
402 Self {
403 background: Hsla::default(),
404 local_player: PlayerColor::default(),
405 text: TextStyle::default(),
406 scrollbar_width: Pixels::default(),
407 syntax: Default::default(),
408 // HACK: Status colors don't have a real default.
409 // We should look into removing the status colors from the editor
410 // style and retrieve them directly from the theme.
411 status: StatusColors::dark(),
412 inlay_hints_style: HighlightStyle::default(),
413 suggestions_style: HighlightStyle::default(),
414 unnecessary_code_fade: Default::default(),
415 }
416 }
417}
418
419pub fn make_inlay_hints_style(cx: &WindowContext) -> HighlightStyle {
420 let show_background = all_language_settings(None, cx)
421 .language(None)
422 .inlay_hints
423 .show_background;
424
425 HighlightStyle {
426 color: Some(cx.theme().status().hint),
427 background_color: show_background.then(|| cx.theme().status().hint_background),
428 ..HighlightStyle::default()
429 }
430}
431
432type CompletionId = usize;
433
434#[derive(Clone, Debug)]
435struct CompletionState {
436 // render_inlay_ids represents the inlay hints that are inserted
437 // for rendering the inline completions. They may be discontinuous
438 // in the event that the completion provider returns some intersection
439 // with the existing content.
440 render_inlay_ids: Vec<InlayId>,
441 // text is the resulting rope that is inserted when the user accepts a completion.
442 text: Rope,
443 // position is the position of the cursor when the completion was triggered.
444 position: multi_buffer::Anchor,
445 // delete_range is the range of text that this completion state covers.
446 // if the completion is accepted, this range should be deleted.
447 delete_range: Option<Range<multi_buffer::Anchor>>,
448}
449
450#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Default)]
451struct EditorActionId(usize);
452
453impl EditorActionId {
454 pub fn post_inc(&mut self) -> Self {
455 let answer = self.0;
456
457 *self = Self(answer + 1);
458
459 Self(answer)
460 }
461}
462
463// type GetFieldEditorTheme = dyn Fn(&theme::Theme) -> theme::FieldEditor;
464// type OverrideTextStyle = dyn Fn(&EditorStyle) -> Option<HighlightStyle>;
465
466type BackgroundHighlight = (fn(&ThemeColors) -> Hsla, Arc<[Range<Anchor>]>);
467type GutterHighlight = (fn(&AppContext) -> Hsla, Arc<[Range<Anchor>]>);
468
469#[derive(Default)]
470struct ScrollbarMarkerState {
471 scrollbar_size: Size<Pixels>,
472 dirty: bool,
473 markers: Arc<[PaintQuad]>,
474 pending_refresh: Option<Task<Result<()>>>,
475}
476
477impl ScrollbarMarkerState {
478 fn should_refresh(&self, scrollbar_size: Size<Pixels>) -> bool {
479 self.pending_refresh.is_none() && (self.scrollbar_size != scrollbar_size || self.dirty)
480 }
481}
482
483#[derive(Clone, Debug)]
484struct RunnableTasks {
485 templates: Vec<(TaskSourceKind, TaskTemplate)>,
486 offset: MultiBufferOffset,
487 // We need the column at which the task context evaluation should take place (when we're spawning it via gutter).
488 column: u32,
489 // Values of all named captures, including those starting with '_'
490 extra_variables: HashMap<String, String>,
491 // Full range of the tagged region. We use it to determine which `extra_variables` to grab for context resolution in e.g. a modal.
492 context_range: Range<BufferOffset>,
493}
494
495#[derive(Clone)]
496struct ResolvedTasks {
497 templates: SmallVec<[(TaskSourceKind, ResolvedTask); 1]>,
498 position: Anchor,
499}
500#[derive(Copy, Clone, Debug)]
501struct MultiBufferOffset(usize);
502#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
503struct BufferOffset(usize);
504
505// Addons allow storing per-editor state in other crates (e.g. Vim)
506pub trait Addon: 'static {
507 fn extend_key_context(&self, _: &mut KeyContext, _: &AppContext) {}
508
509 fn to_any(&self) -> &dyn std::any::Any;
510}
511
512/// Zed's primary text input `View`, allowing users to edit a [`MultiBuffer`]
513///
514/// See the [module level documentation](self) for more information.
515pub struct Editor {
516 focus_handle: FocusHandle,
517 last_focused_descendant: Option<WeakFocusHandle>,
518 /// The text buffer being edited
519 buffer: Model<MultiBuffer>,
520 /// Map of how text in the buffer should be displayed.
521 /// Handles soft wraps, folds, fake inlay text insertions, etc.
522 pub display_map: Model<DisplayMap>,
523 pub selections: SelectionsCollection,
524 pub scroll_manager: ScrollManager,
525 /// When inline assist editors are linked, they all render cursors because
526 /// typing enters text into each of them, even the ones that aren't focused.
527 pub(crate) show_cursor_when_unfocused: bool,
528 columnar_selection_tail: Option<Anchor>,
529 add_selections_state: Option<AddSelectionsState>,
530 select_next_state: Option<SelectNextState>,
531 select_prev_state: Option<SelectNextState>,
532 selection_history: SelectionHistory,
533 autoclose_regions: Vec<AutocloseRegion>,
534 snippet_stack: InvalidationStack<SnippetState>,
535 select_larger_syntax_node_stack: Vec<Box<[Selection<usize>]>>,
536 ime_transaction: Option<TransactionId>,
537 active_diagnostics: Option<ActiveDiagnosticGroup>,
538 soft_wrap_mode_override: Option<language_settings::SoftWrap>,
539 project: Option<Model<Project>>,
540 completion_provider: Option<Box<dyn CompletionProvider>>,
541 collaboration_hub: Option<Box<dyn CollaborationHub>>,
542 blink_manager: Model<BlinkManager>,
543 show_cursor_names: bool,
544 hovered_cursors: HashMap<HoveredCursor, Task<()>>,
545 pub show_local_selections: bool,
546 mode: EditorMode,
547 show_breadcrumbs: bool,
548 show_gutter: bool,
549 show_line_numbers: Option<bool>,
550 use_relative_line_numbers: Option<bool>,
551 show_git_diff_gutter: Option<bool>,
552 show_code_actions: Option<bool>,
553 show_runnables: Option<bool>,
554 show_wrap_guides: Option<bool>,
555 show_indent_guides: Option<bool>,
556 placeholder_text: Option<Arc<str>>,
557 highlight_order: usize,
558 highlighted_rows: HashMap<TypeId, Vec<RowHighlight>>,
559 background_highlights: TreeMap<TypeId, BackgroundHighlight>,
560 gutter_highlights: TreeMap<TypeId, GutterHighlight>,
561 scrollbar_marker_state: ScrollbarMarkerState,
562 active_indent_guides_state: ActiveIndentGuidesState,
563 nav_history: Option<ItemNavHistory>,
564 context_menu: RwLock<Option<ContextMenu>>,
565 mouse_context_menu: Option<MouseContextMenu>,
566 completion_tasks: Vec<(CompletionId, Task<Option<()>>)>,
567 signature_help_state: SignatureHelpState,
568 auto_signature_help: Option<bool>,
569 find_all_references_task_sources: Vec<Anchor>,
570 next_completion_id: CompletionId,
571 completion_documentation_pre_resolve_debounce: DebouncedDelay,
572 available_code_actions: Option<(Location, Arc<[CodeAction]>)>,
573 code_actions_task: Option<Task<()>>,
574 document_highlights_task: Option<Task<()>>,
575 linked_editing_range_task: Option<Task<Option<()>>>,
576 linked_edit_ranges: linked_editing_ranges::LinkedEditingRanges,
577 pending_rename: Option<RenameState>,
578 searchable: bool,
579 cursor_shape: CursorShape,
580 current_line_highlight: Option<CurrentLineHighlight>,
581 collapse_matches: bool,
582 autoindent_mode: Option<AutoindentMode>,
583 workspace: Option<(WeakView<Workspace>, Option<WorkspaceId>)>,
584 input_enabled: bool,
585 use_modal_editing: bool,
586 read_only: bool,
587 leader_peer_id: Option<PeerId>,
588 remote_id: Option<ViewId>,
589 hover_state: HoverState,
590 gutter_hovered: bool,
591 hovered_link_state: Option<HoveredLinkState>,
592 inline_completion_provider: Option<RegisteredInlineCompletionProvider>,
593 active_inline_completion: Option<CompletionState>,
594 // enable_inline_completions is a switch that Vim can use to disable
595 // inline completions based on its mode.
596 enable_inline_completions: bool,
597 show_inline_completions_override: Option<bool>,
598 inlay_hint_cache: InlayHintCache,
599 expanded_hunks: ExpandedHunks,
600 next_inlay_id: usize,
601 _subscriptions: Vec<Subscription>,
602 pixel_position_of_newest_cursor: Option<gpui::Point<Pixels>>,
603 gutter_dimensions: GutterDimensions,
604 style: Option<EditorStyle>,
605 next_editor_action_id: EditorActionId,
606 editor_actions: Rc<RefCell<BTreeMap<EditorActionId, Box<dyn Fn(&mut ViewContext<Self>)>>>>,
607 use_autoclose: bool,
608 use_auto_surround: bool,
609 auto_replace_emoji_shortcode: bool,
610 show_git_blame_gutter: bool,
611 show_git_blame_inline: bool,
612 show_git_blame_inline_delay_task: Option<Task<()>>,
613 git_blame_inline_enabled: bool,
614 serialize_dirty_buffers: bool,
615 show_selection_menu: Option<bool>,
616 blame: Option<Model<GitBlame>>,
617 blame_subscription: Option<Subscription>,
618 custom_context_menu: Option<
619 Box<
620 dyn 'static
621 + Fn(&mut Self, DisplayPoint, &mut ViewContext<Self>) -> Option<View<ui::ContextMenu>>,
622 >,
623 >,
624 last_bounds: Option<Bounds<Pixels>>,
625 expect_bounds_change: Option<Bounds<Pixels>>,
626 tasks: BTreeMap<(BufferId, BufferRow), RunnableTasks>,
627 tasks_update_task: Option<Task<()>>,
628 previous_search_ranges: Option<Arc<[Range<Anchor>]>>,
629 file_header_size: u32,
630 breadcrumb_header: Option<String>,
631 focused_block: Option<FocusedBlock>,
632 next_scroll_position: NextScrollCursorCenterTopBottom,
633 addons: HashMap<TypeId, Box<dyn Addon>>,
634 _scroll_cursor_center_top_bottom_task: Task<()>,
635}
636
637#[derive(Copy, Clone, Debug, PartialEq, Eq, Default)]
638enum NextScrollCursorCenterTopBottom {
639 #[default]
640 Center,
641 Top,
642 Bottom,
643}
644
645impl NextScrollCursorCenterTopBottom {
646 fn next(&self) -> Self {
647 match self {
648 Self::Center => Self::Top,
649 Self::Top => Self::Bottom,
650 Self::Bottom => Self::Center,
651 }
652 }
653}
654
655#[derive(Clone)]
656pub struct EditorSnapshot {
657 pub mode: EditorMode,
658 show_gutter: bool,
659 show_line_numbers: Option<bool>,
660 show_git_diff_gutter: Option<bool>,
661 show_code_actions: Option<bool>,
662 show_runnables: Option<bool>,
663 render_git_blame_gutter: bool,
664 pub display_snapshot: DisplaySnapshot,
665 pub placeholder_text: Option<Arc<str>>,
666 is_focused: bool,
667 scroll_anchor: ScrollAnchor,
668 ongoing_scroll: OngoingScroll,
669 current_line_highlight: CurrentLineHighlight,
670 gutter_hovered: bool,
671}
672
673const GIT_BLAME_GUTTER_WIDTH_CHARS: f32 = 53.;
674
675#[derive(Default, Debug, Clone, Copy)]
676pub struct GutterDimensions {
677 pub left_padding: Pixels,
678 pub right_padding: Pixels,
679 pub width: Pixels,
680 pub margin: Pixels,
681 pub git_blame_entries_width: Option<Pixels>,
682}
683
684impl GutterDimensions {
685 /// The full width of the space taken up by the gutter.
686 pub fn full_width(&self) -> Pixels {
687 self.margin + self.width
688 }
689
690 /// The width of the space reserved for the fold indicators,
691 /// use alongside 'justify_end' and `gutter_width` to
692 /// right align content with the line numbers
693 pub fn fold_area_width(&self) -> Pixels {
694 self.margin + self.right_padding
695 }
696}
697
698#[derive(Debug)]
699pub struct RemoteSelection {
700 pub replica_id: ReplicaId,
701 pub selection: Selection<Anchor>,
702 pub cursor_shape: CursorShape,
703 pub peer_id: PeerId,
704 pub line_mode: bool,
705 pub participant_index: Option<ParticipantIndex>,
706 pub user_name: Option<SharedString>,
707}
708
709#[derive(Clone, Debug)]
710struct SelectionHistoryEntry {
711 selections: Arc<[Selection<Anchor>]>,
712 select_next_state: Option<SelectNextState>,
713 select_prev_state: Option<SelectNextState>,
714 add_selections_state: Option<AddSelectionsState>,
715}
716
717enum SelectionHistoryMode {
718 Normal,
719 Undoing,
720 Redoing,
721}
722
723#[derive(Clone, PartialEq, Eq, Hash)]
724struct HoveredCursor {
725 replica_id: u16,
726 selection_id: usize,
727}
728
729impl Default for SelectionHistoryMode {
730 fn default() -> Self {
731 Self::Normal
732 }
733}
734
735#[derive(Default)]
736struct SelectionHistory {
737 #[allow(clippy::type_complexity)]
738 selections_by_transaction:
739 HashMap<TransactionId, (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)>,
740 mode: SelectionHistoryMode,
741 undo_stack: VecDeque<SelectionHistoryEntry>,
742 redo_stack: VecDeque<SelectionHistoryEntry>,
743}
744
745impl SelectionHistory {
746 fn insert_transaction(
747 &mut self,
748 transaction_id: TransactionId,
749 selections: Arc<[Selection<Anchor>]>,
750 ) {
751 self.selections_by_transaction
752 .insert(transaction_id, (selections, None));
753 }
754
755 #[allow(clippy::type_complexity)]
756 fn transaction(
757 &self,
758 transaction_id: TransactionId,
759 ) -> Option<&(Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
760 self.selections_by_transaction.get(&transaction_id)
761 }
762
763 #[allow(clippy::type_complexity)]
764 fn transaction_mut(
765 &mut self,
766 transaction_id: TransactionId,
767 ) -> Option<&mut (Arc<[Selection<Anchor>]>, Option<Arc<[Selection<Anchor>]>>)> {
768 self.selections_by_transaction.get_mut(&transaction_id)
769 }
770
771 fn push(&mut self, entry: SelectionHistoryEntry) {
772 if !entry.selections.is_empty() {
773 match self.mode {
774 SelectionHistoryMode::Normal => {
775 self.push_undo(entry);
776 self.redo_stack.clear();
777 }
778 SelectionHistoryMode::Undoing => self.push_redo(entry),
779 SelectionHistoryMode::Redoing => self.push_undo(entry),
780 }
781 }
782 }
783
784 fn push_undo(&mut self, entry: SelectionHistoryEntry) {
785 if self
786 .undo_stack
787 .back()
788 .map_or(true, |e| e.selections != entry.selections)
789 {
790 self.undo_stack.push_back(entry);
791 if self.undo_stack.len() > MAX_SELECTION_HISTORY_LEN {
792 self.undo_stack.pop_front();
793 }
794 }
795 }
796
797 fn push_redo(&mut self, entry: SelectionHistoryEntry) {
798 if self
799 .redo_stack
800 .back()
801 .map_or(true, |e| e.selections != entry.selections)
802 {
803 self.redo_stack.push_back(entry);
804 if self.redo_stack.len() > MAX_SELECTION_HISTORY_LEN {
805 self.redo_stack.pop_front();
806 }
807 }
808 }
809}
810
811struct RowHighlight {
812 index: usize,
813 range: RangeInclusive<Anchor>,
814 color: Option<Hsla>,
815 should_autoscroll: bool,
816}
817
818#[derive(Clone, Debug)]
819struct AddSelectionsState {
820 above: bool,
821 stack: Vec<usize>,
822}
823
824#[derive(Clone)]
825struct SelectNextState {
826 query: AhoCorasick,
827 wordwise: bool,
828 done: bool,
829}
830
831impl std::fmt::Debug for SelectNextState {
832 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
833 f.debug_struct(std::any::type_name::<Self>())
834 .field("wordwise", &self.wordwise)
835 .field("done", &self.done)
836 .finish()
837 }
838}
839
840#[derive(Debug)]
841struct AutocloseRegion {
842 selection_id: usize,
843 range: Range<Anchor>,
844 pair: BracketPair,
845}
846
847#[derive(Debug)]
848struct SnippetState {
849 ranges: Vec<Vec<Range<Anchor>>>,
850 active_index: usize,
851}
852
853#[doc(hidden)]
854pub struct RenameState {
855 pub range: Range<Anchor>,
856 pub old_name: Arc<str>,
857 pub editor: View<Editor>,
858 block_id: CustomBlockId,
859}
860
861struct InvalidationStack<T>(Vec<T>);
862
863struct RegisteredInlineCompletionProvider {
864 provider: Arc<dyn InlineCompletionProviderHandle>,
865 _subscription: Subscription,
866}
867
868enum ContextMenu {
869 Completions(CompletionsMenu),
870 CodeActions(CodeActionsMenu),
871}
872
873impl ContextMenu {
874 fn select_first(
875 &mut self,
876 project: Option<&Model<Project>>,
877 cx: &mut ViewContext<Editor>,
878 ) -> bool {
879 if self.visible() {
880 match self {
881 ContextMenu::Completions(menu) => menu.select_first(project, cx),
882 ContextMenu::CodeActions(menu) => menu.select_first(cx),
883 }
884 true
885 } else {
886 false
887 }
888 }
889
890 fn select_prev(
891 &mut self,
892 project: Option<&Model<Project>>,
893 cx: &mut ViewContext<Editor>,
894 ) -> bool {
895 if self.visible() {
896 match self {
897 ContextMenu::Completions(menu) => menu.select_prev(project, cx),
898 ContextMenu::CodeActions(menu) => menu.select_prev(cx),
899 }
900 true
901 } else {
902 false
903 }
904 }
905
906 fn select_next(
907 &mut self,
908 project: Option<&Model<Project>>,
909 cx: &mut ViewContext<Editor>,
910 ) -> bool {
911 if self.visible() {
912 match self {
913 ContextMenu::Completions(menu) => menu.select_next(project, cx),
914 ContextMenu::CodeActions(menu) => menu.select_next(cx),
915 }
916 true
917 } else {
918 false
919 }
920 }
921
922 fn select_last(
923 &mut self,
924 project: Option<&Model<Project>>,
925 cx: &mut ViewContext<Editor>,
926 ) -> bool {
927 if self.visible() {
928 match self {
929 ContextMenu::Completions(menu) => menu.select_last(project, cx),
930 ContextMenu::CodeActions(menu) => menu.select_last(cx),
931 }
932 true
933 } else {
934 false
935 }
936 }
937
938 fn visible(&self) -> bool {
939 match self {
940 ContextMenu::Completions(menu) => menu.visible(),
941 ContextMenu::CodeActions(menu) => menu.visible(),
942 }
943 }
944
945 fn render(
946 &self,
947 cursor_position: DisplayPoint,
948 style: &EditorStyle,
949 max_height: Pixels,
950 workspace: Option<WeakView<Workspace>>,
951 cx: &mut ViewContext<Editor>,
952 ) -> (ContextMenuOrigin, AnyElement) {
953 match self {
954 ContextMenu::Completions(menu) => (
955 ContextMenuOrigin::EditorPoint(cursor_position),
956 menu.render(style, max_height, workspace, cx),
957 ),
958 ContextMenu::CodeActions(menu) => menu.render(cursor_position, style, max_height, cx),
959 }
960 }
961}
962
963enum ContextMenuOrigin {
964 EditorPoint(DisplayPoint),
965 GutterIndicator(DisplayRow),
966}
967
968#[derive(Clone)]
969struct CompletionsMenu {
970 id: CompletionId,
971 sort_completions: bool,
972 initial_position: Anchor,
973 buffer: Model<Buffer>,
974 completions: Arc<RwLock<Box<[Completion]>>>,
975 match_candidates: Arc<[StringMatchCandidate]>,
976 matches: Arc<[StringMatch]>,
977 selected_item: usize,
978 scroll_handle: UniformListScrollHandle,
979 selected_completion_documentation_resolve_debounce: Arc<Mutex<DebouncedDelay>>,
980}
981
982impl CompletionsMenu {
983 fn select_first(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
984 self.selected_item = 0;
985 self.scroll_handle.scroll_to_item(self.selected_item);
986 self.attempt_resolve_selected_completion_documentation(project, cx);
987 cx.notify();
988 }
989
990 fn select_prev(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
991 if self.selected_item > 0 {
992 self.selected_item -= 1;
993 } else {
994 self.selected_item = self.matches.len() - 1;
995 }
996 self.scroll_handle.scroll_to_item(self.selected_item);
997 self.attempt_resolve_selected_completion_documentation(project, cx);
998 cx.notify();
999 }
1000
1001 fn select_next(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
1002 if self.selected_item + 1 < self.matches.len() {
1003 self.selected_item += 1;
1004 } else {
1005 self.selected_item = 0;
1006 }
1007 self.scroll_handle.scroll_to_item(self.selected_item);
1008 self.attempt_resolve_selected_completion_documentation(project, cx);
1009 cx.notify();
1010 }
1011
1012 fn select_last(&mut self, project: Option<&Model<Project>>, cx: &mut ViewContext<Editor>) {
1013 self.selected_item = self.matches.len() - 1;
1014 self.scroll_handle.scroll_to_item(self.selected_item);
1015 self.attempt_resolve_selected_completion_documentation(project, cx);
1016 cx.notify();
1017 }
1018
1019 fn pre_resolve_completion_documentation(
1020 buffer: Model<Buffer>,
1021 completions: Arc<RwLock<Box<[Completion]>>>,
1022 matches: Arc<[StringMatch]>,
1023 editor: &Editor,
1024 cx: &mut ViewContext<Editor>,
1025 ) -> Task<()> {
1026 let settings = EditorSettings::get_global(cx);
1027 if !settings.show_completion_documentation {
1028 return Task::ready(());
1029 }
1030
1031 let Some(provider) = editor.completion_provider.as_ref() else {
1032 return Task::ready(());
1033 };
1034
1035 let resolve_task = provider.resolve_completions(
1036 buffer,
1037 matches.iter().map(|m| m.candidate_id).collect(),
1038 completions.clone(),
1039 cx,
1040 );
1041
1042 cx.spawn(move |this, mut cx| async move {
1043 if let Some(true) = resolve_task.await.log_err() {
1044 this.update(&mut cx, |_, cx| cx.notify()).ok();
1045 }
1046 })
1047 }
1048
1049 fn attempt_resolve_selected_completion_documentation(
1050 &mut self,
1051 project: Option<&Model<Project>>,
1052 cx: &mut ViewContext<Editor>,
1053 ) {
1054 let settings = EditorSettings::get_global(cx);
1055 if !settings.show_completion_documentation {
1056 return;
1057 }
1058
1059 let completion_index = self.matches[self.selected_item].candidate_id;
1060 let Some(project) = project else {
1061 return;
1062 };
1063
1064 let resolve_task = project.update(cx, |project, cx| {
1065 project.resolve_completions(
1066 self.buffer.clone(),
1067 vec![completion_index],
1068 self.completions.clone(),
1069 cx,
1070 )
1071 });
1072
1073 let delay_ms =
1074 EditorSettings::get_global(cx).completion_documentation_secondary_query_debounce;
1075 let delay = Duration::from_millis(delay_ms);
1076
1077 self.selected_completion_documentation_resolve_debounce
1078 .lock()
1079 .fire_new(delay, cx, |_, cx| {
1080 cx.spawn(move |this, mut cx| async move {
1081 if let Some(true) = resolve_task.await.log_err() {
1082 this.update(&mut cx, |_, cx| cx.notify()).ok();
1083 }
1084 })
1085 });
1086 }
1087
1088 fn visible(&self) -> bool {
1089 !self.matches.is_empty()
1090 }
1091
1092 fn render(
1093 &self,
1094 style: &EditorStyle,
1095 max_height: Pixels,
1096 workspace: Option<WeakView<Workspace>>,
1097 cx: &mut ViewContext<Editor>,
1098 ) -> AnyElement {
1099 let settings = EditorSettings::get_global(cx);
1100 let show_completion_documentation = settings.show_completion_documentation;
1101
1102 let widest_completion_ix = self
1103 .matches
1104 .iter()
1105 .enumerate()
1106 .max_by_key(|(_, mat)| {
1107 let completions = self.completions.read();
1108 let completion = &completions[mat.candidate_id];
1109 let documentation = &completion.documentation;
1110
1111 let mut len = completion.label.text.chars().count();
1112 if let Some(Documentation::SingleLine(text)) = documentation {
1113 if show_completion_documentation {
1114 len += text.chars().count();
1115 }
1116 }
1117
1118 len
1119 })
1120 .map(|(ix, _)| ix);
1121
1122 let completions = self.completions.clone();
1123 let matches = self.matches.clone();
1124 let selected_item = self.selected_item;
1125 let style = style.clone();
1126
1127 let multiline_docs = if show_completion_documentation {
1128 let mat = &self.matches[selected_item];
1129 let multiline_docs = match &self.completions.read()[mat.candidate_id].documentation {
1130 Some(Documentation::MultiLinePlainText(text)) => {
1131 Some(div().child(SharedString::from(text.clone())))
1132 }
1133 Some(Documentation::MultiLineMarkdown(parsed)) if !parsed.text.is_empty() => {
1134 Some(div().child(render_parsed_markdown(
1135 "completions_markdown",
1136 parsed,
1137 &style,
1138 workspace,
1139 cx,
1140 )))
1141 }
1142 _ => None,
1143 };
1144 multiline_docs.map(|div| {
1145 div.id("multiline_docs")
1146 .max_h(max_height)
1147 .flex_1()
1148 .px_1p5()
1149 .py_1()
1150 .min_w(px(260.))
1151 .max_w(px(640.))
1152 .w(px(500.))
1153 .overflow_y_scroll()
1154 .occlude()
1155 })
1156 } else {
1157 None
1158 };
1159
1160 let list = uniform_list(
1161 cx.view().clone(),
1162 "completions",
1163 matches.len(),
1164 move |_editor, range, cx| {
1165 let start_ix = range.start;
1166 let completions_guard = completions.read();
1167
1168 matches[range]
1169 .iter()
1170 .enumerate()
1171 .map(|(ix, mat)| {
1172 let item_ix = start_ix + ix;
1173 let candidate_id = mat.candidate_id;
1174 let completion = &completions_guard[candidate_id];
1175
1176 let documentation = if show_completion_documentation {
1177 &completion.documentation
1178 } else {
1179 &None
1180 };
1181
1182 let highlights = gpui::combine_highlights(
1183 mat.ranges().map(|range| (range, FontWeight::BOLD.into())),
1184 styled_runs_for_code_label(&completion.label, &style.syntax).map(
1185 |(range, mut highlight)| {
1186 // Ignore font weight for syntax highlighting, as we'll use it
1187 // for fuzzy matches.
1188 highlight.font_weight = None;
1189
1190 if completion.lsp_completion.deprecated.unwrap_or(false) {
1191 highlight.strikethrough = Some(StrikethroughStyle {
1192 thickness: 1.0.into(),
1193 ..Default::default()
1194 });
1195 highlight.color = Some(cx.theme().colors().text_muted);
1196 }
1197
1198 (range, highlight)
1199 },
1200 ),
1201 );
1202 let completion_label = StyledText::new(completion.label.text.clone())
1203 .with_highlights(&style.text, highlights);
1204 let documentation_label =
1205 if let Some(Documentation::SingleLine(text)) = documentation {
1206 if text.trim().is_empty() {
1207 None
1208 } else {
1209 Some(
1210 Label::new(text.clone())
1211 .ml_4()
1212 .size(LabelSize::Small)
1213 .color(Color::Muted),
1214 )
1215 }
1216 } else {
1217 None
1218 };
1219
1220 div().min_w(px(220.)).max_w(px(540.)).child(
1221 ListItem::new(mat.candidate_id)
1222 .inset(true)
1223 .selected(item_ix == selected_item)
1224 .on_click(cx.listener(move |editor, _event, cx| {
1225 cx.stop_propagation();
1226 if let Some(task) = editor.confirm_completion(
1227 &ConfirmCompletion {
1228 item_ix: Some(item_ix),
1229 },
1230 cx,
1231 ) {
1232 task.detach_and_log_err(cx)
1233 }
1234 }))
1235 .child(h_flex().overflow_hidden().child(completion_label))
1236 .end_slot::<Label>(documentation_label),
1237 )
1238 })
1239 .collect()
1240 },
1241 )
1242 .occlude()
1243 .max_h(max_height)
1244 .track_scroll(self.scroll_handle.clone())
1245 .with_width_from_item(widest_completion_ix)
1246 .with_sizing_behavior(ListSizingBehavior::Infer);
1247
1248 Popover::new()
1249 .child(list)
1250 .when_some(multiline_docs, |popover, multiline_docs| {
1251 popover.aside(multiline_docs)
1252 })
1253 .into_any_element()
1254 }
1255
1256 pub async fn filter(&mut self, query: Option<&str>, executor: BackgroundExecutor) {
1257 let mut matches = if let Some(query) = query {
1258 fuzzy::match_strings(
1259 &self.match_candidates,
1260 query,
1261 query.chars().any(|c| c.is_uppercase()),
1262 100,
1263 &Default::default(),
1264 executor,
1265 )
1266 .await
1267 } else {
1268 self.match_candidates
1269 .iter()
1270 .enumerate()
1271 .map(|(candidate_id, candidate)| StringMatch {
1272 candidate_id,
1273 score: Default::default(),
1274 positions: Default::default(),
1275 string: candidate.string.clone(),
1276 })
1277 .collect()
1278 };
1279
1280 // Remove all candidates where the query's start does not match the start of any word in the candidate
1281 if let Some(query) = query {
1282 if let Some(query_start) = query.chars().next() {
1283 matches.retain(|string_match| {
1284 split_words(&string_match.string).any(|word| {
1285 // Check that the first codepoint of the word as lowercase matches the first
1286 // codepoint of the query as lowercase
1287 word.chars()
1288 .flat_map(|codepoint| codepoint.to_lowercase())
1289 .zip(query_start.to_lowercase())
1290 .all(|(word_cp, query_cp)| word_cp == query_cp)
1291 })
1292 });
1293 }
1294 }
1295
1296 let completions = self.completions.read();
1297 if self.sort_completions {
1298 matches.sort_unstable_by_key(|mat| {
1299 // We do want to strike a balance here between what the language server tells us
1300 // to sort by (the sort_text) and what are "obvious" good matches (i.e. when you type
1301 // `Creat` and there is a local variable called `CreateComponent`).
1302 // So what we do is: we bucket all matches into two buckets
1303 // - Strong matches
1304 // - Weak matches
1305 // Strong matches are the ones with a high fuzzy-matcher score (the "obvious" matches)
1306 // and the Weak matches are the rest.
1307 //
1308 // For the strong matches, we sort by the language-servers score first and for the weak
1309 // matches, we prefer our fuzzy finder first.
1310 //
1311 // The thinking behind that: it's useless to take the sort_text the language-server gives
1312 // us into account when it's obviously a bad match.
1313
1314 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1315 enum MatchScore<'a> {
1316 Strong {
1317 sort_text: Option<&'a str>,
1318 score: Reverse<OrderedFloat<f64>>,
1319 sort_key: (usize, &'a str),
1320 },
1321 Weak {
1322 score: Reverse<OrderedFloat<f64>>,
1323 sort_text: Option<&'a str>,
1324 sort_key: (usize, &'a str),
1325 },
1326 }
1327
1328 let completion = &completions[mat.candidate_id];
1329 let sort_key = completion.sort_key();
1330 let sort_text = completion.lsp_completion.sort_text.as_deref();
1331 let score = Reverse(OrderedFloat(mat.score));
1332
1333 if mat.score >= 0.2 {
1334 MatchScore::Strong {
1335 sort_text,
1336 score,
1337 sort_key,
1338 }
1339 } else {
1340 MatchScore::Weak {
1341 score,
1342 sort_text,
1343 sort_key,
1344 }
1345 }
1346 });
1347 }
1348
1349 for mat in &mut matches {
1350 let completion = &completions[mat.candidate_id];
1351 mat.string.clone_from(&completion.label.text);
1352 for position in &mut mat.positions {
1353 *position += completion.label.filter_range.start;
1354 }
1355 }
1356 drop(completions);
1357
1358 self.matches = matches.into();
1359 self.selected_item = 0;
1360 }
1361}
1362
1363#[derive(Clone)]
1364struct CodeActionContents {
1365 tasks: Option<Arc<ResolvedTasks>>,
1366 actions: Option<Arc<[CodeAction]>>,
1367}
1368
1369impl CodeActionContents {
1370 fn len(&self) -> usize {
1371 match (&self.tasks, &self.actions) {
1372 (Some(tasks), Some(actions)) => actions.len() + tasks.templates.len(),
1373 (Some(tasks), None) => tasks.templates.len(),
1374 (None, Some(actions)) => actions.len(),
1375 (None, None) => 0,
1376 }
1377 }
1378
1379 fn is_empty(&self) -> bool {
1380 match (&self.tasks, &self.actions) {
1381 (Some(tasks), Some(actions)) => actions.is_empty() && tasks.templates.is_empty(),
1382 (Some(tasks), None) => tasks.templates.is_empty(),
1383 (None, Some(actions)) => actions.is_empty(),
1384 (None, None) => true,
1385 }
1386 }
1387
1388 fn iter(&self) -> impl Iterator<Item = CodeActionsItem> + '_ {
1389 self.tasks
1390 .iter()
1391 .flat_map(|tasks| {
1392 tasks
1393 .templates
1394 .iter()
1395 .map(|(kind, task)| CodeActionsItem::Task(kind.clone(), task.clone()))
1396 })
1397 .chain(self.actions.iter().flat_map(|actions| {
1398 actions
1399 .iter()
1400 .map(|action| CodeActionsItem::CodeAction(action.clone()))
1401 }))
1402 }
1403 fn get(&self, index: usize) -> Option<CodeActionsItem> {
1404 match (&self.tasks, &self.actions) {
1405 (Some(tasks), Some(actions)) => {
1406 if index < tasks.templates.len() {
1407 tasks
1408 .templates
1409 .get(index)
1410 .cloned()
1411 .map(|(kind, task)| CodeActionsItem::Task(kind, task))
1412 } else {
1413 actions
1414 .get(index - tasks.templates.len())
1415 .cloned()
1416 .map(CodeActionsItem::CodeAction)
1417 }
1418 }
1419 (Some(tasks), None) => tasks
1420 .templates
1421 .get(index)
1422 .cloned()
1423 .map(|(kind, task)| CodeActionsItem::Task(kind, task)),
1424 (None, Some(actions)) => actions.get(index).cloned().map(CodeActionsItem::CodeAction),
1425 (None, None) => None,
1426 }
1427 }
1428}
1429
1430#[allow(clippy::large_enum_variant)]
1431#[derive(Clone)]
1432enum CodeActionsItem {
1433 Task(TaskSourceKind, ResolvedTask),
1434 CodeAction(CodeAction),
1435}
1436
1437impl CodeActionsItem {
1438 fn as_task(&self) -> Option<&ResolvedTask> {
1439 let Self::Task(_, task) = self else {
1440 return None;
1441 };
1442 Some(task)
1443 }
1444 fn as_code_action(&self) -> Option<&CodeAction> {
1445 let Self::CodeAction(action) = self else {
1446 return None;
1447 };
1448 Some(action)
1449 }
1450 fn label(&self) -> String {
1451 match self {
1452 Self::CodeAction(action) => action.lsp_action.title.clone(),
1453 Self::Task(_, task) => task.resolved_label.clone(),
1454 }
1455 }
1456}
1457
1458struct CodeActionsMenu {
1459 actions: CodeActionContents,
1460 buffer: Model<Buffer>,
1461 selected_item: usize,
1462 scroll_handle: UniformListScrollHandle,
1463 deployed_from_indicator: Option<DisplayRow>,
1464}
1465
1466impl CodeActionsMenu {
1467 fn select_first(&mut self, cx: &mut ViewContext<Editor>) {
1468 self.selected_item = 0;
1469 self.scroll_handle.scroll_to_item(self.selected_item);
1470 cx.notify()
1471 }
1472
1473 fn select_prev(&mut self, cx: &mut ViewContext<Editor>) {
1474 if self.selected_item > 0 {
1475 self.selected_item -= 1;
1476 } else {
1477 self.selected_item = self.actions.len() - 1;
1478 }
1479 self.scroll_handle.scroll_to_item(self.selected_item);
1480 cx.notify();
1481 }
1482
1483 fn select_next(&mut self, cx: &mut ViewContext<Editor>) {
1484 if self.selected_item + 1 < self.actions.len() {
1485 self.selected_item += 1;
1486 } else {
1487 self.selected_item = 0;
1488 }
1489 self.scroll_handle.scroll_to_item(self.selected_item);
1490 cx.notify();
1491 }
1492
1493 fn select_last(&mut self, cx: &mut ViewContext<Editor>) {
1494 self.selected_item = self.actions.len() - 1;
1495 self.scroll_handle.scroll_to_item(self.selected_item);
1496 cx.notify()
1497 }
1498
1499 fn visible(&self) -> bool {
1500 !self.actions.is_empty()
1501 }
1502
1503 fn render(
1504 &self,
1505 cursor_position: DisplayPoint,
1506 _style: &EditorStyle,
1507 max_height: Pixels,
1508 cx: &mut ViewContext<Editor>,
1509 ) -> (ContextMenuOrigin, AnyElement) {
1510 let actions = self.actions.clone();
1511 let selected_item = self.selected_item;
1512 let element = uniform_list(
1513 cx.view().clone(),
1514 "code_actions_menu",
1515 self.actions.len(),
1516 move |_this, range, cx| {
1517 actions
1518 .iter()
1519 .skip(range.start)
1520 .take(range.end - range.start)
1521 .enumerate()
1522 .map(|(ix, action)| {
1523 let item_ix = range.start + ix;
1524 let selected = selected_item == item_ix;
1525 let colors = cx.theme().colors();
1526 div()
1527 .px_1()
1528 .rounded_md()
1529 .text_color(colors.text)
1530 .when(selected, |style| {
1531 style
1532 .bg(colors.element_active)
1533 .text_color(colors.text_accent)
1534 })
1535 .hover(|style| {
1536 style
1537 .bg(colors.element_hover)
1538 .text_color(colors.text_accent)
1539 })
1540 .whitespace_nowrap()
1541 .when_some(action.as_code_action(), |this, action| {
1542 this.on_mouse_down(
1543 MouseButton::Left,
1544 cx.listener(move |editor, _, cx| {
1545 cx.stop_propagation();
1546 if let Some(task) = editor.confirm_code_action(
1547 &ConfirmCodeAction {
1548 item_ix: Some(item_ix),
1549 },
1550 cx,
1551 ) {
1552 task.detach_and_log_err(cx)
1553 }
1554 }),
1555 )
1556 // TASK: It would be good to make lsp_action.title a SharedString to avoid allocating here.
1557 .child(SharedString::from(action.lsp_action.title.clone()))
1558 })
1559 .when_some(action.as_task(), |this, task| {
1560 this.on_mouse_down(
1561 MouseButton::Left,
1562 cx.listener(move |editor, _, cx| {
1563 cx.stop_propagation();
1564 if let Some(task) = editor.confirm_code_action(
1565 &ConfirmCodeAction {
1566 item_ix: Some(item_ix),
1567 },
1568 cx,
1569 ) {
1570 task.detach_and_log_err(cx)
1571 }
1572 }),
1573 )
1574 .child(SharedString::from(task.resolved_label.clone()))
1575 })
1576 })
1577 .collect()
1578 },
1579 )
1580 .elevation_1(cx)
1581 .p_1()
1582 .max_h(max_height)
1583 .occlude()
1584 .track_scroll(self.scroll_handle.clone())
1585 .with_width_from_item(
1586 self.actions
1587 .iter()
1588 .enumerate()
1589 .max_by_key(|(_, action)| match action {
1590 CodeActionsItem::Task(_, task) => task.resolved_label.chars().count(),
1591 CodeActionsItem::CodeAction(action) => action.lsp_action.title.chars().count(),
1592 })
1593 .map(|(ix, _)| ix),
1594 )
1595 .with_sizing_behavior(ListSizingBehavior::Infer)
1596 .into_any_element();
1597
1598 let cursor_position = if let Some(row) = self.deployed_from_indicator {
1599 ContextMenuOrigin::GutterIndicator(row)
1600 } else {
1601 ContextMenuOrigin::EditorPoint(cursor_position)
1602 };
1603
1604 (cursor_position, element)
1605 }
1606}
1607
1608#[derive(Debug)]
1609struct ActiveDiagnosticGroup {
1610 primary_range: Range<Anchor>,
1611 primary_message: String,
1612 group_id: usize,
1613 blocks: HashMap<CustomBlockId, Diagnostic>,
1614 is_valid: bool,
1615}
1616
1617#[derive(Serialize, Deserialize, Clone, Debug)]
1618pub struct ClipboardSelection {
1619 pub len: usize,
1620 pub is_entire_line: bool,
1621 pub first_line_indent: u32,
1622}
1623
1624#[derive(Debug)]
1625pub(crate) struct NavigationData {
1626 cursor_anchor: Anchor,
1627 cursor_position: Point,
1628 scroll_anchor: ScrollAnchor,
1629 scroll_top_row: u32,
1630}
1631
1632#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1633enum GotoDefinitionKind {
1634 Symbol,
1635 Declaration,
1636 Type,
1637 Implementation,
1638}
1639
1640#[derive(Debug, Clone)]
1641enum InlayHintRefreshReason {
1642 Toggle(bool),
1643 SettingsChange(InlayHintSettings),
1644 NewLinesShown,
1645 BufferEdited(HashSet<Arc<Language>>),
1646 RefreshRequested,
1647 ExcerptsRemoved(Vec<ExcerptId>),
1648}
1649
1650impl InlayHintRefreshReason {
1651 fn description(&self) -> &'static str {
1652 match self {
1653 Self::Toggle(_) => "toggle",
1654 Self::SettingsChange(_) => "settings change",
1655 Self::NewLinesShown => "new lines shown",
1656 Self::BufferEdited(_) => "buffer edited",
1657 Self::RefreshRequested => "refresh requested",
1658 Self::ExcerptsRemoved(_) => "excerpts removed",
1659 }
1660 }
1661}
1662
1663pub(crate) struct FocusedBlock {
1664 id: BlockId,
1665 focus_handle: WeakFocusHandle,
1666}
1667
1668impl Editor {
1669 pub fn single_line(cx: &mut ViewContext<Self>) -> Self {
1670 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1671 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1672 Self::new(
1673 EditorMode::SingleLine { auto_width: false },
1674 buffer,
1675 None,
1676 false,
1677 cx,
1678 )
1679 }
1680
1681 pub fn multi_line(cx: &mut ViewContext<Self>) -> Self {
1682 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1683 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1684 Self::new(EditorMode::Full, buffer, None, false, cx)
1685 }
1686
1687 pub fn auto_width(cx: &mut ViewContext<Self>) -> Self {
1688 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1689 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1690 Self::new(
1691 EditorMode::SingleLine { auto_width: true },
1692 buffer,
1693 None,
1694 false,
1695 cx,
1696 )
1697 }
1698
1699 pub fn auto_height(max_lines: usize, cx: &mut ViewContext<Self>) -> Self {
1700 let buffer = cx.new_model(|cx| Buffer::local("", cx));
1701 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1702 Self::new(
1703 EditorMode::AutoHeight { max_lines },
1704 buffer,
1705 None,
1706 false,
1707 cx,
1708 )
1709 }
1710
1711 pub fn for_buffer(
1712 buffer: Model<Buffer>,
1713 project: Option<Model<Project>>,
1714 cx: &mut ViewContext<Self>,
1715 ) -> Self {
1716 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
1717 Self::new(EditorMode::Full, buffer, project, false, cx)
1718 }
1719
1720 pub fn for_multibuffer(
1721 buffer: Model<MultiBuffer>,
1722 project: Option<Model<Project>>,
1723 show_excerpt_controls: bool,
1724 cx: &mut ViewContext<Self>,
1725 ) -> Self {
1726 Self::new(EditorMode::Full, buffer, project, show_excerpt_controls, cx)
1727 }
1728
1729 pub fn clone(&self, cx: &mut ViewContext<Self>) -> Self {
1730 let show_excerpt_controls = self.display_map.read(cx).show_excerpt_controls();
1731 let mut clone = Self::new(
1732 self.mode,
1733 self.buffer.clone(),
1734 self.project.clone(),
1735 show_excerpt_controls,
1736 cx,
1737 );
1738 self.display_map.update(cx, |display_map, cx| {
1739 let snapshot = display_map.snapshot(cx);
1740 clone.display_map.update(cx, |display_map, cx| {
1741 display_map.set_state(&snapshot, cx);
1742 });
1743 });
1744 clone.selections.clone_state(&self.selections);
1745 clone.scroll_manager.clone_state(&self.scroll_manager);
1746 clone.searchable = self.searchable;
1747 clone
1748 }
1749
1750 pub fn new(
1751 mode: EditorMode,
1752 buffer: Model<MultiBuffer>,
1753 project: Option<Model<Project>>,
1754 show_excerpt_controls: bool,
1755 cx: &mut ViewContext<Self>,
1756 ) -> Self {
1757 let style = cx.text_style();
1758 let font_size = style.font_size.to_pixels(cx.rem_size());
1759 let editor = cx.view().downgrade();
1760 let fold_placeholder = FoldPlaceholder {
1761 constrain_width: true,
1762 render: Arc::new(move |fold_id, fold_range, cx| {
1763 let editor = editor.clone();
1764 div()
1765 .id(fold_id)
1766 .bg(cx.theme().colors().ghost_element_background)
1767 .hover(|style| style.bg(cx.theme().colors().ghost_element_hover))
1768 .active(|style| style.bg(cx.theme().colors().ghost_element_active))
1769 .rounded_sm()
1770 .size_full()
1771 .cursor_pointer()
1772 .child("⋯")
1773 .on_mouse_down(MouseButton::Left, |_, cx| cx.stop_propagation())
1774 .on_click(move |_, cx| {
1775 editor
1776 .update(cx, |editor, cx| {
1777 editor.unfold_ranges(
1778 [fold_range.start..fold_range.end],
1779 true,
1780 false,
1781 cx,
1782 );
1783 cx.stop_propagation();
1784 })
1785 .ok();
1786 })
1787 .into_any()
1788 }),
1789 merge_adjacent: true,
1790 };
1791 let file_header_size = if show_excerpt_controls { 3 } else { 2 };
1792 let display_map = cx.new_model(|cx| {
1793 DisplayMap::new(
1794 buffer.clone(),
1795 style.font(),
1796 font_size,
1797 None,
1798 show_excerpt_controls,
1799 file_header_size,
1800 MULTI_BUFFER_EXCERPT_HEADER_HEIGHT,
1801 MULTI_BUFFER_EXCERPT_FOOTER_HEIGHT,
1802 fold_placeholder,
1803 cx,
1804 )
1805 });
1806
1807 let selections = SelectionsCollection::new(display_map.clone(), buffer.clone());
1808
1809 let blink_manager = cx.new_model(|cx| BlinkManager::new(CURSOR_BLINK_INTERVAL, cx));
1810
1811 let soft_wrap_mode_override = matches!(mode, EditorMode::SingleLine { .. })
1812 .then(|| language_settings::SoftWrap::PreferLine);
1813
1814 let mut project_subscriptions = Vec::new();
1815 if mode == EditorMode::Full {
1816 if let Some(project) = project.as_ref() {
1817 if buffer.read(cx).is_singleton() {
1818 project_subscriptions.push(cx.observe(project, |_, _, cx| {
1819 cx.emit(EditorEvent::TitleChanged);
1820 }));
1821 }
1822 project_subscriptions.push(cx.subscribe(project, |editor, _, event, cx| {
1823 if let project::Event::RefreshInlayHints = event {
1824 editor.refresh_inlay_hints(InlayHintRefreshReason::RefreshRequested, cx);
1825 } else if let project::Event::SnippetEdit(id, snippet_edits) = event {
1826 if let Some(buffer) = editor.buffer.read(cx).buffer(*id) {
1827 let focus_handle = editor.focus_handle(cx);
1828 if focus_handle.is_focused(cx) {
1829 let snapshot = buffer.read(cx).snapshot();
1830 for (range, snippet) in snippet_edits {
1831 let editor_range =
1832 language::range_from_lsp(*range).to_offset(&snapshot);
1833 editor
1834 .insert_snippet(&[editor_range], snippet.clone(), cx)
1835 .ok();
1836 }
1837 }
1838 }
1839 }
1840 }));
1841 let task_inventory = project.read(cx).task_inventory().clone();
1842 project_subscriptions.push(cx.observe(&task_inventory, |editor, _, cx| {
1843 editor.tasks_update_task = Some(editor.refresh_runnables(cx));
1844 }));
1845 }
1846 }
1847
1848 let inlay_hint_settings = inlay_hint_settings(
1849 selections.newest_anchor().head(),
1850 &buffer.read(cx).snapshot(cx),
1851 cx,
1852 );
1853 let focus_handle = cx.focus_handle();
1854 cx.on_focus(&focus_handle, Self::handle_focus).detach();
1855 cx.on_focus_in(&focus_handle, Self::handle_focus_in)
1856 .detach();
1857 cx.on_focus_out(&focus_handle, Self::handle_focus_out)
1858 .detach();
1859 cx.on_blur(&focus_handle, Self::handle_blur).detach();
1860
1861 let show_indent_guides = if matches!(mode, EditorMode::SingleLine { .. }) {
1862 Some(false)
1863 } else {
1864 None
1865 };
1866
1867 let mut this = Self {
1868 focus_handle,
1869 show_cursor_when_unfocused: false,
1870 last_focused_descendant: None,
1871 buffer: buffer.clone(),
1872 display_map: display_map.clone(),
1873 selections,
1874 scroll_manager: ScrollManager::new(cx),
1875 columnar_selection_tail: None,
1876 add_selections_state: None,
1877 select_next_state: None,
1878 select_prev_state: None,
1879 selection_history: Default::default(),
1880 autoclose_regions: Default::default(),
1881 snippet_stack: Default::default(),
1882 select_larger_syntax_node_stack: Vec::new(),
1883 ime_transaction: Default::default(),
1884 active_diagnostics: None,
1885 soft_wrap_mode_override,
1886 completion_provider: project.clone().map(|project| Box::new(project) as _),
1887 collaboration_hub: project.clone().map(|project| Box::new(project) as _),
1888 project,
1889 blink_manager: blink_manager.clone(),
1890 show_local_selections: true,
1891 mode,
1892 show_breadcrumbs: EditorSettings::get_global(cx).toolbar.breadcrumbs,
1893 show_gutter: mode == EditorMode::Full,
1894 show_line_numbers: None,
1895 use_relative_line_numbers: None,
1896 show_git_diff_gutter: None,
1897 show_code_actions: None,
1898 show_runnables: None,
1899 show_wrap_guides: None,
1900 show_indent_guides,
1901 placeholder_text: None,
1902 highlight_order: 0,
1903 highlighted_rows: HashMap::default(),
1904 background_highlights: Default::default(),
1905 gutter_highlights: TreeMap::default(),
1906 scrollbar_marker_state: ScrollbarMarkerState::default(),
1907 active_indent_guides_state: ActiveIndentGuidesState::default(),
1908 nav_history: None,
1909 context_menu: RwLock::new(None),
1910 mouse_context_menu: None,
1911 completion_tasks: Default::default(),
1912 signature_help_state: SignatureHelpState::default(),
1913 auto_signature_help: None,
1914 find_all_references_task_sources: Vec::new(),
1915 next_completion_id: 0,
1916 completion_documentation_pre_resolve_debounce: DebouncedDelay::new(),
1917 next_inlay_id: 0,
1918 available_code_actions: Default::default(),
1919 code_actions_task: Default::default(),
1920 document_highlights_task: Default::default(),
1921 linked_editing_range_task: Default::default(),
1922 pending_rename: Default::default(),
1923 searchable: true,
1924 cursor_shape: EditorSettings::get_global(cx)
1925 .cursor_shape
1926 .unwrap_or_default(),
1927 current_line_highlight: None,
1928 autoindent_mode: Some(AutoindentMode::EachLine),
1929 collapse_matches: false,
1930 workspace: None,
1931 input_enabled: true,
1932 use_modal_editing: mode == EditorMode::Full,
1933 read_only: false,
1934 use_autoclose: true,
1935 use_auto_surround: true,
1936 auto_replace_emoji_shortcode: false,
1937 leader_peer_id: None,
1938 remote_id: None,
1939 hover_state: Default::default(),
1940 hovered_link_state: Default::default(),
1941 inline_completion_provider: None,
1942 active_inline_completion: None,
1943 inlay_hint_cache: InlayHintCache::new(inlay_hint_settings),
1944 expanded_hunks: ExpandedHunks::default(),
1945 gutter_hovered: false,
1946 pixel_position_of_newest_cursor: None,
1947 last_bounds: None,
1948 expect_bounds_change: None,
1949 gutter_dimensions: GutterDimensions::default(),
1950 style: None,
1951 show_cursor_names: false,
1952 hovered_cursors: Default::default(),
1953 next_editor_action_id: EditorActionId::default(),
1954 editor_actions: Rc::default(),
1955 show_inline_completions_override: None,
1956 enable_inline_completions: true,
1957 custom_context_menu: None,
1958 show_git_blame_gutter: false,
1959 show_git_blame_inline: false,
1960 show_selection_menu: None,
1961 show_git_blame_inline_delay_task: None,
1962 git_blame_inline_enabled: ProjectSettings::get_global(cx).git.inline_blame_enabled(),
1963 serialize_dirty_buffers: ProjectSettings::get_global(cx)
1964 .session
1965 .restore_unsaved_buffers,
1966 blame: None,
1967 blame_subscription: None,
1968 file_header_size,
1969 tasks: Default::default(),
1970 _subscriptions: vec![
1971 cx.observe(&buffer, Self::on_buffer_changed),
1972 cx.subscribe(&buffer, Self::on_buffer_event),
1973 cx.observe(&display_map, Self::on_display_map_changed),
1974 cx.observe(&blink_manager, |_, _, cx| cx.notify()),
1975 cx.observe_global::<SettingsStore>(Self::settings_changed),
1976 observe_buffer_font_size_adjustment(cx, |_, cx| cx.notify()),
1977 cx.observe_window_activation(|editor, cx| {
1978 let active = cx.is_window_active();
1979 editor.blink_manager.update(cx, |blink_manager, cx| {
1980 if active {
1981 blink_manager.enable(cx);
1982 } else {
1983 blink_manager.disable(cx);
1984 }
1985 });
1986 }),
1987 ],
1988 tasks_update_task: None,
1989 linked_edit_ranges: Default::default(),
1990 previous_search_ranges: None,
1991 breadcrumb_header: None,
1992 focused_block: None,
1993 next_scroll_position: NextScrollCursorCenterTopBottom::default(),
1994 addons: HashMap::default(),
1995 _scroll_cursor_center_top_bottom_task: Task::ready(()),
1996 };
1997 this.tasks_update_task = Some(this.refresh_runnables(cx));
1998 this._subscriptions.extend(project_subscriptions);
1999
2000 this.end_selection(cx);
2001 this.scroll_manager.show_scrollbar(cx);
2002
2003 if mode == EditorMode::Full {
2004 let should_auto_hide_scrollbars = cx.should_auto_hide_scrollbars();
2005 cx.set_global(ScrollbarAutoHide(should_auto_hide_scrollbars));
2006
2007 if this.git_blame_inline_enabled {
2008 this.git_blame_inline_enabled = true;
2009 this.start_git_blame_inline(false, cx);
2010 }
2011 }
2012
2013 this.report_editor_event("open", None, cx);
2014 this
2015 }
2016
2017 pub fn mouse_menu_is_focused(&self, cx: &WindowContext) -> bool {
2018 self.mouse_context_menu
2019 .as_ref()
2020 .is_some_and(|menu| menu.context_menu.focus_handle(cx).is_focused(cx))
2021 }
2022
2023 fn key_context(&self, cx: &ViewContext<Self>) -> KeyContext {
2024 let mut key_context = KeyContext::new_with_defaults();
2025 key_context.add("Editor");
2026 let mode = match self.mode {
2027 EditorMode::SingleLine { .. } => "single_line",
2028 EditorMode::AutoHeight { .. } => "auto_height",
2029 EditorMode::Full => "full",
2030 };
2031
2032 if EditorSettings::jupyter_enabled(cx) {
2033 key_context.add("jupyter");
2034 }
2035
2036 key_context.set("mode", mode);
2037 if self.pending_rename.is_some() {
2038 key_context.add("renaming");
2039 }
2040 if self.context_menu_visible() {
2041 match self.context_menu.read().as_ref() {
2042 Some(ContextMenu::Completions(_)) => {
2043 key_context.add("menu");
2044 key_context.add("showing_completions")
2045 }
2046 Some(ContextMenu::CodeActions(_)) => {
2047 key_context.add("menu");
2048 key_context.add("showing_code_actions")
2049 }
2050 None => {}
2051 }
2052 }
2053
2054 // Disable vim contexts when a sub-editor (e.g. rename/inline assistant) is focused.
2055 if !self.focus_handle(cx).contains_focused(cx)
2056 || (self.is_focused(cx) || self.mouse_menu_is_focused(cx))
2057 {
2058 for addon in self.addons.values() {
2059 addon.extend_key_context(&mut key_context, cx)
2060 }
2061 }
2062
2063 if let Some(extension) = self
2064 .buffer
2065 .read(cx)
2066 .as_singleton()
2067 .and_then(|buffer| buffer.read(cx).file()?.path().extension()?.to_str())
2068 {
2069 key_context.set("extension", extension.to_string());
2070 }
2071
2072 if self.has_active_inline_completion(cx) {
2073 key_context.add("copilot_suggestion");
2074 key_context.add("inline_completion");
2075 }
2076
2077 key_context
2078 }
2079
2080 pub fn new_file(
2081 workspace: &mut Workspace,
2082 _: &workspace::NewFile,
2083 cx: &mut ViewContext<Workspace>,
2084 ) {
2085 Self::new_in_workspace(workspace, cx).detach_and_prompt_err(
2086 "Failed to create buffer",
2087 cx,
2088 |e, _| match e.error_code() {
2089 ErrorCode::RemoteUpgradeRequired => Some(format!(
2090 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2091 e.error_tag("required").unwrap_or("the latest version")
2092 )),
2093 _ => None,
2094 },
2095 );
2096 }
2097
2098 pub fn new_in_workspace(
2099 workspace: &mut Workspace,
2100 cx: &mut ViewContext<Workspace>,
2101 ) -> Task<Result<View<Editor>>> {
2102 let project = workspace.project().clone();
2103 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2104
2105 cx.spawn(|workspace, mut cx| async move {
2106 let buffer = create.await?;
2107 workspace.update(&mut cx, |workspace, cx| {
2108 let editor =
2109 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx));
2110 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
2111 editor
2112 })
2113 })
2114 }
2115
2116 fn new_file_vertical(
2117 workspace: &mut Workspace,
2118 _: &workspace::NewFileSplitVertical,
2119 cx: &mut ViewContext<Workspace>,
2120 ) {
2121 Self::new_file_in_direction(workspace, SplitDirection::vertical(cx), cx)
2122 }
2123
2124 fn new_file_horizontal(
2125 workspace: &mut Workspace,
2126 _: &workspace::NewFileSplitHorizontal,
2127 cx: &mut ViewContext<Workspace>,
2128 ) {
2129 Self::new_file_in_direction(workspace, SplitDirection::horizontal(cx), cx)
2130 }
2131
2132 fn new_file_in_direction(
2133 workspace: &mut Workspace,
2134 direction: SplitDirection,
2135 cx: &mut ViewContext<Workspace>,
2136 ) {
2137 let project = workspace.project().clone();
2138 let create = project.update(cx, |project, cx| project.create_buffer(cx));
2139
2140 cx.spawn(|workspace, mut cx| async move {
2141 let buffer = create.await?;
2142 workspace.update(&mut cx, move |workspace, cx| {
2143 workspace.split_item(
2144 direction,
2145 Box::new(
2146 cx.new_view(|cx| Editor::for_buffer(buffer, Some(project.clone()), cx)),
2147 ),
2148 cx,
2149 )
2150 })?;
2151 anyhow::Ok(())
2152 })
2153 .detach_and_prompt_err("Failed to create buffer", cx, |e, _| match e.error_code() {
2154 ErrorCode::RemoteUpgradeRequired => Some(format!(
2155 "The remote instance of Zed does not support this yet. It must be upgraded to {}",
2156 e.error_tag("required").unwrap_or("the latest version")
2157 )),
2158 _ => None,
2159 });
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 mut entries = transaction.0.into_iter().collect::<Vec<_>>();
4762 cx.update(|cx| {
4763 entries.sort_unstable_by_key(|(buffer, _)| {
4764 buffer.read(cx).file().map(|f| f.path().clone())
4765 });
4766 })?;
4767
4768 // If the project transaction's edits are all contained within this editor, then
4769 // avoid opening a new editor to display them.
4770
4771 if let Some((buffer, transaction)) = entries.first() {
4772 if entries.len() == 1 {
4773 let excerpt = this.update(&mut cx, |editor, cx| {
4774 editor
4775 .buffer()
4776 .read(cx)
4777 .excerpt_containing(editor.selections.newest_anchor().head(), cx)
4778 })?;
4779 if let Some((_, excerpted_buffer, excerpt_range)) = excerpt {
4780 if excerpted_buffer == *buffer {
4781 let all_edits_within_excerpt = buffer.read_with(&cx, |buffer, _| {
4782 let excerpt_range = excerpt_range.to_offset(buffer);
4783 buffer
4784 .edited_ranges_for_transaction::<usize>(transaction)
4785 .all(|range| {
4786 excerpt_range.start <= range.start
4787 && excerpt_range.end >= range.end
4788 })
4789 })?;
4790
4791 if all_edits_within_excerpt {
4792 return Ok(());
4793 }
4794 }
4795 }
4796 }
4797 } else {
4798 return Ok(());
4799 }
4800
4801 let mut ranges_to_highlight = Vec::new();
4802 let excerpt_buffer = cx.new_model(|cx| {
4803 let mut multibuffer = MultiBuffer::new(Capability::ReadWrite).with_title(title);
4804 for (buffer_handle, transaction) in &entries {
4805 let buffer = buffer_handle.read(cx);
4806 ranges_to_highlight.extend(
4807 multibuffer.push_excerpts_with_context_lines(
4808 buffer_handle.clone(),
4809 buffer
4810 .edited_ranges_for_transaction::<usize>(transaction)
4811 .collect(),
4812 DEFAULT_MULTIBUFFER_CONTEXT,
4813 cx,
4814 ),
4815 );
4816 }
4817 multibuffer.push_transaction(entries.iter().map(|(b, t)| (b, t)), cx);
4818 multibuffer
4819 })?;
4820
4821 workspace.update(&mut cx, |workspace, cx| {
4822 let project = workspace.project().clone();
4823 let editor =
4824 cx.new_view(|cx| Editor::for_multibuffer(excerpt_buffer, Some(project), true, cx));
4825 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, true, cx);
4826 editor.update(cx, |editor, cx| {
4827 editor.highlight_background::<Self>(
4828 &ranges_to_highlight,
4829 |theme| theme.editor_highlighted_line_background,
4830 cx,
4831 );
4832 });
4833 })?;
4834
4835 Ok(())
4836 }
4837
4838 fn refresh_code_actions(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4839 let project = self.project.clone()?;
4840 let buffer = self.buffer.read(cx);
4841 let newest_selection = self.selections.newest_anchor().clone();
4842 let (start_buffer, start) = buffer.text_anchor_for_position(newest_selection.start, cx)?;
4843 let (end_buffer, end) = buffer.text_anchor_for_position(newest_selection.end, cx)?;
4844 if start_buffer != end_buffer {
4845 return None;
4846 }
4847
4848 self.code_actions_task = Some(cx.spawn(|this, mut cx| async move {
4849 cx.background_executor()
4850 .timer(CODE_ACTIONS_DEBOUNCE_TIMEOUT)
4851 .await;
4852
4853 let actions = if let Ok(code_actions) = project.update(&mut cx, |project, cx| {
4854 project.code_actions(&start_buffer, start..end, cx)
4855 }) {
4856 code_actions.await
4857 } else {
4858 Vec::new()
4859 };
4860
4861 this.update(&mut cx, |this, cx| {
4862 this.available_code_actions = if actions.is_empty() {
4863 None
4864 } else {
4865 Some((
4866 Location {
4867 buffer: start_buffer,
4868 range: start..end,
4869 },
4870 actions.into(),
4871 ))
4872 };
4873 cx.notify();
4874 })
4875 .log_err();
4876 }));
4877 None
4878 }
4879
4880 fn start_inline_blame_timer(&mut self, cx: &mut ViewContext<Self>) {
4881 if let Some(delay) = ProjectSettings::get_global(cx).git.inline_blame_delay() {
4882 self.show_git_blame_inline = false;
4883
4884 self.show_git_blame_inline_delay_task = Some(cx.spawn(|this, mut cx| async move {
4885 cx.background_executor().timer(delay).await;
4886
4887 this.update(&mut cx, |this, cx| {
4888 this.show_git_blame_inline = true;
4889 cx.notify();
4890 })
4891 .log_err();
4892 }));
4893 }
4894 }
4895
4896 fn refresh_document_highlights(&mut self, cx: &mut ViewContext<Self>) -> Option<()> {
4897 if self.pending_rename.is_some() {
4898 return None;
4899 }
4900
4901 let project = self.project.clone()?;
4902 let buffer = self.buffer.read(cx);
4903 let newest_selection = self.selections.newest_anchor().clone();
4904 let cursor_position = newest_selection.head();
4905 let (cursor_buffer, cursor_buffer_position) =
4906 buffer.text_anchor_for_position(cursor_position, cx)?;
4907 let (tail_buffer, _) = buffer.text_anchor_for_position(newest_selection.tail(), cx)?;
4908 if cursor_buffer != tail_buffer {
4909 return None;
4910 }
4911
4912 self.document_highlights_task = Some(cx.spawn(|this, mut cx| async move {
4913 cx.background_executor()
4914 .timer(DOCUMENT_HIGHLIGHTS_DEBOUNCE_TIMEOUT)
4915 .await;
4916
4917 let highlights = if let Some(highlights) = project
4918 .update(&mut cx, |project, cx| {
4919 project.document_highlights(&cursor_buffer, cursor_buffer_position, cx)
4920 })
4921 .log_err()
4922 {
4923 highlights.await.log_err()
4924 } else {
4925 None
4926 };
4927
4928 if let Some(highlights) = highlights {
4929 this.update(&mut cx, |this, cx| {
4930 if this.pending_rename.is_some() {
4931 return;
4932 }
4933
4934 let buffer_id = cursor_position.buffer_id;
4935 let buffer = this.buffer.read(cx);
4936 if !buffer
4937 .text_anchor_for_position(cursor_position, cx)
4938 .map_or(false, |(buffer, _)| buffer == cursor_buffer)
4939 {
4940 return;
4941 }
4942
4943 let cursor_buffer_snapshot = cursor_buffer.read(cx);
4944 let mut write_ranges = Vec::new();
4945 let mut read_ranges = Vec::new();
4946 for highlight in highlights {
4947 for (excerpt_id, excerpt_range) in
4948 buffer.excerpts_for_buffer(&cursor_buffer, cx)
4949 {
4950 let start = highlight
4951 .range
4952 .start
4953 .max(&excerpt_range.context.start, cursor_buffer_snapshot);
4954 let end = highlight
4955 .range
4956 .end
4957 .min(&excerpt_range.context.end, cursor_buffer_snapshot);
4958 if start.cmp(&end, cursor_buffer_snapshot).is_ge() {
4959 continue;
4960 }
4961
4962 let range = Anchor {
4963 buffer_id,
4964 excerpt_id,
4965 text_anchor: start,
4966 }..Anchor {
4967 buffer_id,
4968 excerpt_id,
4969 text_anchor: end,
4970 };
4971 if highlight.kind == lsp::DocumentHighlightKind::WRITE {
4972 write_ranges.push(range);
4973 } else {
4974 read_ranges.push(range);
4975 }
4976 }
4977 }
4978
4979 this.highlight_background::<DocumentHighlightRead>(
4980 &read_ranges,
4981 |theme| theme.editor_document_highlight_read_background,
4982 cx,
4983 );
4984 this.highlight_background::<DocumentHighlightWrite>(
4985 &write_ranges,
4986 |theme| theme.editor_document_highlight_write_background,
4987 cx,
4988 );
4989 cx.notify();
4990 })
4991 .log_err();
4992 }
4993 }));
4994 None
4995 }
4996
4997 pub fn refresh_inline_completion(
4998 &mut self,
4999 debounce: bool,
5000 user_requested: bool,
5001 cx: &mut ViewContext<Self>,
5002 ) -> Option<()> {
5003 let provider = self.inline_completion_provider()?;
5004 let cursor = self.selections.newest_anchor().head();
5005 let (buffer, cursor_buffer_position) =
5006 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5007
5008 if !user_requested
5009 && (!self.enable_inline_completions
5010 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx))
5011 {
5012 self.discard_inline_completion(false, cx);
5013 return None;
5014 }
5015
5016 self.update_visible_inline_completion(cx);
5017 provider.refresh(buffer, cursor_buffer_position, debounce, cx);
5018 Some(())
5019 }
5020
5021 fn cycle_inline_completion(
5022 &mut self,
5023 direction: Direction,
5024 cx: &mut ViewContext<Self>,
5025 ) -> Option<()> {
5026 let provider = self.inline_completion_provider()?;
5027 let cursor = self.selections.newest_anchor().head();
5028 let (buffer, cursor_buffer_position) =
5029 self.buffer.read(cx).text_anchor_for_position(cursor, cx)?;
5030 if !self.enable_inline_completions
5031 || !self.should_show_inline_completions(&buffer, cursor_buffer_position, cx)
5032 {
5033 return None;
5034 }
5035
5036 provider.cycle(buffer, cursor_buffer_position, direction, cx);
5037 self.update_visible_inline_completion(cx);
5038
5039 Some(())
5040 }
5041
5042 pub fn show_inline_completion(&mut self, _: &ShowInlineCompletion, cx: &mut ViewContext<Self>) {
5043 if !self.has_active_inline_completion(cx) {
5044 self.refresh_inline_completion(false, true, cx);
5045 return;
5046 }
5047
5048 self.update_visible_inline_completion(cx);
5049 }
5050
5051 pub fn display_cursor_names(&mut self, _: &DisplayCursorNames, cx: &mut ViewContext<Self>) {
5052 self.show_cursor_names(cx);
5053 }
5054
5055 fn show_cursor_names(&mut self, cx: &mut ViewContext<Self>) {
5056 self.show_cursor_names = true;
5057 cx.notify();
5058 cx.spawn(|this, mut cx| async move {
5059 cx.background_executor().timer(CURSORS_VISIBLE_FOR).await;
5060 this.update(&mut cx, |this, cx| {
5061 this.show_cursor_names = false;
5062 cx.notify()
5063 })
5064 .ok()
5065 })
5066 .detach();
5067 }
5068
5069 pub fn next_inline_completion(&mut self, _: &NextInlineCompletion, cx: &mut ViewContext<Self>) {
5070 if self.has_active_inline_completion(cx) {
5071 self.cycle_inline_completion(Direction::Next, cx);
5072 } else {
5073 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5074 if is_copilot_disabled {
5075 cx.propagate();
5076 }
5077 }
5078 }
5079
5080 pub fn previous_inline_completion(
5081 &mut self,
5082 _: &PreviousInlineCompletion,
5083 cx: &mut ViewContext<Self>,
5084 ) {
5085 if self.has_active_inline_completion(cx) {
5086 self.cycle_inline_completion(Direction::Prev, cx);
5087 } else {
5088 let is_copilot_disabled = self.refresh_inline_completion(false, true, cx).is_none();
5089 if is_copilot_disabled {
5090 cx.propagate();
5091 }
5092 }
5093 }
5094
5095 pub fn accept_inline_completion(
5096 &mut self,
5097 _: &AcceptInlineCompletion,
5098 cx: &mut ViewContext<Self>,
5099 ) {
5100 let Some(completion) = self.take_active_inline_completion(cx) else {
5101 return;
5102 };
5103 if let Some(provider) = self.inline_completion_provider() {
5104 provider.accept(cx);
5105 }
5106
5107 cx.emit(EditorEvent::InputHandled {
5108 utf16_range_to_replace: None,
5109 text: completion.text.to_string().into(),
5110 });
5111
5112 if let Some(range) = completion.delete_range {
5113 self.change_selections(None, cx, |s| s.select_ranges([range]))
5114 }
5115 self.insert_with_autoindent_mode(&completion.text.to_string(), None, cx);
5116 self.refresh_inline_completion(true, true, cx);
5117 cx.notify();
5118 }
5119
5120 pub fn accept_partial_inline_completion(
5121 &mut self,
5122 _: &AcceptPartialInlineCompletion,
5123 cx: &mut ViewContext<Self>,
5124 ) {
5125 if self.selections.count() == 1 && self.has_active_inline_completion(cx) {
5126 if let Some(completion) = self.take_active_inline_completion(cx) {
5127 let mut partial_completion = completion
5128 .text
5129 .chars()
5130 .by_ref()
5131 .take_while(|c| c.is_alphabetic())
5132 .collect::<String>();
5133 if partial_completion.is_empty() {
5134 partial_completion = completion
5135 .text
5136 .chars()
5137 .by_ref()
5138 .take_while(|c| c.is_whitespace() || !c.is_alphabetic())
5139 .collect::<String>();
5140 }
5141
5142 cx.emit(EditorEvent::InputHandled {
5143 utf16_range_to_replace: None,
5144 text: partial_completion.clone().into(),
5145 });
5146
5147 if let Some(range) = completion.delete_range {
5148 self.change_selections(None, cx, |s| s.select_ranges([range]))
5149 }
5150 self.insert_with_autoindent_mode(&partial_completion, None, cx);
5151
5152 self.refresh_inline_completion(true, true, cx);
5153 cx.notify();
5154 }
5155 }
5156 }
5157
5158 fn discard_inline_completion(
5159 &mut self,
5160 should_report_inline_completion_event: bool,
5161 cx: &mut ViewContext<Self>,
5162 ) -> bool {
5163 if let Some(provider) = self.inline_completion_provider() {
5164 provider.discard(should_report_inline_completion_event, cx);
5165 }
5166
5167 self.take_active_inline_completion(cx).is_some()
5168 }
5169
5170 pub fn has_active_inline_completion(&self, cx: &AppContext) -> bool {
5171 if let Some(completion) = self.active_inline_completion.as_ref() {
5172 let buffer = self.buffer.read(cx).read(cx);
5173 completion.position.is_valid(&buffer)
5174 } else {
5175 false
5176 }
5177 }
5178
5179 fn take_active_inline_completion(
5180 &mut self,
5181 cx: &mut ViewContext<Self>,
5182 ) -> Option<CompletionState> {
5183 let completion = self.active_inline_completion.take()?;
5184 let render_inlay_ids = completion.render_inlay_ids.clone();
5185 self.display_map.update(cx, |map, cx| {
5186 map.splice_inlays(render_inlay_ids, Default::default(), cx);
5187 });
5188 let buffer = self.buffer.read(cx).read(cx);
5189
5190 if completion.position.is_valid(&buffer) {
5191 Some(completion)
5192 } else {
5193 None
5194 }
5195 }
5196
5197 fn update_visible_inline_completion(&mut self, cx: &mut ViewContext<Self>) {
5198 let selection = self.selections.newest_anchor();
5199 let cursor = selection.head();
5200
5201 let excerpt_id = cursor.excerpt_id;
5202
5203 if self.context_menu.read().is_none()
5204 && self.completion_tasks.is_empty()
5205 && selection.start == selection.end
5206 {
5207 if let Some(provider) = self.inline_completion_provider() {
5208 if let Some((buffer, cursor_buffer_position)) =
5209 self.buffer.read(cx).text_anchor_for_position(cursor, cx)
5210 {
5211 if let Some(proposal) =
5212 provider.active_completion_text(&buffer, cursor_buffer_position, cx)
5213 {
5214 let mut to_remove = Vec::new();
5215 if let Some(completion) = self.active_inline_completion.take() {
5216 to_remove.extend(completion.render_inlay_ids.iter());
5217 }
5218
5219 let to_add = proposal
5220 .inlays
5221 .iter()
5222 .filter_map(|inlay| {
5223 let snapshot = self.buffer.read(cx).snapshot(cx);
5224 let id = post_inc(&mut self.next_inlay_id);
5225 match inlay {
5226 InlayProposal::Hint(position, hint) => {
5227 let position =
5228 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5229 Some(Inlay::hint(id, position, hint))
5230 }
5231 InlayProposal::Suggestion(position, text) => {
5232 let position =
5233 snapshot.anchor_in_excerpt(excerpt_id, *position)?;
5234 Some(Inlay::suggestion(id, position, text.clone()))
5235 }
5236 }
5237 })
5238 .collect_vec();
5239
5240 self.active_inline_completion = Some(CompletionState {
5241 position: cursor,
5242 text: proposal.text,
5243 delete_range: proposal.delete_range.and_then(|range| {
5244 let snapshot = self.buffer.read(cx).snapshot(cx);
5245 let start = snapshot.anchor_in_excerpt(excerpt_id, range.start);
5246 let end = snapshot.anchor_in_excerpt(excerpt_id, range.end);
5247 Some(start?..end?)
5248 }),
5249 render_inlay_ids: to_add.iter().map(|i| i.id).collect(),
5250 });
5251
5252 self.display_map
5253 .update(cx, move |map, cx| map.splice_inlays(to_remove, to_add, cx));
5254
5255 cx.notify();
5256 return;
5257 }
5258 }
5259 }
5260 }
5261
5262 self.discard_inline_completion(false, cx);
5263 }
5264
5265 fn inline_completion_provider(&self) -> Option<Arc<dyn InlineCompletionProviderHandle>> {
5266 Some(self.inline_completion_provider.as_ref()?.provider.clone())
5267 }
5268
5269 fn render_code_actions_indicator(
5270 &self,
5271 _style: &EditorStyle,
5272 row: DisplayRow,
5273 is_active: bool,
5274 cx: &mut ViewContext<Self>,
5275 ) -> Option<IconButton> {
5276 if self.available_code_actions.is_some() {
5277 Some(
5278 IconButton::new("code_actions_indicator", ui::IconName::Bolt)
5279 .shape(ui::IconButtonShape::Square)
5280 .icon_size(IconSize::XSmall)
5281 .icon_color(Color::Muted)
5282 .selected(is_active)
5283 .on_click(cx.listener(move |editor, _e, cx| {
5284 editor.focus(cx);
5285 editor.toggle_code_actions(
5286 &ToggleCodeActions {
5287 deployed_from_indicator: Some(row),
5288 },
5289 cx,
5290 );
5291 })),
5292 )
5293 } else {
5294 None
5295 }
5296 }
5297
5298 fn clear_tasks(&mut self) {
5299 self.tasks.clear()
5300 }
5301
5302 fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
5303 if self.tasks.insert(key, value).is_some() {
5304 // This case should hopefully be rare, but just in case...
5305 log::error!("multiple different run targets found on a single line, only the last target will be rendered")
5306 }
5307 }
5308
5309 fn render_run_indicator(
5310 &self,
5311 _style: &EditorStyle,
5312 is_active: bool,
5313 row: DisplayRow,
5314 cx: &mut ViewContext<Self>,
5315 ) -> IconButton {
5316 IconButton::new(("run_indicator", row.0 as usize), ui::IconName::Play)
5317 .shape(ui::IconButtonShape::Square)
5318 .icon_size(IconSize::XSmall)
5319 .icon_color(Color::Muted)
5320 .selected(is_active)
5321 .on_click(cx.listener(move |editor, _e, cx| {
5322 editor.focus(cx);
5323 editor.toggle_code_actions(
5324 &ToggleCodeActions {
5325 deployed_from_indicator: Some(row),
5326 },
5327 cx,
5328 );
5329 }))
5330 }
5331
5332 fn close_hunk_diff_button(
5333 &self,
5334 hunk: HoveredHunk,
5335 row: DisplayRow,
5336 cx: &mut ViewContext<Self>,
5337 ) -> IconButton {
5338 IconButton::new(
5339 ("close_hunk_diff_indicator", row.0 as usize),
5340 ui::IconName::Close,
5341 )
5342 .shape(ui::IconButtonShape::Square)
5343 .icon_size(IconSize::XSmall)
5344 .icon_color(Color::Muted)
5345 .tooltip(|cx| Tooltip::for_action("Close hunk diff", &ToggleHunkDiff, cx))
5346 .on_click(cx.listener(move |editor, _e, cx| editor.toggle_hovered_hunk(&hunk, cx)))
5347 }
5348
5349 pub fn context_menu_visible(&self) -> bool {
5350 self.context_menu
5351 .read()
5352 .as_ref()
5353 .map_or(false, |menu| menu.visible())
5354 }
5355
5356 fn render_context_menu(
5357 &self,
5358 cursor_position: DisplayPoint,
5359 style: &EditorStyle,
5360 max_height: Pixels,
5361 cx: &mut ViewContext<Editor>,
5362 ) -> Option<(ContextMenuOrigin, AnyElement)> {
5363 self.context_menu.read().as_ref().map(|menu| {
5364 menu.render(
5365 cursor_position,
5366 style,
5367 max_height,
5368 self.workspace.as_ref().map(|(w, _)| w.clone()),
5369 cx,
5370 )
5371 })
5372 }
5373
5374 fn hide_context_menu(&mut self, cx: &mut ViewContext<Self>) -> Option<ContextMenu> {
5375 cx.notify();
5376 self.completion_tasks.clear();
5377 let context_menu = self.context_menu.write().take();
5378 if context_menu.is_some() {
5379 self.update_visible_inline_completion(cx);
5380 }
5381 context_menu
5382 }
5383
5384 pub fn insert_snippet(
5385 &mut self,
5386 insertion_ranges: &[Range<usize>],
5387 snippet: Snippet,
5388 cx: &mut ViewContext<Self>,
5389 ) -> Result<()> {
5390 struct Tabstop<T> {
5391 is_end_tabstop: bool,
5392 ranges: Vec<Range<T>>,
5393 }
5394
5395 let tabstops = self.buffer.update(cx, |buffer, cx| {
5396 let snippet_text: Arc<str> = snippet.text.clone().into();
5397 buffer.edit(
5398 insertion_ranges
5399 .iter()
5400 .cloned()
5401 .map(|range| (range, snippet_text.clone())),
5402 Some(AutoindentMode::EachLine),
5403 cx,
5404 );
5405
5406 let snapshot = &*buffer.read(cx);
5407 let snippet = &snippet;
5408 snippet
5409 .tabstops
5410 .iter()
5411 .map(|tabstop| {
5412 let is_end_tabstop = tabstop.first().map_or(false, |tabstop| {
5413 tabstop.is_empty() && tabstop.start == snippet.text.len() as isize
5414 });
5415 let mut tabstop_ranges = tabstop
5416 .iter()
5417 .flat_map(|tabstop_range| {
5418 let mut delta = 0_isize;
5419 insertion_ranges.iter().map(move |insertion_range| {
5420 let insertion_start = insertion_range.start as isize + delta;
5421 delta +=
5422 snippet.text.len() as isize - insertion_range.len() as isize;
5423
5424 let start = ((insertion_start + tabstop_range.start) as usize)
5425 .min(snapshot.len());
5426 let end = ((insertion_start + tabstop_range.end) as usize)
5427 .min(snapshot.len());
5428 snapshot.anchor_before(start)..snapshot.anchor_after(end)
5429 })
5430 })
5431 .collect::<Vec<_>>();
5432 tabstop_ranges.sort_unstable_by(|a, b| a.start.cmp(&b.start, snapshot));
5433
5434 Tabstop {
5435 is_end_tabstop,
5436 ranges: tabstop_ranges,
5437 }
5438 })
5439 .collect::<Vec<_>>()
5440 });
5441 if let Some(tabstop) = tabstops.first() {
5442 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5443 s.select_ranges(tabstop.ranges.iter().cloned());
5444 });
5445
5446 // If we're already at the last tabstop and it's at the end of the snippet,
5447 // we're done, we don't need to keep the state around.
5448 if !tabstop.is_end_tabstop {
5449 let ranges = tabstops
5450 .into_iter()
5451 .map(|tabstop| tabstop.ranges)
5452 .collect::<Vec<_>>();
5453 self.snippet_stack.push(SnippetState {
5454 active_index: 0,
5455 ranges,
5456 });
5457 }
5458
5459 // Check whether the just-entered snippet ends with an auto-closable bracket.
5460 if self.autoclose_regions.is_empty() {
5461 let snapshot = self.buffer.read(cx).snapshot(cx);
5462 for selection in &mut self.selections.all::<Point>(cx) {
5463 let selection_head = selection.head();
5464 let Some(scope) = snapshot.language_scope_at(selection_head) else {
5465 continue;
5466 };
5467
5468 let mut bracket_pair = None;
5469 let next_chars = snapshot.chars_at(selection_head).collect::<String>();
5470 let prev_chars = snapshot
5471 .reversed_chars_at(selection_head)
5472 .collect::<String>();
5473 for (pair, enabled) in scope.brackets() {
5474 if enabled
5475 && pair.close
5476 && prev_chars.starts_with(pair.start.as_str())
5477 && next_chars.starts_with(pair.end.as_str())
5478 {
5479 bracket_pair = Some(pair.clone());
5480 break;
5481 }
5482 }
5483 if let Some(pair) = bracket_pair {
5484 let start = snapshot.anchor_after(selection_head);
5485 let end = snapshot.anchor_after(selection_head);
5486 self.autoclose_regions.push(AutocloseRegion {
5487 selection_id: selection.id,
5488 range: start..end,
5489 pair,
5490 });
5491 }
5492 }
5493 }
5494 }
5495 Ok(())
5496 }
5497
5498 pub fn move_to_next_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5499 self.move_to_snippet_tabstop(Bias::Right, cx)
5500 }
5501
5502 pub fn move_to_prev_snippet_tabstop(&mut self, cx: &mut ViewContext<Self>) -> bool {
5503 self.move_to_snippet_tabstop(Bias::Left, cx)
5504 }
5505
5506 pub fn move_to_snippet_tabstop(&mut self, bias: Bias, cx: &mut ViewContext<Self>) -> bool {
5507 if let Some(mut snippet) = self.snippet_stack.pop() {
5508 match bias {
5509 Bias::Left => {
5510 if snippet.active_index > 0 {
5511 snippet.active_index -= 1;
5512 } else {
5513 self.snippet_stack.push(snippet);
5514 return false;
5515 }
5516 }
5517 Bias::Right => {
5518 if snippet.active_index + 1 < snippet.ranges.len() {
5519 snippet.active_index += 1;
5520 } else {
5521 self.snippet_stack.push(snippet);
5522 return false;
5523 }
5524 }
5525 }
5526 if let Some(current_ranges) = snippet.ranges.get(snippet.active_index) {
5527 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
5528 s.select_anchor_ranges(current_ranges.iter().cloned())
5529 });
5530 // If snippet state is not at the last tabstop, push it back on the stack
5531 if snippet.active_index + 1 < snippet.ranges.len() {
5532 self.snippet_stack.push(snippet);
5533 }
5534 return true;
5535 }
5536 }
5537
5538 false
5539 }
5540
5541 pub fn clear(&mut self, cx: &mut ViewContext<Self>) {
5542 self.transact(cx, |this, cx| {
5543 this.select_all(&SelectAll, cx);
5544 this.insert("", cx);
5545 });
5546 }
5547
5548 pub fn backspace(&mut self, _: &Backspace, cx: &mut ViewContext<Self>) {
5549 self.transact(cx, |this, cx| {
5550 this.select_autoclose_pair(cx);
5551 let mut linked_ranges = HashMap::<_, Vec<_>>::default();
5552 if !this.linked_edit_ranges.is_empty() {
5553 let selections = this.selections.all::<MultiBufferPoint>(cx);
5554 let snapshot = this.buffer.read(cx).snapshot(cx);
5555
5556 for selection in selections.iter() {
5557 let selection_start = snapshot.anchor_before(selection.start).text_anchor;
5558 let selection_end = snapshot.anchor_after(selection.end).text_anchor;
5559 if selection_start.buffer_id != selection_end.buffer_id {
5560 continue;
5561 }
5562 if let Some(ranges) =
5563 this.linked_editing_ranges_for(selection_start..selection_end, cx)
5564 {
5565 for (buffer, entries) in ranges {
5566 linked_ranges.entry(buffer).or_default().extend(entries);
5567 }
5568 }
5569 }
5570 }
5571
5572 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
5573 if !this.selections.line_mode {
5574 let display_map = this.display_map.update(cx, |map, cx| map.snapshot(cx));
5575 for selection in &mut selections {
5576 if selection.is_empty() {
5577 let old_head = selection.head();
5578 let mut new_head =
5579 movement::left(&display_map, old_head.to_display_point(&display_map))
5580 .to_point(&display_map);
5581 if let Some((buffer, line_buffer_range)) = display_map
5582 .buffer_snapshot
5583 .buffer_line_for_row(MultiBufferRow(old_head.row))
5584 {
5585 let indent_size =
5586 buffer.indent_size_for_line(line_buffer_range.start.row);
5587 let indent_len = match indent_size.kind {
5588 IndentKind::Space => {
5589 buffer.settings_at(line_buffer_range.start, cx).tab_size
5590 }
5591 IndentKind::Tab => NonZeroU32::new(1).unwrap(),
5592 };
5593 if old_head.column <= indent_size.len && old_head.column > 0 {
5594 let indent_len = indent_len.get();
5595 new_head = cmp::min(
5596 new_head,
5597 MultiBufferPoint::new(
5598 old_head.row,
5599 ((old_head.column - 1) / indent_len) * indent_len,
5600 ),
5601 );
5602 }
5603 }
5604
5605 selection.set_head(new_head, SelectionGoal::None);
5606 }
5607 }
5608 }
5609
5610 this.signature_help_state.set_backspace_pressed(true);
5611 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5612 this.insert("", cx);
5613 let empty_str: Arc<str> = Arc::from("");
5614 for (buffer, edits) in linked_ranges {
5615 let snapshot = buffer.read(cx).snapshot();
5616 use text::ToPoint as TP;
5617
5618 let edits = edits
5619 .into_iter()
5620 .map(|range| {
5621 let end_point = TP::to_point(&range.end, &snapshot);
5622 let mut start_point = TP::to_point(&range.start, &snapshot);
5623
5624 if end_point == start_point {
5625 let offset = text::ToOffset::to_offset(&range.start, &snapshot)
5626 .saturating_sub(1);
5627 start_point = TP::to_point(&offset, &snapshot);
5628 };
5629
5630 (start_point..end_point, empty_str.clone())
5631 })
5632 .sorted_by_key(|(range, _)| range.start)
5633 .collect::<Vec<_>>();
5634 buffer.update(cx, |this, cx| {
5635 this.edit(edits, None, cx);
5636 })
5637 }
5638 this.refresh_inline_completion(true, false, cx);
5639 linked_editing_ranges::refresh_linked_ranges(this, cx);
5640 });
5641 }
5642
5643 pub fn delete(&mut self, _: &Delete, cx: &mut ViewContext<Self>) {
5644 self.transact(cx, |this, cx| {
5645 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5646 let line_mode = s.line_mode;
5647 s.move_with(|map, selection| {
5648 if selection.is_empty() && !line_mode {
5649 let cursor = movement::right(map, selection.head());
5650 selection.end = cursor;
5651 selection.reversed = true;
5652 selection.goal = SelectionGoal::None;
5653 }
5654 })
5655 });
5656 this.insert("", cx);
5657 this.refresh_inline_completion(true, false, cx);
5658 });
5659 }
5660
5661 pub fn tab_prev(&mut self, _: &TabPrev, cx: &mut ViewContext<Self>) {
5662 if self.move_to_prev_snippet_tabstop(cx) {
5663 return;
5664 }
5665
5666 self.outdent(&Outdent, cx);
5667 }
5668
5669 pub fn tab(&mut self, _: &Tab, cx: &mut ViewContext<Self>) {
5670 if self.move_to_next_snippet_tabstop(cx) || self.read_only(cx) {
5671 return;
5672 }
5673
5674 let mut selections = self.selections.all_adjusted(cx);
5675 let buffer = self.buffer.read(cx);
5676 let snapshot = buffer.snapshot(cx);
5677 let rows_iter = selections.iter().map(|s| s.head().row);
5678 let suggested_indents = snapshot.suggested_indents(rows_iter, cx);
5679
5680 let mut edits = Vec::new();
5681 let mut prev_edited_row = 0;
5682 let mut row_delta = 0;
5683 for selection in &mut selections {
5684 if selection.start.row != prev_edited_row {
5685 row_delta = 0;
5686 }
5687 prev_edited_row = selection.end.row;
5688
5689 // If the selection is non-empty, then increase the indentation of the selected lines.
5690 if !selection.is_empty() {
5691 row_delta =
5692 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5693 continue;
5694 }
5695
5696 // If the selection is empty and the cursor is in the leading whitespace before the
5697 // suggested indentation, then auto-indent the line.
5698 let cursor = selection.head();
5699 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(cursor.row));
5700 if let Some(suggested_indent) =
5701 suggested_indents.get(&MultiBufferRow(cursor.row)).copied()
5702 {
5703 if cursor.column < suggested_indent.len
5704 && cursor.column <= current_indent.len
5705 && current_indent.len <= suggested_indent.len
5706 {
5707 selection.start = Point::new(cursor.row, suggested_indent.len);
5708 selection.end = selection.start;
5709 if row_delta == 0 {
5710 edits.extend(Buffer::edit_for_indent_size_adjustment(
5711 cursor.row,
5712 current_indent,
5713 suggested_indent,
5714 ));
5715 row_delta = suggested_indent.len - current_indent.len;
5716 }
5717 continue;
5718 }
5719 }
5720
5721 // Otherwise, insert a hard or soft tab.
5722 let settings = buffer.settings_at(cursor, cx);
5723 let tab_size = if settings.hard_tabs {
5724 IndentSize::tab()
5725 } else {
5726 let tab_size = settings.tab_size.get();
5727 let char_column = snapshot
5728 .text_for_range(Point::new(cursor.row, 0)..cursor)
5729 .flat_map(str::chars)
5730 .count()
5731 + row_delta as usize;
5732 let chars_to_next_tab_stop = tab_size - (char_column as u32 % tab_size);
5733 IndentSize::spaces(chars_to_next_tab_stop)
5734 };
5735 selection.start = Point::new(cursor.row, cursor.column + row_delta + tab_size.len);
5736 selection.end = selection.start;
5737 edits.push((cursor..cursor, tab_size.chars().collect::<String>()));
5738 row_delta += tab_size.len;
5739 }
5740
5741 self.transact(cx, |this, cx| {
5742 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5743 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5744 this.refresh_inline_completion(true, false, cx);
5745 });
5746 }
5747
5748 pub fn indent(&mut self, _: &Indent, cx: &mut ViewContext<Self>) {
5749 if self.read_only(cx) {
5750 return;
5751 }
5752 let mut selections = self.selections.all::<Point>(cx);
5753 let mut prev_edited_row = 0;
5754 let mut row_delta = 0;
5755 let mut edits = Vec::new();
5756 let buffer = self.buffer.read(cx);
5757 let snapshot = buffer.snapshot(cx);
5758 for selection in &mut selections {
5759 if selection.start.row != prev_edited_row {
5760 row_delta = 0;
5761 }
5762 prev_edited_row = selection.end.row;
5763
5764 row_delta =
5765 Self::indent_selection(buffer, &snapshot, selection, &mut edits, row_delta, cx);
5766 }
5767
5768 self.transact(cx, |this, cx| {
5769 this.buffer.update(cx, |b, cx| b.edit(edits, None, cx));
5770 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5771 });
5772 }
5773
5774 fn indent_selection(
5775 buffer: &MultiBuffer,
5776 snapshot: &MultiBufferSnapshot,
5777 selection: &mut Selection<Point>,
5778 edits: &mut Vec<(Range<Point>, String)>,
5779 delta_for_start_row: u32,
5780 cx: &AppContext,
5781 ) -> u32 {
5782 let settings = buffer.settings_at(selection.start, cx);
5783 let tab_size = settings.tab_size.get();
5784 let indent_kind = if settings.hard_tabs {
5785 IndentKind::Tab
5786 } else {
5787 IndentKind::Space
5788 };
5789 let mut start_row = selection.start.row;
5790 let mut end_row = selection.end.row + 1;
5791
5792 // If a selection ends at the beginning of a line, don't indent
5793 // that last line.
5794 if selection.end.column == 0 && selection.end.row > selection.start.row {
5795 end_row -= 1;
5796 }
5797
5798 // Avoid re-indenting a row that has already been indented by a
5799 // previous selection, but still update this selection's column
5800 // to reflect that indentation.
5801 if delta_for_start_row > 0 {
5802 start_row += 1;
5803 selection.start.column += delta_for_start_row;
5804 if selection.end.row == selection.start.row {
5805 selection.end.column += delta_for_start_row;
5806 }
5807 }
5808
5809 let mut delta_for_end_row = 0;
5810 let has_multiple_rows = start_row + 1 != end_row;
5811 for row in start_row..end_row {
5812 let current_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
5813 let indent_delta = match (current_indent.kind, indent_kind) {
5814 (IndentKind::Space, IndentKind::Space) => {
5815 let columns_to_next_tab_stop = tab_size - (current_indent.len % tab_size);
5816 IndentSize::spaces(columns_to_next_tab_stop)
5817 }
5818 (IndentKind::Tab, IndentKind::Space) => IndentSize::spaces(tab_size),
5819 (_, IndentKind::Tab) => IndentSize::tab(),
5820 };
5821
5822 let start = if has_multiple_rows || current_indent.len < selection.start.column {
5823 0
5824 } else {
5825 selection.start.column
5826 };
5827 let row_start = Point::new(row, start);
5828 edits.push((
5829 row_start..row_start,
5830 indent_delta.chars().collect::<String>(),
5831 ));
5832
5833 // Update this selection's endpoints to reflect the indentation.
5834 if row == selection.start.row {
5835 selection.start.column += indent_delta.len;
5836 }
5837 if row == selection.end.row {
5838 selection.end.column += indent_delta.len;
5839 delta_for_end_row = indent_delta.len;
5840 }
5841 }
5842
5843 if selection.start.row == selection.end.row {
5844 delta_for_start_row + delta_for_end_row
5845 } else {
5846 delta_for_end_row
5847 }
5848 }
5849
5850 pub fn outdent(&mut self, _: &Outdent, cx: &mut ViewContext<Self>) {
5851 if self.read_only(cx) {
5852 return;
5853 }
5854 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5855 let selections = self.selections.all::<Point>(cx);
5856 let mut deletion_ranges = Vec::new();
5857 let mut last_outdent = None;
5858 {
5859 let buffer = self.buffer.read(cx);
5860 let snapshot = buffer.snapshot(cx);
5861 for selection in &selections {
5862 let settings = buffer.settings_at(selection.start, cx);
5863 let tab_size = settings.tab_size.get();
5864 let mut rows = selection.spanned_rows(false, &display_map);
5865
5866 // Avoid re-outdenting a row that has already been outdented by a
5867 // previous selection.
5868 if let Some(last_row) = last_outdent {
5869 if last_row == rows.start {
5870 rows.start = rows.start.next_row();
5871 }
5872 }
5873 let has_multiple_rows = rows.len() > 1;
5874 for row in rows.iter_rows() {
5875 let indent_size = snapshot.indent_size_for_line(row);
5876 if indent_size.len > 0 {
5877 let deletion_len = match indent_size.kind {
5878 IndentKind::Space => {
5879 let columns_to_prev_tab_stop = indent_size.len % tab_size;
5880 if columns_to_prev_tab_stop == 0 {
5881 tab_size
5882 } else {
5883 columns_to_prev_tab_stop
5884 }
5885 }
5886 IndentKind::Tab => 1,
5887 };
5888 let start = if has_multiple_rows
5889 || deletion_len > selection.start.column
5890 || indent_size.len < selection.start.column
5891 {
5892 0
5893 } else {
5894 selection.start.column - deletion_len
5895 };
5896 deletion_ranges.push(
5897 Point::new(row.0, start)..Point::new(row.0, start + deletion_len),
5898 );
5899 last_outdent = Some(row);
5900 }
5901 }
5902 }
5903 }
5904
5905 self.transact(cx, |this, cx| {
5906 this.buffer.update(cx, |buffer, cx| {
5907 let empty_str: Arc<str> = Arc::default();
5908 buffer.edit(
5909 deletion_ranges
5910 .into_iter()
5911 .map(|range| (range, empty_str.clone())),
5912 None,
5913 cx,
5914 );
5915 });
5916 let selections = this.selections.all::<usize>(cx);
5917 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
5918 });
5919 }
5920
5921 pub fn delete_line(&mut self, _: &DeleteLine, cx: &mut ViewContext<Self>) {
5922 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
5923 let selections = self.selections.all::<Point>(cx);
5924
5925 let mut new_cursors = Vec::new();
5926 let mut edit_ranges = Vec::new();
5927 let mut selections = selections.iter().peekable();
5928 while let Some(selection) = selections.next() {
5929 let mut rows = selection.spanned_rows(false, &display_map);
5930 let goal_display_column = selection.head().to_display_point(&display_map).column();
5931
5932 // Accumulate contiguous regions of rows that we want to delete.
5933 while let Some(next_selection) = selections.peek() {
5934 let next_rows = next_selection.spanned_rows(false, &display_map);
5935 if next_rows.start <= rows.end {
5936 rows.end = next_rows.end;
5937 selections.next().unwrap();
5938 } else {
5939 break;
5940 }
5941 }
5942
5943 let buffer = &display_map.buffer_snapshot;
5944 let mut edit_start = Point::new(rows.start.0, 0).to_offset(buffer);
5945 let edit_end;
5946 let cursor_buffer_row;
5947 if buffer.max_point().row >= rows.end.0 {
5948 // If there's a line after the range, delete the \n from the end of the row range
5949 // and position the cursor on the next line.
5950 edit_end = Point::new(rows.end.0, 0).to_offset(buffer);
5951 cursor_buffer_row = rows.end;
5952 } else {
5953 // If there isn't a line after the range, delete the \n from the line before the
5954 // start of the row range and position the cursor there.
5955 edit_start = edit_start.saturating_sub(1);
5956 edit_end = buffer.len();
5957 cursor_buffer_row = rows.start.previous_row();
5958 }
5959
5960 let mut cursor = Point::new(cursor_buffer_row.0, 0).to_display_point(&display_map);
5961 *cursor.column_mut() =
5962 cmp::min(goal_display_column, display_map.line_len(cursor.row()));
5963
5964 new_cursors.push((
5965 selection.id,
5966 buffer.anchor_after(cursor.to_point(&display_map)),
5967 ));
5968 edit_ranges.push(edit_start..edit_end);
5969 }
5970
5971 self.transact(cx, |this, cx| {
5972 let buffer = this.buffer.update(cx, |buffer, cx| {
5973 let empty_str: Arc<str> = Arc::default();
5974 buffer.edit(
5975 edit_ranges
5976 .into_iter()
5977 .map(|range| (range, empty_str.clone())),
5978 None,
5979 cx,
5980 );
5981 buffer.snapshot(cx)
5982 });
5983 let new_selections = new_cursors
5984 .into_iter()
5985 .map(|(id, cursor)| {
5986 let cursor = cursor.to_point(&buffer);
5987 Selection {
5988 id,
5989 start: cursor,
5990 end: cursor,
5991 reversed: false,
5992 goal: SelectionGoal::None,
5993 }
5994 })
5995 .collect();
5996
5997 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
5998 s.select(new_selections);
5999 });
6000 });
6001 }
6002
6003 pub fn join_lines(&mut self, _: &JoinLines, cx: &mut ViewContext<Self>) {
6004 if self.read_only(cx) {
6005 return;
6006 }
6007 let mut row_ranges = Vec::<Range<MultiBufferRow>>::new();
6008 for selection in self.selections.all::<Point>(cx) {
6009 let start = MultiBufferRow(selection.start.row);
6010 let end = if selection.start.row == selection.end.row {
6011 MultiBufferRow(selection.start.row + 1)
6012 } else {
6013 MultiBufferRow(selection.end.row)
6014 };
6015
6016 if let Some(last_row_range) = row_ranges.last_mut() {
6017 if start <= last_row_range.end {
6018 last_row_range.end = end;
6019 continue;
6020 }
6021 }
6022 row_ranges.push(start..end);
6023 }
6024
6025 let snapshot = self.buffer.read(cx).snapshot(cx);
6026 let mut cursor_positions = Vec::new();
6027 for row_range in &row_ranges {
6028 let anchor = snapshot.anchor_before(Point::new(
6029 row_range.end.previous_row().0,
6030 snapshot.line_len(row_range.end.previous_row()),
6031 ));
6032 cursor_positions.push(anchor..anchor);
6033 }
6034
6035 self.transact(cx, |this, cx| {
6036 for row_range in row_ranges.into_iter().rev() {
6037 for row in row_range.iter_rows().rev() {
6038 let end_of_line = Point::new(row.0, snapshot.line_len(row));
6039 let next_line_row = row.next_row();
6040 let indent = snapshot.indent_size_for_line(next_line_row);
6041 let start_of_next_line = Point::new(next_line_row.0, indent.len);
6042
6043 let replace = if snapshot.line_len(next_line_row) > indent.len {
6044 " "
6045 } else {
6046 ""
6047 };
6048
6049 this.buffer.update(cx, |buffer, cx| {
6050 buffer.edit([(end_of_line..start_of_next_line, replace)], None, cx)
6051 });
6052 }
6053 }
6054
6055 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6056 s.select_anchor_ranges(cursor_positions)
6057 });
6058 });
6059 }
6060
6061 pub fn sort_lines_case_sensitive(
6062 &mut self,
6063 _: &SortLinesCaseSensitive,
6064 cx: &mut ViewContext<Self>,
6065 ) {
6066 self.manipulate_lines(cx, |lines| lines.sort())
6067 }
6068
6069 pub fn sort_lines_case_insensitive(
6070 &mut self,
6071 _: &SortLinesCaseInsensitive,
6072 cx: &mut ViewContext<Self>,
6073 ) {
6074 self.manipulate_lines(cx, |lines| lines.sort_by_key(|line| line.to_lowercase()))
6075 }
6076
6077 pub fn unique_lines_case_insensitive(
6078 &mut self,
6079 _: &UniqueLinesCaseInsensitive,
6080 cx: &mut ViewContext<Self>,
6081 ) {
6082 self.manipulate_lines(cx, |lines| {
6083 let mut seen = HashSet::default();
6084 lines.retain(|line| seen.insert(line.to_lowercase()));
6085 })
6086 }
6087
6088 pub fn unique_lines_case_sensitive(
6089 &mut self,
6090 _: &UniqueLinesCaseSensitive,
6091 cx: &mut ViewContext<Self>,
6092 ) {
6093 self.manipulate_lines(cx, |lines| {
6094 let mut seen = HashSet::default();
6095 lines.retain(|line| seen.insert(*line));
6096 })
6097 }
6098
6099 pub fn revert_file(&mut self, _: &RevertFile, cx: &mut ViewContext<Self>) {
6100 let mut revert_changes = HashMap::default();
6101 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6102 for hunk in hunks_for_rows(
6103 Some(MultiBufferRow(0)..multi_buffer_snapshot.max_buffer_row()).into_iter(),
6104 &multi_buffer_snapshot,
6105 ) {
6106 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6107 }
6108 if !revert_changes.is_empty() {
6109 self.transact(cx, |editor, cx| {
6110 editor.revert(revert_changes, cx);
6111 });
6112 }
6113 }
6114
6115 pub fn revert_selected_hunks(&mut self, _: &RevertSelectedHunks, cx: &mut ViewContext<Self>) {
6116 let revert_changes = self.gather_revert_changes(&self.selections.disjoint_anchors(), cx);
6117 if !revert_changes.is_empty() {
6118 self.transact(cx, |editor, cx| {
6119 editor.revert(revert_changes, cx);
6120 });
6121 }
6122 }
6123
6124 pub fn open_active_item_in_terminal(&mut self, _: &OpenInTerminal, cx: &mut ViewContext<Self>) {
6125 if let Some(working_directory) = self.active_excerpt(cx).and_then(|(_, buffer, _)| {
6126 let project_path = buffer.read(cx).project_path(cx)?;
6127 let project = self.project.as_ref()?.read(cx);
6128 let entry = project.entry_for_path(&project_path, cx)?;
6129 let abs_path = project.absolute_path(&project_path, cx)?;
6130 let parent = if entry.is_symlink {
6131 abs_path.canonicalize().ok()?
6132 } else {
6133 abs_path
6134 }
6135 .parent()?
6136 .to_path_buf();
6137 Some(parent)
6138 }) {
6139 cx.dispatch_action(OpenTerminal { working_directory }.boxed_clone());
6140 }
6141 }
6142
6143 fn gather_revert_changes(
6144 &mut self,
6145 selections: &[Selection<Anchor>],
6146 cx: &mut ViewContext<'_, Editor>,
6147 ) -> HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>> {
6148 let mut revert_changes = HashMap::default();
6149 let multi_buffer_snapshot = self.buffer.read(cx).snapshot(cx);
6150 for hunk in hunks_for_selections(&multi_buffer_snapshot, selections) {
6151 Self::prepare_revert_change(&mut revert_changes, self.buffer(), &hunk, cx);
6152 }
6153 revert_changes
6154 }
6155
6156 pub fn prepare_revert_change(
6157 revert_changes: &mut HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
6158 multi_buffer: &Model<MultiBuffer>,
6159 hunk: &MultiBufferDiffHunk,
6160 cx: &AppContext,
6161 ) -> Option<()> {
6162 let buffer = multi_buffer.read(cx).buffer(hunk.buffer_id)?;
6163 let buffer = buffer.read(cx);
6164 let original_text = buffer.diff_base()?.slice(hunk.diff_base_byte_range.clone());
6165 let buffer_snapshot = buffer.snapshot();
6166 let buffer_revert_changes = revert_changes.entry(buffer.remote_id()).or_default();
6167 if let Err(i) = buffer_revert_changes.binary_search_by(|probe| {
6168 probe
6169 .0
6170 .start
6171 .cmp(&hunk.buffer_range.start, &buffer_snapshot)
6172 .then(probe.0.end.cmp(&hunk.buffer_range.end, &buffer_snapshot))
6173 }) {
6174 buffer_revert_changes.insert(i, (hunk.buffer_range.clone(), original_text));
6175 Some(())
6176 } else {
6177 None
6178 }
6179 }
6180
6181 pub fn reverse_lines(&mut self, _: &ReverseLines, cx: &mut ViewContext<Self>) {
6182 self.manipulate_lines(cx, |lines| lines.reverse())
6183 }
6184
6185 pub fn shuffle_lines(&mut self, _: &ShuffleLines, cx: &mut ViewContext<Self>) {
6186 self.manipulate_lines(cx, |lines| lines.shuffle(&mut thread_rng()))
6187 }
6188
6189 fn manipulate_lines<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6190 where
6191 Fn: FnMut(&mut Vec<&str>),
6192 {
6193 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6194 let buffer = self.buffer.read(cx).snapshot(cx);
6195
6196 let mut edits = Vec::new();
6197
6198 let selections = self.selections.all::<Point>(cx);
6199 let mut selections = selections.iter().peekable();
6200 let mut contiguous_row_selections = Vec::new();
6201 let mut new_selections = Vec::new();
6202 let mut added_lines = 0;
6203 let mut removed_lines = 0;
6204
6205 while let Some(selection) = selections.next() {
6206 let (start_row, end_row) = consume_contiguous_rows(
6207 &mut contiguous_row_selections,
6208 selection,
6209 &display_map,
6210 &mut selections,
6211 );
6212
6213 let start_point = Point::new(start_row.0, 0);
6214 let end_point = Point::new(
6215 end_row.previous_row().0,
6216 buffer.line_len(end_row.previous_row()),
6217 );
6218 let text = buffer
6219 .text_for_range(start_point..end_point)
6220 .collect::<String>();
6221
6222 let mut lines = text.split('\n').collect_vec();
6223
6224 let lines_before = lines.len();
6225 callback(&mut lines);
6226 let lines_after = lines.len();
6227
6228 edits.push((start_point..end_point, lines.join("\n")));
6229
6230 // Selections must change based on added and removed line count
6231 let start_row =
6232 MultiBufferRow(start_point.row + added_lines as u32 - removed_lines as u32);
6233 let end_row = MultiBufferRow(start_row.0 + lines_after.saturating_sub(1) as u32);
6234 new_selections.push(Selection {
6235 id: selection.id,
6236 start: start_row,
6237 end: end_row,
6238 goal: SelectionGoal::None,
6239 reversed: selection.reversed,
6240 });
6241
6242 if lines_after > lines_before {
6243 added_lines += lines_after - lines_before;
6244 } else if lines_before > lines_after {
6245 removed_lines += lines_before - lines_after;
6246 }
6247 }
6248
6249 self.transact(cx, |this, cx| {
6250 let buffer = this.buffer.update(cx, |buffer, cx| {
6251 buffer.edit(edits, None, cx);
6252 buffer.snapshot(cx)
6253 });
6254
6255 // Recalculate offsets on newly edited buffer
6256 let new_selections = new_selections
6257 .iter()
6258 .map(|s| {
6259 let start_point = Point::new(s.start.0, 0);
6260 let end_point = Point::new(s.end.0, buffer.line_len(s.end));
6261 Selection {
6262 id: s.id,
6263 start: buffer.point_to_offset(start_point),
6264 end: buffer.point_to_offset(end_point),
6265 goal: s.goal,
6266 reversed: s.reversed,
6267 }
6268 })
6269 .collect();
6270
6271 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6272 s.select(new_selections);
6273 });
6274
6275 this.request_autoscroll(Autoscroll::fit(), cx);
6276 });
6277 }
6278
6279 pub fn convert_to_upper_case(&mut self, _: &ConvertToUpperCase, cx: &mut ViewContext<Self>) {
6280 self.manipulate_text(cx, |text| text.to_uppercase())
6281 }
6282
6283 pub fn convert_to_lower_case(&mut self, _: &ConvertToLowerCase, cx: &mut ViewContext<Self>) {
6284 self.manipulate_text(cx, |text| text.to_lowercase())
6285 }
6286
6287 pub fn convert_to_title_case(&mut self, _: &ConvertToTitleCase, cx: &mut ViewContext<Self>) {
6288 self.manipulate_text(cx, |text| {
6289 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6290 // https://github.com/rutrum/convert-case/issues/16
6291 text.split('\n')
6292 .map(|line| line.to_case(Case::Title))
6293 .join("\n")
6294 })
6295 }
6296
6297 pub fn convert_to_snake_case(&mut self, _: &ConvertToSnakeCase, cx: &mut ViewContext<Self>) {
6298 self.manipulate_text(cx, |text| text.to_case(Case::Snake))
6299 }
6300
6301 pub fn convert_to_kebab_case(&mut self, _: &ConvertToKebabCase, cx: &mut ViewContext<Self>) {
6302 self.manipulate_text(cx, |text| text.to_case(Case::Kebab))
6303 }
6304
6305 pub fn convert_to_upper_camel_case(
6306 &mut self,
6307 _: &ConvertToUpperCamelCase,
6308 cx: &mut ViewContext<Self>,
6309 ) {
6310 self.manipulate_text(cx, |text| {
6311 // Hack to get around the fact that to_case crate doesn't support '\n' as a word boundary
6312 // https://github.com/rutrum/convert-case/issues/16
6313 text.split('\n')
6314 .map(|line| line.to_case(Case::UpperCamel))
6315 .join("\n")
6316 })
6317 }
6318
6319 pub fn convert_to_lower_camel_case(
6320 &mut self,
6321 _: &ConvertToLowerCamelCase,
6322 cx: &mut ViewContext<Self>,
6323 ) {
6324 self.manipulate_text(cx, |text| text.to_case(Case::Camel))
6325 }
6326
6327 pub fn convert_to_opposite_case(
6328 &mut self,
6329 _: &ConvertToOppositeCase,
6330 cx: &mut ViewContext<Self>,
6331 ) {
6332 self.manipulate_text(cx, |text| {
6333 text.chars()
6334 .fold(String::with_capacity(text.len()), |mut t, c| {
6335 if c.is_uppercase() {
6336 t.extend(c.to_lowercase());
6337 } else {
6338 t.extend(c.to_uppercase());
6339 }
6340 t
6341 })
6342 })
6343 }
6344
6345 fn manipulate_text<Fn>(&mut self, cx: &mut ViewContext<Self>, mut callback: Fn)
6346 where
6347 Fn: FnMut(&str) -> String,
6348 {
6349 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6350 let buffer = self.buffer.read(cx).snapshot(cx);
6351
6352 let mut new_selections = Vec::new();
6353 let mut edits = Vec::new();
6354 let mut selection_adjustment = 0i32;
6355
6356 for selection in self.selections.all::<usize>(cx) {
6357 let selection_is_empty = selection.is_empty();
6358
6359 let (start, end) = if selection_is_empty {
6360 let word_range = movement::surrounding_word(
6361 &display_map,
6362 selection.start.to_display_point(&display_map),
6363 );
6364 let start = word_range.start.to_offset(&display_map, Bias::Left);
6365 let end = word_range.end.to_offset(&display_map, Bias::Left);
6366 (start, end)
6367 } else {
6368 (selection.start, selection.end)
6369 };
6370
6371 let text = buffer.text_for_range(start..end).collect::<String>();
6372 let old_length = text.len() as i32;
6373 let text = callback(&text);
6374
6375 new_selections.push(Selection {
6376 start: (start as i32 - selection_adjustment) as usize,
6377 end: ((start + text.len()) as i32 - selection_adjustment) as usize,
6378 goal: SelectionGoal::None,
6379 ..selection
6380 });
6381
6382 selection_adjustment += old_length - text.len() as i32;
6383
6384 edits.push((start..end, text));
6385 }
6386
6387 self.transact(cx, |this, cx| {
6388 this.buffer.update(cx, |buffer, cx| {
6389 buffer.edit(edits, None, cx);
6390 });
6391
6392 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6393 s.select(new_selections);
6394 });
6395
6396 this.request_autoscroll(Autoscroll::fit(), cx);
6397 });
6398 }
6399
6400 pub fn duplicate_line(&mut self, upwards: bool, cx: &mut ViewContext<Self>) {
6401 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6402 let buffer = &display_map.buffer_snapshot;
6403 let selections = self.selections.all::<Point>(cx);
6404
6405 let mut edits = Vec::new();
6406 let mut selections_iter = selections.iter().peekable();
6407 while let Some(selection) = selections_iter.next() {
6408 // Avoid duplicating the same lines twice.
6409 let mut rows = selection.spanned_rows(false, &display_map);
6410
6411 while let Some(next_selection) = selections_iter.peek() {
6412 let next_rows = next_selection.spanned_rows(false, &display_map);
6413 if next_rows.start < rows.end {
6414 rows.end = next_rows.end;
6415 selections_iter.next().unwrap();
6416 } else {
6417 break;
6418 }
6419 }
6420
6421 // Copy the text from the selected row region and splice it either at the start
6422 // or end of the region.
6423 let start = Point::new(rows.start.0, 0);
6424 let end = Point::new(
6425 rows.end.previous_row().0,
6426 buffer.line_len(rows.end.previous_row()),
6427 );
6428 let text = buffer
6429 .text_for_range(start..end)
6430 .chain(Some("\n"))
6431 .collect::<String>();
6432 let insert_location = if upwards {
6433 Point::new(rows.end.0, 0)
6434 } else {
6435 start
6436 };
6437 edits.push((insert_location..insert_location, text));
6438 }
6439
6440 self.transact(cx, |this, cx| {
6441 this.buffer.update(cx, |buffer, cx| {
6442 buffer.edit(edits, None, cx);
6443 });
6444
6445 this.request_autoscroll(Autoscroll::fit(), cx);
6446 });
6447 }
6448
6449 pub fn duplicate_line_up(&mut self, _: &DuplicateLineUp, cx: &mut ViewContext<Self>) {
6450 self.duplicate_line(true, cx);
6451 }
6452
6453 pub fn duplicate_line_down(&mut self, _: &DuplicateLineDown, cx: &mut ViewContext<Self>) {
6454 self.duplicate_line(false, cx);
6455 }
6456
6457 pub fn move_line_up(&mut self, _: &MoveLineUp, cx: &mut ViewContext<Self>) {
6458 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6459 let buffer = self.buffer.read(cx).snapshot(cx);
6460
6461 let mut edits = Vec::new();
6462 let mut unfold_ranges = Vec::new();
6463 let mut refold_ranges = Vec::new();
6464
6465 let selections = self.selections.all::<Point>(cx);
6466 let mut selections = selections.iter().peekable();
6467 let mut contiguous_row_selections = Vec::new();
6468 let mut new_selections = Vec::new();
6469
6470 while let Some(selection) = selections.next() {
6471 // Find all the selections that span a contiguous row range
6472 let (start_row, end_row) = consume_contiguous_rows(
6473 &mut contiguous_row_selections,
6474 selection,
6475 &display_map,
6476 &mut selections,
6477 );
6478
6479 // Move the text spanned by the row range to be before the line preceding the row range
6480 if start_row.0 > 0 {
6481 let range_to_move = Point::new(
6482 start_row.previous_row().0,
6483 buffer.line_len(start_row.previous_row()),
6484 )
6485 ..Point::new(
6486 end_row.previous_row().0,
6487 buffer.line_len(end_row.previous_row()),
6488 );
6489 let insertion_point = display_map
6490 .prev_line_boundary(Point::new(start_row.previous_row().0, 0))
6491 .0;
6492
6493 // Don't move lines across excerpts
6494 if buffer
6495 .excerpt_boundaries_in_range((
6496 Bound::Excluded(insertion_point),
6497 Bound::Included(range_to_move.end),
6498 ))
6499 .next()
6500 .is_none()
6501 {
6502 let text = buffer
6503 .text_for_range(range_to_move.clone())
6504 .flat_map(|s| s.chars())
6505 .skip(1)
6506 .chain(['\n'])
6507 .collect::<String>();
6508
6509 edits.push((
6510 buffer.anchor_after(range_to_move.start)
6511 ..buffer.anchor_before(range_to_move.end),
6512 String::new(),
6513 ));
6514 let insertion_anchor = buffer.anchor_after(insertion_point);
6515 edits.push((insertion_anchor..insertion_anchor, text));
6516
6517 let row_delta = range_to_move.start.row - insertion_point.row + 1;
6518
6519 // Move selections up
6520 new_selections.extend(contiguous_row_selections.drain(..).map(
6521 |mut selection| {
6522 selection.start.row -= row_delta;
6523 selection.end.row -= row_delta;
6524 selection
6525 },
6526 ));
6527
6528 // Move folds up
6529 unfold_ranges.push(range_to_move.clone());
6530 for fold in display_map.folds_in_range(
6531 buffer.anchor_before(range_to_move.start)
6532 ..buffer.anchor_after(range_to_move.end),
6533 ) {
6534 let mut start = fold.range.start.to_point(&buffer);
6535 let mut end = fold.range.end.to_point(&buffer);
6536 start.row -= row_delta;
6537 end.row -= row_delta;
6538 refold_ranges.push((start..end, fold.placeholder.clone()));
6539 }
6540 }
6541 }
6542
6543 // If we didn't move line(s), preserve the existing selections
6544 new_selections.append(&mut contiguous_row_selections);
6545 }
6546
6547 self.transact(cx, |this, cx| {
6548 this.unfold_ranges(unfold_ranges, true, true, cx);
6549 this.buffer.update(cx, |buffer, cx| {
6550 for (range, text) in edits {
6551 buffer.edit([(range, text)], None, cx);
6552 }
6553 });
6554 this.fold_ranges(refold_ranges, true, cx);
6555 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6556 s.select(new_selections);
6557 })
6558 });
6559 }
6560
6561 pub fn move_line_down(&mut self, _: &MoveLineDown, cx: &mut ViewContext<Self>) {
6562 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
6563 let buffer = self.buffer.read(cx).snapshot(cx);
6564
6565 let mut edits = Vec::new();
6566 let mut unfold_ranges = Vec::new();
6567 let mut refold_ranges = Vec::new();
6568
6569 let selections = self.selections.all::<Point>(cx);
6570 let mut selections = selections.iter().peekable();
6571 let mut contiguous_row_selections = Vec::new();
6572 let mut new_selections = Vec::new();
6573
6574 while let Some(selection) = selections.next() {
6575 // Find all the selections that span a contiguous row range
6576 let (start_row, end_row) = consume_contiguous_rows(
6577 &mut contiguous_row_selections,
6578 selection,
6579 &display_map,
6580 &mut selections,
6581 );
6582
6583 // Move the text spanned by the row range to be after the last line of the row range
6584 if end_row.0 <= buffer.max_point().row {
6585 let range_to_move =
6586 MultiBufferPoint::new(start_row.0, 0)..MultiBufferPoint::new(end_row.0, 0);
6587 let insertion_point = display_map
6588 .next_line_boundary(MultiBufferPoint::new(end_row.0, 0))
6589 .0;
6590
6591 // Don't move lines across excerpt boundaries
6592 if buffer
6593 .excerpt_boundaries_in_range((
6594 Bound::Excluded(range_to_move.start),
6595 Bound::Included(insertion_point),
6596 ))
6597 .next()
6598 .is_none()
6599 {
6600 let mut text = String::from("\n");
6601 text.extend(buffer.text_for_range(range_to_move.clone()));
6602 text.pop(); // Drop trailing newline
6603 edits.push((
6604 buffer.anchor_after(range_to_move.start)
6605 ..buffer.anchor_before(range_to_move.end),
6606 String::new(),
6607 ));
6608 let insertion_anchor = buffer.anchor_after(insertion_point);
6609 edits.push((insertion_anchor..insertion_anchor, text));
6610
6611 let row_delta = insertion_point.row - range_to_move.end.row + 1;
6612
6613 // Move selections down
6614 new_selections.extend(contiguous_row_selections.drain(..).map(
6615 |mut selection| {
6616 selection.start.row += row_delta;
6617 selection.end.row += row_delta;
6618 selection
6619 },
6620 ));
6621
6622 // Move folds down
6623 unfold_ranges.push(range_to_move.clone());
6624 for fold in display_map.folds_in_range(
6625 buffer.anchor_before(range_to_move.start)
6626 ..buffer.anchor_after(range_to_move.end),
6627 ) {
6628 let mut start = fold.range.start.to_point(&buffer);
6629 let mut end = fold.range.end.to_point(&buffer);
6630 start.row += row_delta;
6631 end.row += row_delta;
6632 refold_ranges.push((start..end, fold.placeholder.clone()));
6633 }
6634 }
6635 }
6636
6637 // If we didn't move line(s), preserve the existing selections
6638 new_selections.append(&mut contiguous_row_selections);
6639 }
6640
6641 self.transact(cx, |this, cx| {
6642 this.unfold_ranges(unfold_ranges, true, true, cx);
6643 this.buffer.update(cx, |buffer, cx| {
6644 for (range, text) in edits {
6645 buffer.edit([(range, text)], None, cx);
6646 }
6647 });
6648 this.fold_ranges(refold_ranges, true, cx);
6649 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(new_selections));
6650 });
6651 }
6652
6653 pub fn transpose(&mut self, _: &Transpose, cx: &mut ViewContext<Self>) {
6654 let text_layout_details = &self.text_layout_details(cx);
6655 self.transact(cx, |this, cx| {
6656 let edits = this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6657 let mut edits: Vec<(Range<usize>, String)> = Default::default();
6658 let line_mode = s.line_mode;
6659 s.move_with(|display_map, selection| {
6660 if !selection.is_empty() || line_mode {
6661 return;
6662 }
6663
6664 let mut head = selection.head();
6665 let mut transpose_offset = head.to_offset(display_map, Bias::Right);
6666 if head.column() == display_map.line_len(head.row()) {
6667 transpose_offset = display_map
6668 .buffer_snapshot
6669 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6670 }
6671
6672 if transpose_offset == 0 {
6673 return;
6674 }
6675
6676 *head.column_mut() += 1;
6677 head = display_map.clip_point(head, Bias::Right);
6678 let goal = SelectionGoal::HorizontalPosition(
6679 display_map
6680 .x_for_display_point(head, text_layout_details)
6681 .into(),
6682 );
6683 selection.collapse_to(head, goal);
6684
6685 let transpose_start = display_map
6686 .buffer_snapshot
6687 .clip_offset(transpose_offset.saturating_sub(1), Bias::Left);
6688 if edits.last().map_or(true, |e| e.0.end <= transpose_start) {
6689 let transpose_end = display_map
6690 .buffer_snapshot
6691 .clip_offset(transpose_offset + 1, Bias::Right);
6692 if let Some(ch) =
6693 display_map.buffer_snapshot.chars_at(transpose_start).next()
6694 {
6695 edits.push((transpose_start..transpose_offset, String::new()));
6696 edits.push((transpose_end..transpose_end, ch.to_string()));
6697 }
6698 }
6699 });
6700 edits
6701 });
6702 this.buffer
6703 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6704 let selections = this.selections.all::<usize>(cx);
6705 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6706 s.select(selections);
6707 });
6708 });
6709 }
6710
6711 pub fn rewrap(&mut self, _: &Rewrap, cx: &mut ViewContext<Self>) {
6712 self.rewrap_impl(true, cx)
6713 }
6714
6715 pub fn rewrap_impl(&mut self, only_text: bool, cx: &mut ViewContext<Self>) {
6716 let buffer = self.buffer.read(cx).snapshot(cx);
6717 let selections = self.selections.all::<Point>(cx);
6718 let mut selections = selections.iter().peekable();
6719
6720 let mut edits = Vec::new();
6721 let mut rewrapped_row_ranges = Vec::<RangeInclusive<u32>>::new();
6722
6723 while let Some(selection) = selections.next() {
6724 let mut start_row = selection.start.row;
6725 let mut end_row = selection.end.row;
6726
6727 // Skip selections that overlap with a range that has already been rewrapped.
6728 let selection_range = start_row..end_row;
6729 if rewrapped_row_ranges
6730 .iter()
6731 .any(|range| range.overlaps(&selection_range))
6732 {
6733 continue;
6734 }
6735
6736 let mut should_rewrap = !only_text;
6737
6738 if let Some(language_scope) = buffer.language_scope_at(selection.head()) {
6739 match language_scope.language_name().0.as_ref() {
6740 "Markdown" | "Plain Text" => {
6741 should_rewrap = true;
6742 }
6743 _ => {}
6744 }
6745 }
6746
6747 // Since not all lines in the selection may be at the same indent
6748 // level, choose the indent size that is the most common between all
6749 // of the lines.
6750 //
6751 // If there is a tie, we use the deepest indent.
6752 let (indent_size, indent_end) = {
6753 let mut indent_size_occurrences = HashMap::default();
6754 let mut rows_by_indent_size = HashMap::<IndentSize, Vec<u32>>::default();
6755
6756 for row in start_row..=end_row {
6757 let indent = buffer.indent_size_for_line(MultiBufferRow(row));
6758 rows_by_indent_size.entry(indent).or_default().push(row);
6759 *indent_size_occurrences.entry(indent).or_insert(0) += 1;
6760 }
6761
6762 let indent_size = indent_size_occurrences
6763 .into_iter()
6764 .max_by_key(|(indent, count)| (*count, indent.len))
6765 .map(|(indent, _)| indent)
6766 .unwrap_or_default();
6767 let row = rows_by_indent_size[&indent_size][0];
6768 let indent_end = Point::new(row, indent_size.len);
6769
6770 (indent_size, indent_end)
6771 };
6772
6773 let mut line_prefix = indent_size.chars().collect::<String>();
6774
6775 if let Some(comment_prefix) =
6776 buffer
6777 .language_scope_at(selection.head())
6778 .and_then(|language| {
6779 language
6780 .line_comment_prefixes()
6781 .iter()
6782 .find(|prefix| buffer.contains_str_at(indent_end, prefix))
6783 .cloned()
6784 })
6785 {
6786 line_prefix.push_str(&comment_prefix);
6787 should_rewrap = true;
6788 }
6789
6790 if selection.is_empty() {
6791 'expand_upwards: while start_row > 0 {
6792 let prev_row = start_row - 1;
6793 if buffer.contains_str_at(Point::new(prev_row, 0), &line_prefix)
6794 && buffer.line_len(MultiBufferRow(prev_row)) as usize > line_prefix.len()
6795 {
6796 start_row = prev_row;
6797 } else {
6798 break 'expand_upwards;
6799 }
6800 }
6801
6802 'expand_downwards: while end_row < buffer.max_point().row {
6803 let next_row = end_row + 1;
6804 if buffer.contains_str_at(Point::new(next_row, 0), &line_prefix)
6805 && buffer.line_len(MultiBufferRow(next_row)) as usize > line_prefix.len()
6806 {
6807 end_row = next_row;
6808 } else {
6809 break 'expand_downwards;
6810 }
6811 }
6812 }
6813
6814 if !should_rewrap {
6815 continue;
6816 }
6817
6818 let start = Point::new(start_row, 0);
6819 let end = Point::new(end_row, buffer.line_len(MultiBufferRow(end_row)));
6820 let selection_text = buffer.text_for_range(start..end).collect::<String>();
6821 let Some(lines_without_prefixes) = selection_text
6822 .lines()
6823 .map(|line| {
6824 line.strip_prefix(&line_prefix)
6825 .or_else(|| line.trim_start().strip_prefix(&line_prefix.trim_start()))
6826 .ok_or_else(|| {
6827 anyhow!("line did not start with prefix {line_prefix:?}: {line:?}")
6828 })
6829 })
6830 .collect::<Result<Vec<_>, _>>()
6831 .log_err()
6832 else {
6833 continue;
6834 };
6835
6836 let unwrapped_text = lines_without_prefixes.join(" ");
6837 let wrap_column = buffer
6838 .settings_at(Point::new(start_row, 0), cx)
6839 .preferred_line_length as usize;
6840 let mut wrapped_text = String::new();
6841 let mut current_line = line_prefix.clone();
6842 for word in unwrapped_text.split_whitespace() {
6843 if current_line.len() + word.len() >= wrap_column {
6844 wrapped_text.push_str(¤t_line);
6845 wrapped_text.push('\n');
6846 current_line.truncate(line_prefix.len());
6847 }
6848
6849 if current_line.len() > line_prefix.len() {
6850 current_line.push(' ');
6851 }
6852
6853 current_line.push_str(word);
6854 }
6855
6856 if !current_line.is_empty() {
6857 wrapped_text.push_str(¤t_line);
6858 }
6859
6860 let diff = TextDiff::from_lines(&selection_text, &wrapped_text);
6861 let mut offset = start.to_offset(&buffer);
6862 let mut moved_since_edit = true;
6863
6864 for change in diff.iter_all_changes() {
6865 let value = change.value();
6866 match change.tag() {
6867 ChangeTag::Equal => {
6868 offset += value.len();
6869 moved_since_edit = true;
6870 }
6871 ChangeTag::Delete => {
6872 let start = buffer.anchor_after(offset);
6873 let end = buffer.anchor_before(offset + value.len());
6874
6875 if moved_since_edit {
6876 edits.push((start..end, String::new()));
6877 } else {
6878 edits.last_mut().unwrap().0.end = end;
6879 }
6880
6881 offset += value.len();
6882 moved_since_edit = false;
6883 }
6884 ChangeTag::Insert => {
6885 if moved_since_edit {
6886 let anchor = buffer.anchor_after(offset);
6887 edits.push((anchor..anchor, value.to_string()));
6888 } else {
6889 edits.last_mut().unwrap().1.push_str(value);
6890 }
6891
6892 moved_since_edit = false;
6893 }
6894 }
6895 }
6896
6897 rewrapped_row_ranges.push(start_row..=end_row);
6898 }
6899
6900 self.buffer
6901 .update(cx, |buffer, cx| buffer.edit(edits, None, cx));
6902 }
6903
6904 pub fn cut(&mut self, _: &Cut, cx: &mut ViewContext<Self>) {
6905 let mut text = String::new();
6906 let buffer = self.buffer.read(cx).snapshot(cx);
6907 let mut selections = self.selections.all::<Point>(cx);
6908 let mut clipboard_selections = Vec::with_capacity(selections.len());
6909 {
6910 let max_point = buffer.max_point();
6911 let mut is_first = true;
6912 for selection in &mut selections {
6913 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6914 if is_entire_line {
6915 selection.start = Point::new(selection.start.row, 0);
6916 if !selection.is_empty() && selection.end.column == 0 {
6917 selection.end = cmp::min(max_point, selection.end);
6918 } else {
6919 selection.end = cmp::min(max_point, Point::new(selection.end.row + 1, 0));
6920 }
6921 selection.goal = SelectionGoal::None;
6922 }
6923 if is_first {
6924 is_first = false;
6925 } else {
6926 text += "\n";
6927 }
6928 let mut len = 0;
6929 for chunk in buffer.text_for_range(selection.start..selection.end) {
6930 text.push_str(chunk);
6931 len += chunk.len();
6932 }
6933 clipboard_selections.push(ClipboardSelection {
6934 len,
6935 is_entire_line,
6936 first_line_indent: buffer
6937 .indent_size_for_line(MultiBufferRow(selection.start.row))
6938 .len,
6939 });
6940 }
6941 }
6942
6943 self.transact(cx, |this, cx| {
6944 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
6945 s.select(selections);
6946 });
6947 this.insert("", cx);
6948 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6949 text,
6950 clipboard_selections,
6951 ));
6952 });
6953 }
6954
6955 pub fn copy(&mut self, _: &Copy, cx: &mut ViewContext<Self>) {
6956 let selections = self.selections.all::<Point>(cx);
6957 let buffer = self.buffer.read(cx).read(cx);
6958 let mut text = String::new();
6959
6960 let mut clipboard_selections = Vec::with_capacity(selections.len());
6961 {
6962 let max_point = buffer.max_point();
6963 let mut is_first = true;
6964 for selection in selections.iter() {
6965 let mut start = selection.start;
6966 let mut end = selection.end;
6967 let is_entire_line = selection.is_empty() || self.selections.line_mode;
6968 if is_entire_line {
6969 start = Point::new(start.row, 0);
6970 end = cmp::min(max_point, Point::new(end.row + 1, 0));
6971 }
6972 if is_first {
6973 is_first = false;
6974 } else {
6975 text += "\n";
6976 }
6977 let mut len = 0;
6978 for chunk in buffer.text_for_range(start..end) {
6979 text.push_str(chunk);
6980 len += chunk.len();
6981 }
6982 clipboard_selections.push(ClipboardSelection {
6983 len,
6984 is_entire_line,
6985 first_line_indent: buffer.indent_size_for_line(MultiBufferRow(start.row)).len,
6986 });
6987 }
6988 }
6989
6990 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
6991 text,
6992 clipboard_selections,
6993 ));
6994 }
6995
6996 pub fn do_paste(
6997 &mut self,
6998 text: &String,
6999 clipboard_selections: Option<Vec<ClipboardSelection>>,
7000 handle_entire_lines: bool,
7001 cx: &mut ViewContext<Self>,
7002 ) {
7003 if self.read_only(cx) {
7004 return;
7005 }
7006
7007 let clipboard_text = Cow::Borrowed(text);
7008
7009 self.transact(cx, |this, cx| {
7010 if let Some(mut clipboard_selections) = clipboard_selections {
7011 let old_selections = this.selections.all::<usize>(cx);
7012 let all_selections_were_entire_line =
7013 clipboard_selections.iter().all(|s| s.is_entire_line);
7014 let first_selection_indent_column =
7015 clipboard_selections.first().map(|s| s.first_line_indent);
7016 if clipboard_selections.len() != old_selections.len() {
7017 clipboard_selections.drain(..);
7018 }
7019
7020 this.buffer.update(cx, |buffer, cx| {
7021 let snapshot = buffer.read(cx);
7022 let mut start_offset = 0;
7023 let mut edits = Vec::new();
7024 let mut original_indent_columns = Vec::new();
7025 for (ix, selection) in old_selections.iter().enumerate() {
7026 let to_insert;
7027 let entire_line;
7028 let original_indent_column;
7029 if let Some(clipboard_selection) = clipboard_selections.get(ix) {
7030 let end_offset = start_offset + clipboard_selection.len;
7031 to_insert = &clipboard_text[start_offset..end_offset];
7032 entire_line = clipboard_selection.is_entire_line;
7033 start_offset = end_offset + 1;
7034 original_indent_column = Some(clipboard_selection.first_line_indent);
7035 } else {
7036 to_insert = clipboard_text.as_str();
7037 entire_line = all_selections_were_entire_line;
7038 original_indent_column = first_selection_indent_column
7039 }
7040
7041 // If the corresponding selection was empty when this slice of the
7042 // clipboard text was written, then the entire line containing the
7043 // selection was copied. If this selection is also currently empty,
7044 // then paste the line before the current line of the buffer.
7045 let range = if selection.is_empty() && handle_entire_lines && entire_line {
7046 let column = selection.start.to_point(&snapshot).column as usize;
7047 let line_start = selection.start - column;
7048 line_start..line_start
7049 } else {
7050 selection.range()
7051 };
7052
7053 edits.push((range, to_insert));
7054 original_indent_columns.extend(original_indent_column);
7055 }
7056 drop(snapshot);
7057
7058 buffer.edit(
7059 edits,
7060 Some(AutoindentMode::Block {
7061 original_indent_columns,
7062 }),
7063 cx,
7064 );
7065 });
7066
7067 let selections = this.selections.all::<usize>(cx);
7068 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
7069 } else {
7070 this.insert(&clipboard_text, cx);
7071 }
7072 });
7073 }
7074
7075 pub fn paste(&mut self, _: &Paste, cx: &mut ViewContext<Self>) {
7076 if let Some(item) = cx.read_from_clipboard() {
7077 let entries = item.entries();
7078
7079 match entries.first() {
7080 // For now, we only support applying metadata if there's one string. In the future, we can incorporate all the selections
7081 // of all the pasted entries.
7082 Some(ClipboardEntry::String(clipboard_string)) if entries.len() == 1 => self
7083 .do_paste(
7084 clipboard_string.text(),
7085 clipboard_string.metadata_json::<Vec<ClipboardSelection>>(),
7086 true,
7087 cx,
7088 ),
7089 _ => self.do_paste(&item.text().unwrap_or_default(), None, true, cx),
7090 }
7091 }
7092 }
7093
7094 pub fn undo(&mut self, _: &Undo, cx: &mut ViewContext<Self>) {
7095 if self.read_only(cx) {
7096 return;
7097 }
7098
7099 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.undo(cx)) {
7100 if let Some((selections, _)) =
7101 self.selection_history.transaction(transaction_id).cloned()
7102 {
7103 self.change_selections(None, cx, |s| {
7104 s.select_anchors(selections.to_vec());
7105 });
7106 }
7107 self.request_autoscroll(Autoscroll::fit(), cx);
7108 self.unmark_text(cx);
7109 self.refresh_inline_completion(true, false, cx);
7110 cx.emit(EditorEvent::Edited { transaction_id });
7111 cx.emit(EditorEvent::TransactionUndone { transaction_id });
7112 }
7113 }
7114
7115 pub fn redo(&mut self, _: &Redo, cx: &mut ViewContext<Self>) {
7116 if self.read_only(cx) {
7117 return;
7118 }
7119
7120 if let Some(transaction_id) = self.buffer.update(cx, |buffer, cx| buffer.redo(cx)) {
7121 if let Some((_, Some(selections))) =
7122 self.selection_history.transaction(transaction_id).cloned()
7123 {
7124 self.change_selections(None, cx, |s| {
7125 s.select_anchors(selections.to_vec());
7126 });
7127 }
7128 self.request_autoscroll(Autoscroll::fit(), cx);
7129 self.unmark_text(cx);
7130 self.refresh_inline_completion(true, false, cx);
7131 cx.emit(EditorEvent::Edited { transaction_id });
7132 }
7133 }
7134
7135 pub fn finalize_last_transaction(&mut self, cx: &mut ViewContext<Self>) {
7136 self.buffer
7137 .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
7138 }
7139
7140 pub fn group_until_transaction(&mut self, tx_id: TransactionId, cx: &mut ViewContext<Self>) {
7141 self.buffer
7142 .update(cx, |buffer, cx| buffer.group_until_transaction(tx_id, cx));
7143 }
7144
7145 pub fn move_left(&mut self, _: &MoveLeft, cx: &mut ViewContext<Self>) {
7146 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7147 let line_mode = s.line_mode;
7148 s.move_with(|map, selection| {
7149 let cursor = if selection.is_empty() && !line_mode {
7150 movement::left(map, selection.start)
7151 } else {
7152 selection.start
7153 };
7154 selection.collapse_to(cursor, SelectionGoal::None);
7155 });
7156 })
7157 }
7158
7159 pub fn select_left(&mut self, _: &SelectLeft, cx: &mut ViewContext<Self>) {
7160 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7161 s.move_heads_with(|map, head, _| (movement::left(map, head), SelectionGoal::None));
7162 })
7163 }
7164
7165 pub fn move_right(&mut self, _: &MoveRight, cx: &mut ViewContext<Self>) {
7166 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7167 let line_mode = s.line_mode;
7168 s.move_with(|map, selection| {
7169 let cursor = if selection.is_empty() && !line_mode {
7170 movement::right(map, selection.end)
7171 } else {
7172 selection.end
7173 };
7174 selection.collapse_to(cursor, SelectionGoal::None)
7175 });
7176 })
7177 }
7178
7179 pub fn select_right(&mut self, _: &SelectRight, cx: &mut ViewContext<Self>) {
7180 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7181 s.move_heads_with(|map, head, _| (movement::right(map, head), SelectionGoal::None));
7182 })
7183 }
7184
7185 pub fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
7186 if self.take_rename(true, cx).is_some() {
7187 return;
7188 }
7189
7190 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7191 cx.propagate();
7192 return;
7193 }
7194
7195 let text_layout_details = &self.text_layout_details(cx);
7196 let selection_count = self.selections.count();
7197 let first_selection = self.selections.first_anchor();
7198
7199 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7200 let line_mode = s.line_mode;
7201 s.move_with(|map, selection| {
7202 if !selection.is_empty() && !line_mode {
7203 selection.goal = SelectionGoal::None;
7204 }
7205 let (cursor, goal) = movement::up(
7206 map,
7207 selection.start,
7208 selection.goal,
7209 false,
7210 text_layout_details,
7211 );
7212 selection.collapse_to(cursor, goal);
7213 });
7214 });
7215
7216 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7217 {
7218 cx.propagate();
7219 }
7220 }
7221
7222 pub fn move_up_by_lines(&mut self, action: &MoveUpByLines, cx: &mut ViewContext<Self>) {
7223 if self.take_rename(true, cx).is_some() {
7224 return;
7225 }
7226
7227 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7228 cx.propagate();
7229 return;
7230 }
7231
7232 let text_layout_details = &self.text_layout_details(cx);
7233
7234 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7235 let line_mode = s.line_mode;
7236 s.move_with(|map, selection| {
7237 if !selection.is_empty() && !line_mode {
7238 selection.goal = SelectionGoal::None;
7239 }
7240 let (cursor, goal) = movement::up_by_rows(
7241 map,
7242 selection.start,
7243 action.lines,
7244 selection.goal,
7245 false,
7246 text_layout_details,
7247 );
7248 selection.collapse_to(cursor, goal);
7249 });
7250 })
7251 }
7252
7253 pub fn move_down_by_lines(&mut self, action: &MoveDownByLines, cx: &mut ViewContext<Self>) {
7254 if self.take_rename(true, cx).is_some() {
7255 return;
7256 }
7257
7258 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7259 cx.propagate();
7260 return;
7261 }
7262
7263 let text_layout_details = &self.text_layout_details(cx);
7264
7265 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7266 let line_mode = s.line_mode;
7267 s.move_with(|map, selection| {
7268 if !selection.is_empty() && !line_mode {
7269 selection.goal = SelectionGoal::None;
7270 }
7271 let (cursor, goal) = movement::down_by_rows(
7272 map,
7273 selection.start,
7274 action.lines,
7275 selection.goal,
7276 false,
7277 text_layout_details,
7278 );
7279 selection.collapse_to(cursor, goal);
7280 });
7281 })
7282 }
7283
7284 pub fn select_down_by_lines(&mut self, action: &SelectDownByLines, cx: &mut ViewContext<Self>) {
7285 let text_layout_details = &self.text_layout_details(cx);
7286 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7287 s.move_heads_with(|map, head, goal| {
7288 movement::down_by_rows(map, head, action.lines, goal, false, text_layout_details)
7289 })
7290 })
7291 }
7292
7293 pub fn select_up_by_lines(&mut self, action: &SelectUpByLines, cx: &mut ViewContext<Self>) {
7294 let text_layout_details = &self.text_layout_details(cx);
7295 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7296 s.move_heads_with(|map, head, goal| {
7297 movement::up_by_rows(map, head, action.lines, goal, false, text_layout_details)
7298 })
7299 })
7300 }
7301
7302 pub fn select_page_up(&mut self, _: &SelectPageUp, cx: &mut ViewContext<Self>) {
7303 let Some(row_count) = self.visible_row_count() else {
7304 return;
7305 };
7306
7307 let text_layout_details = &self.text_layout_details(cx);
7308
7309 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7310 s.move_heads_with(|map, head, goal| {
7311 movement::up_by_rows(map, head, row_count, goal, false, text_layout_details)
7312 })
7313 })
7314 }
7315
7316 pub fn move_page_up(&mut self, action: &MovePageUp, cx: &mut ViewContext<Self>) {
7317 if self.take_rename(true, cx).is_some() {
7318 return;
7319 }
7320
7321 if self
7322 .context_menu
7323 .write()
7324 .as_mut()
7325 .map(|menu| menu.select_first(self.project.as_ref(), cx))
7326 .unwrap_or(false)
7327 {
7328 return;
7329 }
7330
7331 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7332 cx.propagate();
7333 return;
7334 }
7335
7336 let Some(row_count) = self.visible_row_count() else {
7337 return;
7338 };
7339
7340 let autoscroll = if action.center_cursor {
7341 Autoscroll::center()
7342 } else {
7343 Autoscroll::fit()
7344 };
7345
7346 let text_layout_details = &self.text_layout_details(cx);
7347
7348 self.change_selections(Some(autoscroll), cx, |s| {
7349 let line_mode = s.line_mode;
7350 s.move_with(|map, selection| {
7351 if !selection.is_empty() && !line_mode {
7352 selection.goal = SelectionGoal::None;
7353 }
7354 let (cursor, goal) = movement::up_by_rows(
7355 map,
7356 selection.end,
7357 row_count,
7358 selection.goal,
7359 false,
7360 text_layout_details,
7361 );
7362 selection.collapse_to(cursor, goal);
7363 });
7364 });
7365 }
7366
7367 pub fn select_up(&mut self, _: &SelectUp, cx: &mut ViewContext<Self>) {
7368 let text_layout_details = &self.text_layout_details(cx);
7369 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7370 s.move_heads_with(|map, head, goal| {
7371 movement::up(map, head, goal, false, text_layout_details)
7372 })
7373 })
7374 }
7375
7376 pub fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
7377 self.take_rename(true, cx);
7378
7379 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7380 cx.propagate();
7381 return;
7382 }
7383
7384 let text_layout_details = &self.text_layout_details(cx);
7385 let selection_count = self.selections.count();
7386 let first_selection = self.selections.first_anchor();
7387
7388 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7389 let line_mode = s.line_mode;
7390 s.move_with(|map, selection| {
7391 if !selection.is_empty() && !line_mode {
7392 selection.goal = SelectionGoal::None;
7393 }
7394 let (cursor, goal) = movement::down(
7395 map,
7396 selection.end,
7397 selection.goal,
7398 false,
7399 text_layout_details,
7400 );
7401 selection.collapse_to(cursor, goal);
7402 });
7403 });
7404
7405 if selection_count == 1 && first_selection.range() == self.selections.first_anchor().range()
7406 {
7407 cx.propagate();
7408 }
7409 }
7410
7411 pub fn select_page_down(&mut self, _: &SelectPageDown, cx: &mut ViewContext<Self>) {
7412 let Some(row_count) = self.visible_row_count() else {
7413 return;
7414 };
7415
7416 let text_layout_details = &self.text_layout_details(cx);
7417
7418 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7419 s.move_heads_with(|map, head, goal| {
7420 movement::down_by_rows(map, head, row_count, goal, false, text_layout_details)
7421 })
7422 })
7423 }
7424
7425 pub fn move_page_down(&mut self, action: &MovePageDown, cx: &mut ViewContext<Self>) {
7426 if self.take_rename(true, cx).is_some() {
7427 return;
7428 }
7429
7430 if self
7431 .context_menu
7432 .write()
7433 .as_mut()
7434 .map(|menu| menu.select_last(self.project.as_ref(), cx))
7435 .unwrap_or(false)
7436 {
7437 return;
7438 }
7439
7440 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7441 cx.propagate();
7442 return;
7443 }
7444
7445 let Some(row_count) = self.visible_row_count() else {
7446 return;
7447 };
7448
7449 let autoscroll = if action.center_cursor {
7450 Autoscroll::center()
7451 } else {
7452 Autoscroll::fit()
7453 };
7454
7455 let text_layout_details = &self.text_layout_details(cx);
7456 self.change_selections(Some(autoscroll), cx, |s| {
7457 let line_mode = s.line_mode;
7458 s.move_with(|map, selection| {
7459 if !selection.is_empty() && !line_mode {
7460 selection.goal = SelectionGoal::None;
7461 }
7462 let (cursor, goal) = movement::down_by_rows(
7463 map,
7464 selection.end,
7465 row_count,
7466 selection.goal,
7467 false,
7468 text_layout_details,
7469 );
7470 selection.collapse_to(cursor, goal);
7471 });
7472 });
7473 }
7474
7475 pub fn select_down(&mut self, _: &SelectDown, cx: &mut ViewContext<Self>) {
7476 let text_layout_details = &self.text_layout_details(cx);
7477 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7478 s.move_heads_with(|map, head, goal| {
7479 movement::down(map, head, goal, false, text_layout_details)
7480 })
7481 });
7482 }
7483
7484 pub fn context_menu_first(&mut self, _: &ContextMenuFirst, cx: &mut ViewContext<Self>) {
7485 if let Some(context_menu) = self.context_menu.write().as_mut() {
7486 context_menu.select_first(self.project.as_ref(), cx);
7487 }
7488 }
7489
7490 pub fn context_menu_prev(&mut self, _: &ContextMenuPrev, cx: &mut ViewContext<Self>) {
7491 if let Some(context_menu) = self.context_menu.write().as_mut() {
7492 context_menu.select_prev(self.project.as_ref(), cx);
7493 }
7494 }
7495
7496 pub fn context_menu_next(&mut self, _: &ContextMenuNext, cx: &mut ViewContext<Self>) {
7497 if let Some(context_menu) = self.context_menu.write().as_mut() {
7498 context_menu.select_next(self.project.as_ref(), cx);
7499 }
7500 }
7501
7502 pub fn context_menu_last(&mut self, _: &ContextMenuLast, cx: &mut ViewContext<Self>) {
7503 if let Some(context_menu) = self.context_menu.write().as_mut() {
7504 context_menu.select_last(self.project.as_ref(), cx);
7505 }
7506 }
7507
7508 pub fn move_to_previous_word_start(
7509 &mut self,
7510 _: &MoveToPreviousWordStart,
7511 cx: &mut ViewContext<Self>,
7512 ) {
7513 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7514 s.move_cursors_with(|map, head, _| {
7515 (
7516 movement::previous_word_start(map, head),
7517 SelectionGoal::None,
7518 )
7519 });
7520 })
7521 }
7522
7523 pub fn move_to_previous_subword_start(
7524 &mut self,
7525 _: &MoveToPreviousSubwordStart,
7526 cx: &mut ViewContext<Self>,
7527 ) {
7528 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7529 s.move_cursors_with(|map, head, _| {
7530 (
7531 movement::previous_subword_start(map, head),
7532 SelectionGoal::None,
7533 )
7534 });
7535 })
7536 }
7537
7538 pub fn select_to_previous_word_start(
7539 &mut self,
7540 _: &SelectToPreviousWordStart,
7541 cx: &mut ViewContext<Self>,
7542 ) {
7543 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7544 s.move_heads_with(|map, head, _| {
7545 (
7546 movement::previous_word_start(map, head),
7547 SelectionGoal::None,
7548 )
7549 });
7550 })
7551 }
7552
7553 pub fn select_to_previous_subword_start(
7554 &mut self,
7555 _: &SelectToPreviousSubwordStart,
7556 cx: &mut ViewContext<Self>,
7557 ) {
7558 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7559 s.move_heads_with(|map, head, _| {
7560 (
7561 movement::previous_subword_start(map, head),
7562 SelectionGoal::None,
7563 )
7564 });
7565 })
7566 }
7567
7568 pub fn delete_to_previous_word_start(
7569 &mut self,
7570 action: &DeleteToPreviousWordStart,
7571 cx: &mut ViewContext<Self>,
7572 ) {
7573 self.transact(cx, |this, cx| {
7574 this.select_autoclose_pair(cx);
7575 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7576 let line_mode = s.line_mode;
7577 s.move_with(|map, selection| {
7578 if selection.is_empty() && !line_mode {
7579 let cursor = if action.ignore_newlines {
7580 movement::previous_word_start(map, selection.head())
7581 } else {
7582 movement::previous_word_start_or_newline(map, selection.head())
7583 };
7584 selection.set_head(cursor, SelectionGoal::None);
7585 }
7586 });
7587 });
7588 this.insert("", cx);
7589 });
7590 }
7591
7592 pub fn delete_to_previous_subword_start(
7593 &mut self,
7594 _: &DeleteToPreviousSubwordStart,
7595 cx: &mut ViewContext<Self>,
7596 ) {
7597 self.transact(cx, |this, cx| {
7598 this.select_autoclose_pair(cx);
7599 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7600 let line_mode = s.line_mode;
7601 s.move_with(|map, selection| {
7602 if selection.is_empty() && !line_mode {
7603 let cursor = movement::previous_subword_start(map, selection.head());
7604 selection.set_head(cursor, SelectionGoal::None);
7605 }
7606 });
7607 });
7608 this.insert("", cx);
7609 });
7610 }
7611
7612 pub fn move_to_next_word_end(&mut self, _: &MoveToNextWordEnd, cx: &mut ViewContext<Self>) {
7613 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7614 s.move_cursors_with(|map, head, _| {
7615 (movement::next_word_end(map, head), SelectionGoal::None)
7616 });
7617 })
7618 }
7619
7620 pub fn move_to_next_subword_end(
7621 &mut self,
7622 _: &MoveToNextSubwordEnd,
7623 cx: &mut ViewContext<Self>,
7624 ) {
7625 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7626 s.move_cursors_with(|map, head, _| {
7627 (movement::next_subword_end(map, head), SelectionGoal::None)
7628 });
7629 })
7630 }
7631
7632 pub fn select_to_next_word_end(&mut self, _: &SelectToNextWordEnd, cx: &mut ViewContext<Self>) {
7633 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7634 s.move_heads_with(|map, head, _| {
7635 (movement::next_word_end(map, head), SelectionGoal::None)
7636 });
7637 })
7638 }
7639
7640 pub fn select_to_next_subword_end(
7641 &mut self,
7642 _: &SelectToNextSubwordEnd,
7643 cx: &mut ViewContext<Self>,
7644 ) {
7645 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7646 s.move_heads_with(|map, head, _| {
7647 (movement::next_subword_end(map, head), SelectionGoal::None)
7648 });
7649 })
7650 }
7651
7652 pub fn delete_to_next_word_end(
7653 &mut self,
7654 action: &DeleteToNextWordEnd,
7655 cx: &mut ViewContext<Self>,
7656 ) {
7657 self.transact(cx, |this, cx| {
7658 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7659 let line_mode = s.line_mode;
7660 s.move_with(|map, selection| {
7661 if selection.is_empty() && !line_mode {
7662 let cursor = if action.ignore_newlines {
7663 movement::next_word_end(map, selection.head())
7664 } else {
7665 movement::next_word_end_or_newline(map, selection.head())
7666 };
7667 selection.set_head(cursor, SelectionGoal::None);
7668 }
7669 });
7670 });
7671 this.insert("", cx);
7672 });
7673 }
7674
7675 pub fn delete_to_next_subword_end(
7676 &mut self,
7677 _: &DeleteToNextSubwordEnd,
7678 cx: &mut ViewContext<Self>,
7679 ) {
7680 self.transact(cx, |this, cx| {
7681 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7682 s.move_with(|map, selection| {
7683 if selection.is_empty() {
7684 let cursor = movement::next_subword_end(map, selection.head());
7685 selection.set_head(cursor, SelectionGoal::None);
7686 }
7687 });
7688 });
7689 this.insert("", cx);
7690 });
7691 }
7692
7693 pub fn move_to_beginning_of_line(
7694 &mut self,
7695 action: &MoveToBeginningOfLine,
7696 cx: &mut ViewContext<Self>,
7697 ) {
7698 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7699 s.move_cursors_with(|map, head, _| {
7700 (
7701 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7702 SelectionGoal::None,
7703 )
7704 });
7705 })
7706 }
7707
7708 pub fn select_to_beginning_of_line(
7709 &mut self,
7710 action: &SelectToBeginningOfLine,
7711 cx: &mut ViewContext<Self>,
7712 ) {
7713 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7714 s.move_heads_with(|map, head, _| {
7715 (
7716 movement::indented_line_beginning(map, head, action.stop_at_soft_wraps),
7717 SelectionGoal::None,
7718 )
7719 });
7720 });
7721 }
7722
7723 pub fn delete_to_beginning_of_line(
7724 &mut self,
7725 _: &DeleteToBeginningOfLine,
7726 cx: &mut ViewContext<Self>,
7727 ) {
7728 self.transact(cx, |this, cx| {
7729 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
7730 s.move_with(|_, selection| {
7731 selection.reversed = true;
7732 });
7733 });
7734
7735 this.select_to_beginning_of_line(
7736 &SelectToBeginningOfLine {
7737 stop_at_soft_wraps: false,
7738 },
7739 cx,
7740 );
7741 this.backspace(&Backspace, cx);
7742 });
7743 }
7744
7745 pub fn move_to_end_of_line(&mut self, action: &MoveToEndOfLine, cx: &mut ViewContext<Self>) {
7746 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7747 s.move_cursors_with(|map, head, _| {
7748 (
7749 movement::line_end(map, head, action.stop_at_soft_wraps),
7750 SelectionGoal::None,
7751 )
7752 });
7753 })
7754 }
7755
7756 pub fn select_to_end_of_line(
7757 &mut self,
7758 action: &SelectToEndOfLine,
7759 cx: &mut ViewContext<Self>,
7760 ) {
7761 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7762 s.move_heads_with(|map, head, _| {
7763 (
7764 movement::line_end(map, head, action.stop_at_soft_wraps),
7765 SelectionGoal::None,
7766 )
7767 });
7768 })
7769 }
7770
7771 pub fn delete_to_end_of_line(&mut self, _: &DeleteToEndOfLine, cx: &mut ViewContext<Self>) {
7772 self.transact(cx, |this, cx| {
7773 this.select_to_end_of_line(
7774 &SelectToEndOfLine {
7775 stop_at_soft_wraps: false,
7776 },
7777 cx,
7778 );
7779 this.delete(&Delete, cx);
7780 });
7781 }
7782
7783 pub fn cut_to_end_of_line(&mut self, _: &CutToEndOfLine, cx: &mut ViewContext<Self>) {
7784 self.transact(cx, |this, cx| {
7785 this.select_to_end_of_line(
7786 &SelectToEndOfLine {
7787 stop_at_soft_wraps: false,
7788 },
7789 cx,
7790 );
7791 this.cut(&Cut, cx);
7792 });
7793 }
7794
7795 pub fn move_to_start_of_paragraph(
7796 &mut self,
7797 _: &MoveToStartOfParagraph,
7798 cx: &mut ViewContext<Self>,
7799 ) {
7800 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7801 cx.propagate();
7802 return;
7803 }
7804
7805 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7806 s.move_with(|map, selection| {
7807 selection.collapse_to(
7808 movement::start_of_paragraph(map, selection.head(), 1),
7809 SelectionGoal::None,
7810 )
7811 });
7812 })
7813 }
7814
7815 pub fn move_to_end_of_paragraph(
7816 &mut self,
7817 _: &MoveToEndOfParagraph,
7818 cx: &mut ViewContext<Self>,
7819 ) {
7820 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7821 cx.propagate();
7822 return;
7823 }
7824
7825 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7826 s.move_with(|map, selection| {
7827 selection.collapse_to(
7828 movement::end_of_paragraph(map, selection.head(), 1),
7829 SelectionGoal::None,
7830 )
7831 });
7832 })
7833 }
7834
7835 pub fn select_to_start_of_paragraph(
7836 &mut self,
7837 _: &SelectToStartOfParagraph,
7838 cx: &mut ViewContext<Self>,
7839 ) {
7840 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7841 cx.propagate();
7842 return;
7843 }
7844
7845 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7846 s.move_heads_with(|map, head, _| {
7847 (
7848 movement::start_of_paragraph(map, head, 1),
7849 SelectionGoal::None,
7850 )
7851 });
7852 })
7853 }
7854
7855 pub fn select_to_end_of_paragraph(
7856 &mut self,
7857 _: &SelectToEndOfParagraph,
7858 cx: &mut ViewContext<Self>,
7859 ) {
7860 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7861 cx.propagate();
7862 return;
7863 }
7864
7865 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7866 s.move_heads_with(|map, head, _| {
7867 (
7868 movement::end_of_paragraph(map, head, 1),
7869 SelectionGoal::None,
7870 )
7871 });
7872 })
7873 }
7874
7875 pub fn move_to_beginning(&mut self, _: &MoveToBeginning, cx: &mut ViewContext<Self>) {
7876 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7877 cx.propagate();
7878 return;
7879 }
7880
7881 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7882 s.select_ranges(vec![0..0]);
7883 });
7884 }
7885
7886 pub fn select_to_beginning(&mut self, _: &SelectToBeginning, cx: &mut ViewContext<Self>) {
7887 let mut selection = self.selections.last::<Point>(cx);
7888 selection.set_head(Point::zero(), SelectionGoal::None);
7889
7890 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7891 s.select(vec![selection]);
7892 });
7893 }
7894
7895 pub fn move_to_end(&mut self, _: &MoveToEnd, cx: &mut ViewContext<Self>) {
7896 if matches!(self.mode, EditorMode::SingleLine { .. }) {
7897 cx.propagate();
7898 return;
7899 }
7900
7901 let cursor = self.buffer.read(cx).read(cx).len();
7902 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7903 s.select_ranges(vec![cursor..cursor])
7904 });
7905 }
7906
7907 pub fn set_nav_history(&mut self, nav_history: Option<ItemNavHistory>) {
7908 self.nav_history = nav_history;
7909 }
7910
7911 pub fn nav_history(&self) -> Option<&ItemNavHistory> {
7912 self.nav_history.as_ref()
7913 }
7914
7915 fn push_to_nav_history(
7916 &mut self,
7917 cursor_anchor: Anchor,
7918 new_position: Option<Point>,
7919 cx: &mut ViewContext<Self>,
7920 ) {
7921 if let Some(nav_history) = self.nav_history.as_mut() {
7922 let buffer = self.buffer.read(cx).read(cx);
7923 let cursor_position = cursor_anchor.to_point(&buffer);
7924 let scroll_state = self.scroll_manager.anchor();
7925 let scroll_top_row = scroll_state.top_row(&buffer);
7926 drop(buffer);
7927
7928 if let Some(new_position) = new_position {
7929 let row_delta = (new_position.row as i64 - cursor_position.row as i64).abs();
7930 if row_delta < MIN_NAVIGATION_HISTORY_ROW_DELTA {
7931 return;
7932 }
7933 }
7934
7935 nav_history.push(
7936 Some(NavigationData {
7937 cursor_anchor,
7938 cursor_position,
7939 scroll_anchor: scroll_state,
7940 scroll_top_row,
7941 }),
7942 cx,
7943 );
7944 }
7945 }
7946
7947 pub fn select_to_end(&mut self, _: &SelectToEnd, cx: &mut ViewContext<Self>) {
7948 let buffer = self.buffer.read(cx).snapshot(cx);
7949 let mut selection = self.selections.first::<usize>(cx);
7950 selection.set_head(buffer.len(), SelectionGoal::None);
7951 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7952 s.select(vec![selection]);
7953 });
7954 }
7955
7956 pub fn select_all(&mut self, _: &SelectAll, cx: &mut ViewContext<Self>) {
7957 let end = self.buffer.read(cx).read(cx).len();
7958 self.change_selections(None, cx, |s| {
7959 s.select_ranges(vec![0..end]);
7960 });
7961 }
7962
7963 pub fn select_line(&mut self, _: &SelectLine, cx: &mut ViewContext<Self>) {
7964 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
7965 let mut selections = self.selections.all::<Point>(cx);
7966 let max_point = display_map.buffer_snapshot.max_point();
7967 for selection in &mut selections {
7968 let rows = selection.spanned_rows(true, &display_map);
7969 selection.start = Point::new(rows.start.0, 0);
7970 selection.end = cmp::min(max_point, Point::new(rows.end.0, 0));
7971 selection.reversed = false;
7972 }
7973 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7974 s.select(selections);
7975 });
7976 }
7977
7978 pub fn split_selection_into_lines(
7979 &mut self,
7980 _: &SplitSelectionIntoLines,
7981 cx: &mut ViewContext<Self>,
7982 ) {
7983 let mut to_unfold = Vec::new();
7984 let mut new_selection_ranges = Vec::new();
7985 {
7986 let selections = self.selections.all::<Point>(cx);
7987 let buffer = self.buffer.read(cx).read(cx);
7988 for selection in selections {
7989 for row in selection.start.row..selection.end.row {
7990 let cursor = Point::new(row, buffer.line_len(MultiBufferRow(row)));
7991 new_selection_ranges.push(cursor..cursor);
7992 }
7993 new_selection_ranges.push(selection.end..selection.end);
7994 to_unfold.push(selection.start..selection.end);
7995 }
7996 }
7997 self.unfold_ranges(to_unfold, true, true, cx);
7998 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
7999 s.select_ranges(new_selection_ranges);
8000 });
8001 }
8002
8003 pub fn add_selection_above(&mut self, _: &AddSelectionAbove, cx: &mut ViewContext<Self>) {
8004 self.add_selection(true, cx);
8005 }
8006
8007 pub fn add_selection_below(&mut self, _: &AddSelectionBelow, cx: &mut ViewContext<Self>) {
8008 self.add_selection(false, cx);
8009 }
8010
8011 fn add_selection(&mut self, above: bool, cx: &mut ViewContext<Self>) {
8012 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8013 let mut selections = self.selections.all::<Point>(cx);
8014 let text_layout_details = self.text_layout_details(cx);
8015 let mut state = self.add_selections_state.take().unwrap_or_else(|| {
8016 let oldest_selection = selections.iter().min_by_key(|s| s.id).unwrap().clone();
8017 let range = oldest_selection.display_range(&display_map).sorted();
8018
8019 let start_x = display_map.x_for_display_point(range.start, &text_layout_details);
8020 let end_x = display_map.x_for_display_point(range.end, &text_layout_details);
8021 let positions = start_x.min(end_x)..start_x.max(end_x);
8022
8023 selections.clear();
8024 let mut stack = Vec::new();
8025 for row in range.start.row().0..=range.end.row().0 {
8026 if let Some(selection) = self.selections.build_columnar_selection(
8027 &display_map,
8028 DisplayRow(row),
8029 &positions,
8030 oldest_selection.reversed,
8031 &text_layout_details,
8032 ) {
8033 stack.push(selection.id);
8034 selections.push(selection);
8035 }
8036 }
8037
8038 if above {
8039 stack.reverse();
8040 }
8041
8042 AddSelectionsState { above, stack }
8043 });
8044
8045 let last_added_selection = *state.stack.last().unwrap();
8046 let mut new_selections = Vec::new();
8047 if above == state.above {
8048 let end_row = if above {
8049 DisplayRow(0)
8050 } else {
8051 display_map.max_point().row()
8052 };
8053
8054 'outer: for selection in selections {
8055 if selection.id == last_added_selection {
8056 let range = selection.display_range(&display_map).sorted();
8057 debug_assert_eq!(range.start.row(), range.end.row());
8058 let mut row = range.start.row();
8059 let positions =
8060 if let SelectionGoal::HorizontalRange { start, end } = selection.goal {
8061 px(start)..px(end)
8062 } else {
8063 let start_x =
8064 display_map.x_for_display_point(range.start, &text_layout_details);
8065 let end_x =
8066 display_map.x_for_display_point(range.end, &text_layout_details);
8067 start_x.min(end_x)..start_x.max(end_x)
8068 };
8069
8070 while row != end_row {
8071 if above {
8072 row.0 -= 1;
8073 } else {
8074 row.0 += 1;
8075 }
8076
8077 if let Some(new_selection) = self.selections.build_columnar_selection(
8078 &display_map,
8079 row,
8080 &positions,
8081 selection.reversed,
8082 &text_layout_details,
8083 ) {
8084 state.stack.push(new_selection.id);
8085 if above {
8086 new_selections.push(new_selection);
8087 new_selections.push(selection);
8088 } else {
8089 new_selections.push(selection);
8090 new_selections.push(new_selection);
8091 }
8092
8093 continue 'outer;
8094 }
8095 }
8096 }
8097
8098 new_selections.push(selection);
8099 }
8100 } else {
8101 new_selections = selections;
8102 new_selections.retain(|s| s.id != last_added_selection);
8103 state.stack.pop();
8104 }
8105
8106 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8107 s.select(new_selections);
8108 });
8109 if state.stack.len() > 1 {
8110 self.add_selections_state = Some(state);
8111 }
8112 }
8113
8114 pub fn select_next_match_internal(
8115 &mut self,
8116 display_map: &DisplaySnapshot,
8117 replace_newest: bool,
8118 autoscroll: Option<Autoscroll>,
8119 cx: &mut ViewContext<Self>,
8120 ) -> Result<()> {
8121 fn select_next_match_ranges(
8122 this: &mut Editor,
8123 range: Range<usize>,
8124 replace_newest: bool,
8125 auto_scroll: Option<Autoscroll>,
8126 cx: &mut ViewContext<Editor>,
8127 ) {
8128 this.unfold_ranges([range.clone()], false, true, cx);
8129 this.change_selections(auto_scroll, cx, |s| {
8130 if replace_newest {
8131 s.delete(s.newest_anchor().id);
8132 }
8133 s.insert_range(range.clone());
8134 });
8135 }
8136
8137 let buffer = &display_map.buffer_snapshot;
8138 let mut selections = self.selections.all::<usize>(cx);
8139 if let Some(mut select_next_state) = self.select_next_state.take() {
8140 let query = &select_next_state.query;
8141 if !select_next_state.done {
8142 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8143 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8144 let mut next_selected_range = None;
8145
8146 let bytes_after_last_selection =
8147 buffer.bytes_in_range(last_selection.end..buffer.len());
8148 let bytes_before_first_selection = buffer.bytes_in_range(0..first_selection.start);
8149 let query_matches = query
8150 .stream_find_iter(bytes_after_last_selection)
8151 .map(|result| (last_selection.end, result))
8152 .chain(
8153 query
8154 .stream_find_iter(bytes_before_first_selection)
8155 .map(|result| (0, result)),
8156 );
8157
8158 for (start_offset, query_match) in query_matches {
8159 let query_match = query_match.unwrap(); // can only fail due to I/O
8160 let offset_range =
8161 start_offset + query_match.start()..start_offset + query_match.end();
8162 let display_range = offset_range.start.to_display_point(display_map)
8163 ..offset_range.end.to_display_point(display_map);
8164
8165 if !select_next_state.wordwise
8166 || (!movement::is_inside_word(display_map, display_range.start)
8167 && !movement::is_inside_word(display_map, display_range.end))
8168 {
8169 // TODO: This is n^2, because we might check all the selections
8170 if !selections
8171 .iter()
8172 .any(|selection| selection.range().overlaps(&offset_range))
8173 {
8174 next_selected_range = Some(offset_range);
8175 break;
8176 }
8177 }
8178 }
8179
8180 if let Some(next_selected_range) = next_selected_range {
8181 select_next_match_ranges(
8182 self,
8183 next_selected_range,
8184 replace_newest,
8185 autoscroll,
8186 cx,
8187 );
8188 } else {
8189 select_next_state.done = true;
8190 }
8191 }
8192
8193 self.select_next_state = Some(select_next_state);
8194 } else {
8195 let mut only_carets = true;
8196 let mut same_text_selected = true;
8197 let mut selected_text = None;
8198
8199 let mut selections_iter = selections.iter().peekable();
8200 while let Some(selection) = selections_iter.next() {
8201 if selection.start != selection.end {
8202 only_carets = false;
8203 }
8204
8205 if same_text_selected {
8206 if selected_text.is_none() {
8207 selected_text =
8208 Some(buffer.text_for_range(selection.range()).collect::<String>());
8209 }
8210
8211 if let Some(next_selection) = selections_iter.peek() {
8212 if next_selection.range().len() == selection.range().len() {
8213 let next_selected_text = buffer
8214 .text_for_range(next_selection.range())
8215 .collect::<String>();
8216 if Some(next_selected_text) != selected_text {
8217 same_text_selected = false;
8218 selected_text = None;
8219 }
8220 } else {
8221 same_text_selected = false;
8222 selected_text = None;
8223 }
8224 }
8225 }
8226 }
8227
8228 if only_carets {
8229 for selection in &mut selections {
8230 let word_range = movement::surrounding_word(
8231 display_map,
8232 selection.start.to_display_point(display_map),
8233 );
8234 selection.start = word_range.start.to_offset(display_map, Bias::Left);
8235 selection.end = word_range.end.to_offset(display_map, Bias::Left);
8236 selection.goal = SelectionGoal::None;
8237 selection.reversed = false;
8238 select_next_match_ranges(
8239 self,
8240 selection.start..selection.end,
8241 replace_newest,
8242 autoscroll,
8243 cx,
8244 );
8245 }
8246
8247 if selections.len() == 1 {
8248 let selection = selections
8249 .last()
8250 .expect("ensured that there's only one selection");
8251 let query = buffer
8252 .text_for_range(selection.start..selection.end)
8253 .collect::<String>();
8254 let is_empty = query.is_empty();
8255 let select_state = SelectNextState {
8256 query: AhoCorasick::new(&[query])?,
8257 wordwise: true,
8258 done: is_empty,
8259 };
8260 self.select_next_state = Some(select_state);
8261 } else {
8262 self.select_next_state = None;
8263 }
8264 } else if let Some(selected_text) = selected_text {
8265 self.select_next_state = Some(SelectNextState {
8266 query: AhoCorasick::new(&[selected_text])?,
8267 wordwise: false,
8268 done: false,
8269 });
8270 self.select_next_match_internal(display_map, replace_newest, autoscroll, cx)?;
8271 }
8272 }
8273 Ok(())
8274 }
8275
8276 pub fn select_all_matches(
8277 &mut self,
8278 _action: &SelectAllMatches,
8279 cx: &mut ViewContext<Self>,
8280 ) -> Result<()> {
8281 self.push_to_selection_history();
8282 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8283
8284 self.select_next_match_internal(&display_map, false, None, cx)?;
8285 let Some(select_next_state) = self.select_next_state.as_mut() else {
8286 return Ok(());
8287 };
8288 if select_next_state.done {
8289 return Ok(());
8290 }
8291
8292 let mut new_selections = self.selections.all::<usize>(cx);
8293
8294 let buffer = &display_map.buffer_snapshot;
8295 let query_matches = select_next_state
8296 .query
8297 .stream_find_iter(buffer.bytes_in_range(0..buffer.len()));
8298
8299 for query_match in query_matches {
8300 let query_match = query_match.unwrap(); // can only fail due to I/O
8301 let offset_range = query_match.start()..query_match.end();
8302 let display_range = offset_range.start.to_display_point(&display_map)
8303 ..offset_range.end.to_display_point(&display_map);
8304
8305 if !select_next_state.wordwise
8306 || (!movement::is_inside_word(&display_map, display_range.start)
8307 && !movement::is_inside_word(&display_map, display_range.end))
8308 {
8309 self.selections.change_with(cx, |selections| {
8310 new_selections.push(Selection {
8311 id: selections.new_selection_id(),
8312 start: offset_range.start,
8313 end: offset_range.end,
8314 reversed: false,
8315 goal: SelectionGoal::None,
8316 });
8317 });
8318 }
8319 }
8320
8321 new_selections.sort_by_key(|selection| selection.start);
8322 let mut ix = 0;
8323 while ix + 1 < new_selections.len() {
8324 let current_selection = &new_selections[ix];
8325 let next_selection = &new_selections[ix + 1];
8326 if current_selection.range().overlaps(&next_selection.range()) {
8327 if current_selection.id < next_selection.id {
8328 new_selections.remove(ix + 1);
8329 } else {
8330 new_selections.remove(ix);
8331 }
8332 } else {
8333 ix += 1;
8334 }
8335 }
8336
8337 select_next_state.done = true;
8338 self.unfold_ranges(
8339 new_selections.iter().map(|selection| selection.range()),
8340 false,
8341 false,
8342 cx,
8343 );
8344 self.change_selections(Some(Autoscroll::fit()), cx, |selections| {
8345 selections.select(new_selections)
8346 });
8347
8348 Ok(())
8349 }
8350
8351 pub fn select_next(&mut self, action: &SelectNext, cx: &mut ViewContext<Self>) -> Result<()> {
8352 self.push_to_selection_history();
8353 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8354 self.select_next_match_internal(
8355 &display_map,
8356 action.replace_newest,
8357 Some(Autoscroll::newest()),
8358 cx,
8359 )?;
8360 Ok(())
8361 }
8362
8363 pub fn select_previous(
8364 &mut self,
8365 action: &SelectPrevious,
8366 cx: &mut ViewContext<Self>,
8367 ) -> Result<()> {
8368 self.push_to_selection_history();
8369 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8370 let buffer = &display_map.buffer_snapshot;
8371 let mut selections = self.selections.all::<usize>(cx);
8372 if let Some(mut select_prev_state) = self.select_prev_state.take() {
8373 let query = &select_prev_state.query;
8374 if !select_prev_state.done {
8375 let first_selection = selections.iter().min_by_key(|s| s.id).unwrap();
8376 let last_selection = selections.iter().max_by_key(|s| s.id).unwrap();
8377 let mut next_selected_range = None;
8378 // When we're iterating matches backwards, the oldest match will actually be the furthest one in the buffer.
8379 let bytes_before_last_selection =
8380 buffer.reversed_bytes_in_range(0..last_selection.start);
8381 let bytes_after_first_selection =
8382 buffer.reversed_bytes_in_range(first_selection.end..buffer.len());
8383 let query_matches = query
8384 .stream_find_iter(bytes_before_last_selection)
8385 .map(|result| (last_selection.start, result))
8386 .chain(
8387 query
8388 .stream_find_iter(bytes_after_first_selection)
8389 .map(|result| (buffer.len(), result)),
8390 );
8391 for (end_offset, query_match) in query_matches {
8392 let query_match = query_match.unwrap(); // can only fail due to I/O
8393 let offset_range =
8394 end_offset - query_match.end()..end_offset - query_match.start();
8395 let display_range = offset_range.start.to_display_point(&display_map)
8396 ..offset_range.end.to_display_point(&display_map);
8397
8398 if !select_prev_state.wordwise
8399 || (!movement::is_inside_word(&display_map, display_range.start)
8400 && !movement::is_inside_word(&display_map, display_range.end))
8401 {
8402 next_selected_range = Some(offset_range);
8403 break;
8404 }
8405 }
8406
8407 if let Some(next_selected_range) = next_selected_range {
8408 self.unfold_ranges([next_selected_range.clone()], false, true, cx);
8409 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8410 if action.replace_newest {
8411 s.delete(s.newest_anchor().id);
8412 }
8413 s.insert_range(next_selected_range);
8414 });
8415 } else {
8416 select_prev_state.done = true;
8417 }
8418 }
8419
8420 self.select_prev_state = Some(select_prev_state);
8421 } else {
8422 let mut only_carets = true;
8423 let mut same_text_selected = true;
8424 let mut selected_text = None;
8425
8426 let mut selections_iter = selections.iter().peekable();
8427 while let Some(selection) = selections_iter.next() {
8428 if selection.start != selection.end {
8429 only_carets = false;
8430 }
8431
8432 if same_text_selected {
8433 if selected_text.is_none() {
8434 selected_text =
8435 Some(buffer.text_for_range(selection.range()).collect::<String>());
8436 }
8437
8438 if let Some(next_selection) = selections_iter.peek() {
8439 if next_selection.range().len() == selection.range().len() {
8440 let next_selected_text = buffer
8441 .text_for_range(next_selection.range())
8442 .collect::<String>();
8443 if Some(next_selected_text) != selected_text {
8444 same_text_selected = false;
8445 selected_text = None;
8446 }
8447 } else {
8448 same_text_selected = false;
8449 selected_text = None;
8450 }
8451 }
8452 }
8453 }
8454
8455 if only_carets {
8456 for selection in &mut selections {
8457 let word_range = movement::surrounding_word(
8458 &display_map,
8459 selection.start.to_display_point(&display_map),
8460 );
8461 selection.start = word_range.start.to_offset(&display_map, Bias::Left);
8462 selection.end = word_range.end.to_offset(&display_map, Bias::Left);
8463 selection.goal = SelectionGoal::None;
8464 selection.reversed = false;
8465 }
8466 if selections.len() == 1 {
8467 let selection = selections
8468 .last()
8469 .expect("ensured that there's only one selection");
8470 let query = buffer
8471 .text_for_range(selection.start..selection.end)
8472 .collect::<String>();
8473 let is_empty = query.is_empty();
8474 let select_state = SelectNextState {
8475 query: AhoCorasick::new(&[query.chars().rev().collect::<String>()])?,
8476 wordwise: true,
8477 done: is_empty,
8478 };
8479 self.select_prev_state = Some(select_state);
8480 } else {
8481 self.select_prev_state = None;
8482 }
8483
8484 self.unfold_ranges(
8485 selections.iter().map(|s| s.range()).collect::<Vec<_>>(),
8486 false,
8487 true,
8488 cx,
8489 );
8490 self.change_selections(Some(Autoscroll::newest()), cx, |s| {
8491 s.select(selections);
8492 });
8493 } else if let Some(selected_text) = selected_text {
8494 self.select_prev_state = Some(SelectNextState {
8495 query: AhoCorasick::new(&[selected_text.chars().rev().collect::<String>()])?,
8496 wordwise: false,
8497 done: false,
8498 });
8499 self.select_previous(action, cx)?;
8500 }
8501 }
8502 Ok(())
8503 }
8504
8505 pub fn toggle_comments(&mut self, action: &ToggleComments, cx: &mut ViewContext<Self>) {
8506 let text_layout_details = &self.text_layout_details(cx);
8507 self.transact(cx, |this, cx| {
8508 let mut selections = this.selections.all::<MultiBufferPoint>(cx);
8509 let mut edits = Vec::new();
8510 let mut selection_edit_ranges = Vec::new();
8511 let mut last_toggled_row = None;
8512 let snapshot = this.buffer.read(cx).read(cx);
8513 let empty_str: Arc<str> = Arc::default();
8514 let mut suffixes_inserted = Vec::new();
8515
8516 fn comment_prefix_range(
8517 snapshot: &MultiBufferSnapshot,
8518 row: MultiBufferRow,
8519 comment_prefix: &str,
8520 comment_prefix_whitespace: &str,
8521 ) -> Range<Point> {
8522 let start = Point::new(row.0, snapshot.indent_size_for_line(row).len);
8523
8524 let mut line_bytes = snapshot
8525 .bytes_in_range(start..snapshot.max_point())
8526 .flatten()
8527 .copied();
8528
8529 // If this line currently begins with the line comment prefix, then record
8530 // the range containing the prefix.
8531 if line_bytes
8532 .by_ref()
8533 .take(comment_prefix.len())
8534 .eq(comment_prefix.bytes())
8535 {
8536 // Include any whitespace that matches the comment prefix.
8537 let matching_whitespace_len = line_bytes
8538 .zip(comment_prefix_whitespace.bytes())
8539 .take_while(|(a, b)| a == b)
8540 .count() as u32;
8541 let end = Point::new(
8542 start.row,
8543 start.column + comment_prefix.len() as u32 + matching_whitespace_len,
8544 );
8545 start..end
8546 } else {
8547 start..start
8548 }
8549 }
8550
8551 fn comment_suffix_range(
8552 snapshot: &MultiBufferSnapshot,
8553 row: MultiBufferRow,
8554 comment_suffix: &str,
8555 comment_suffix_has_leading_space: bool,
8556 ) -> Range<Point> {
8557 let end = Point::new(row.0, snapshot.line_len(row));
8558 let suffix_start_column = end.column.saturating_sub(comment_suffix.len() as u32);
8559
8560 let mut line_end_bytes = snapshot
8561 .bytes_in_range(Point::new(end.row, suffix_start_column.saturating_sub(1))..end)
8562 .flatten()
8563 .copied();
8564
8565 let leading_space_len = if suffix_start_column > 0
8566 && line_end_bytes.next() == Some(b' ')
8567 && comment_suffix_has_leading_space
8568 {
8569 1
8570 } else {
8571 0
8572 };
8573
8574 // If this line currently begins with the line comment prefix, then record
8575 // the range containing the prefix.
8576 if line_end_bytes.by_ref().eq(comment_suffix.bytes()) {
8577 let start = Point::new(end.row, suffix_start_column - leading_space_len);
8578 start..end
8579 } else {
8580 end..end
8581 }
8582 }
8583
8584 // TODO: Handle selections that cross excerpts
8585 for selection in &mut selections {
8586 let start_column = snapshot
8587 .indent_size_for_line(MultiBufferRow(selection.start.row))
8588 .len;
8589 let language = if let Some(language) =
8590 snapshot.language_scope_at(Point::new(selection.start.row, start_column))
8591 {
8592 language
8593 } else {
8594 continue;
8595 };
8596
8597 selection_edit_ranges.clear();
8598
8599 // If multiple selections contain a given row, avoid processing that
8600 // row more than once.
8601 let mut start_row = MultiBufferRow(selection.start.row);
8602 if last_toggled_row == Some(start_row) {
8603 start_row = start_row.next_row();
8604 }
8605 let end_row =
8606 if selection.end.row > selection.start.row && selection.end.column == 0 {
8607 MultiBufferRow(selection.end.row - 1)
8608 } else {
8609 MultiBufferRow(selection.end.row)
8610 };
8611 last_toggled_row = Some(end_row);
8612
8613 if start_row > end_row {
8614 continue;
8615 }
8616
8617 // If the language has line comments, toggle those.
8618 let full_comment_prefixes = language.line_comment_prefixes();
8619 if !full_comment_prefixes.is_empty() {
8620 let first_prefix = full_comment_prefixes
8621 .first()
8622 .expect("prefixes is non-empty");
8623 let prefix_trimmed_lengths = full_comment_prefixes
8624 .iter()
8625 .map(|p| p.trim_end_matches(' ').len())
8626 .collect::<SmallVec<[usize; 4]>>();
8627
8628 let mut all_selection_lines_are_comments = true;
8629
8630 for row in start_row.0..=end_row.0 {
8631 let row = MultiBufferRow(row);
8632 if start_row < end_row && snapshot.is_line_blank(row) {
8633 continue;
8634 }
8635
8636 let prefix_range = full_comment_prefixes
8637 .iter()
8638 .zip(prefix_trimmed_lengths.iter().copied())
8639 .map(|(prefix, trimmed_prefix_len)| {
8640 comment_prefix_range(
8641 snapshot.deref(),
8642 row,
8643 &prefix[..trimmed_prefix_len],
8644 &prefix[trimmed_prefix_len..],
8645 )
8646 })
8647 .max_by_key(|range| range.end.column - range.start.column)
8648 .expect("prefixes is non-empty");
8649
8650 if prefix_range.is_empty() {
8651 all_selection_lines_are_comments = false;
8652 }
8653
8654 selection_edit_ranges.push(prefix_range);
8655 }
8656
8657 if all_selection_lines_are_comments {
8658 edits.extend(
8659 selection_edit_ranges
8660 .iter()
8661 .cloned()
8662 .map(|range| (range, empty_str.clone())),
8663 );
8664 } else {
8665 let min_column = selection_edit_ranges
8666 .iter()
8667 .map(|range| range.start.column)
8668 .min()
8669 .unwrap_or(0);
8670 edits.extend(selection_edit_ranges.iter().map(|range| {
8671 let position = Point::new(range.start.row, min_column);
8672 (position..position, first_prefix.clone())
8673 }));
8674 }
8675 } else if let Some((full_comment_prefix, comment_suffix)) =
8676 language.block_comment_delimiters()
8677 {
8678 let comment_prefix = full_comment_prefix.trim_end_matches(' ');
8679 let comment_prefix_whitespace = &full_comment_prefix[comment_prefix.len()..];
8680 let prefix_range = comment_prefix_range(
8681 snapshot.deref(),
8682 start_row,
8683 comment_prefix,
8684 comment_prefix_whitespace,
8685 );
8686 let suffix_range = comment_suffix_range(
8687 snapshot.deref(),
8688 end_row,
8689 comment_suffix.trim_start_matches(' '),
8690 comment_suffix.starts_with(' '),
8691 );
8692
8693 if prefix_range.is_empty() || suffix_range.is_empty() {
8694 edits.push((
8695 prefix_range.start..prefix_range.start,
8696 full_comment_prefix.clone(),
8697 ));
8698 edits.push((suffix_range.end..suffix_range.end, comment_suffix.clone()));
8699 suffixes_inserted.push((end_row, comment_suffix.len()));
8700 } else {
8701 edits.push((prefix_range, empty_str.clone()));
8702 edits.push((suffix_range, empty_str.clone()));
8703 }
8704 } else {
8705 continue;
8706 }
8707 }
8708
8709 drop(snapshot);
8710 this.buffer.update(cx, |buffer, cx| {
8711 buffer.edit(edits, None, cx);
8712 });
8713
8714 // Adjust selections so that they end before any comment suffixes that
8715 // were inserted.
8716 let mut suffixes_inserted = suffixes_inserted.into_iter().peekable();
8717 let mut selections = this.selections.all::<Point>(cx);
8718 let snapshot = this.buffer.read(cx).read(cx);
8719 for selection in &mut selections {
8720 while let Some((row, suffix_len)) = suffixes_inserted.peek().copied() {
8721 match row.cmp(&MultiBufferRow(selection.end.row)) {
8722 Ordering::Less => {
8723 suffixes_inserted.next();
8724 continue;
8725 }
8726 Ordering::Greater => break,
8727 Ordering::Equal => {
8728 if selection.end.column == snapshot.line_len(row) {
8729 if selection.is_empty() {
8730 selection.start.column -= suffix_len as u32;
8731 }
8732 selection.end.column -= suffix_len as u32;
8733 }
8734 break;
8735 }
8736 }
8737 }
8738 }
8739
8740 drop(snapshot);
8741 this.change_selections(Some(Autoscroll::fit()), cx, |s| s.select(selections));
8742
8743 let selections = this.selections.all::<Point>(cx);
8744 let selections_on_single_row = selections.windows(2).all(|selections| {
8745 selections[0].start.row == selections[1].start.row
8746 && selections[0].end.row == selections[1].end.row
8747 && selections[0].start.row == selections[0].end.row
8748 });
8749 let selections_selecting = selections
8750 .iter()
8751 .any(|selection| selection.start != selection.end);
8752 let advance_downwards = action.advance_downwards
8753 && selections_on_single_row
8754 && !selections_selecting
8755 && !matches!(this.mode, EditorMode::SingleLine { .. });
8756
8757 if advance_downwards {
8758 let snapshot = this.buffer.read(cx).snapshot(cx);
8759
8760 this.change_selections(Some(Autoscroll::fit()), cx, |s| {
8761 s.move_cursors_with(|display_snapshot, display_point, _| {
8762 let mut point = display_point.to_point(display_snapshot);
8763 point.row += 1;
8764 point = snapshot.clip_point(point, Bias::Left);
8765 let display_point = point.to_display_point(display_snapshot);
8766 let goal = SelectionGoal::HorizontalPosition(
8767 display_snapshot
8768 .x_for_display_point(display_point, text_layout_details)
8769 .into(),
8770 );
8771 (display_point, goal)
8772 })
8773 });
8774 }
8775 });
8776 }
8777
8778 pub fn select_enclosing_symbol(
8779 &mut self,
8780 _: &SelectEnclosingSymbol,
8781 cx: &mut ViewContext<Self>,
8782 ) {
8783 let buffer = self.buffer.read(cx).snapshot(cx);
8784 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8785
8786 fn update_selection(
8787 selection: &Selection<usize>,
8788 buffer_snap: &MultiBufferSnapshot,
8789 ) -> Option<Selection<usize>> {
8790 let cursor = selection.head();
8791 let (_buffer_id, symbols) = buffer_snap.symbols_containing(cursor, None)?;
8792 for symbol in symbols.iter().rev() {
8793 let start = symbol.range.start.to_offset(buffer_snap);
8794 let end = symbol.range.end.to_offset(buffer_snap);
8795 let new_range = start..end;
8796 if start < selection.start || end > selection.end {
8797 return Some(Selection {
8798 id: selection.id,
8799 start: new_range.start,
8800 end: new_range.end,
8801 goal: SelectionGoal::None,
8802 reversed: selection.reversed,
8803 });
8804 }
8805 }
8806 None
8807 }
8808
8809 let mut selected_larger_symbol = false;
8810 let new_selections = old_selections
8811 .iter()
8812 .map(|selection| match update_selection(selection, &buffer) {
8813 Some(new_selection) => {
8814 if new_selection.range() != selection.range() {
8815 selected_larger_symbol = true;
8816 }
8817 new_selection
8818 }
8819 None => selection.clone(),
8820 })
8821 .collect::<Vec<_>>();
8822
8823 if selected_larger_symbol {
8824 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8825 s.select(new_selections);
8826 });
8827 }
8828 }
8829
8830 pub fn select_larger_syntax_node(
8831 &mut self,
8832 _: &SelectLargerSyntaxNode,
8833 cx: &mut ViewContext<Self>,
8834 ) {
8835 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
8836 let buffer = self.buffer.read(cx).snapshot(cx);
8837 let old_selections = self.selections.all::<usize>(cx).into_boxed_slice();
8838
8839 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8840 let mut selected_larger_node = false;
8841 let new_selections = old_selections
8842 .iter()
8843 .map(|selection| {
8844 let old_range = selection.start..selection.end;
8845 let mut new_range = old_range.clone();
8846 while let Some(containing_range) =
8847 buffer.range_for_syntax_ancestor(new_range.clone())
8848 {
8849 new_range = containing_range;
8850 if !display_map.intersects_fold(new_range.start)
8851 && !display_map.intersects_fold(new_range.end)
8852 {
8853 break;
8854 }
8855 }
8856
8857 selected_larger_node |= new_range != old_range;
8858 Selection {
8859 id: selection.id,
8860 start: new_range.start,
8861 end: new_range.end,
8862 goal: SelectionGoal::None,
8863 reversed: selection.reversed,
8864 }
8865 })
8866 .collect::<Vec<_>>();
8867
8868 if selected_larger_node {
8869 stack.push(old_selections);
8870 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8871 s.select(new_selections);
8872 });
8873 }
8874 self.select_larger_syntax_node_stack = stack;
8875 }
8876
8877 pub fn select_smaller_syntax_node(
8878 &mut self,
8879 _: &SelectSmallerSyntaxNode,
8880 cx: &mut ViewContext<Self>,
8881 ) {
8882 let mut stack = mem::take(&mut self.select_larger_syntax_node_stack);
8883 if let Some(selections) = stack.pop() {
8884 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
8885 s.select(selections.to_vec());
8886 });
8887 }
8888 self.select_larger_syntax_node_stack = stack;
8889 }
8890
8891 fn refresh_runnables(&mut self, cx: &mut ViewContext<Self>) -> Task<()> {
8892 if !EditorSettings::get_global(cx).gutter.runnables {
8893 self.clear_tasks();
8894 return Task::ready(());
8895 }
8896 let project = self.project.clone();
8897 cx.spawn(|this, mut cx| async move {
8898 let Ok(display_snapshot) = this.update(&mut cx, |this, cx| {
8899 this.display_map.update(cx, |map, cx| map.snapshot(cx))
8900 }) else {
8901 return;
8902 };
8903
8904 let Some(project) = project else {
8905 return;
8906 };
8907
8908 let hide_runnables = project
8909 .update(&mut cx, |project, cx| {
8910 // Do not display any test indicators in non-dev server remote projects.
8911 project.is_via_collab() && project.ssh_connection_string(cx).is_none()
8912 })
8913 .unwrap_or(true);
8914 if hide_runnables {
8915 return;
8916 }
8917 let new_rows =
8918 cx.background_executor()
8919 .spawn({
8920 let snapshot = display_snapshot.clone();
8921 async move {
8922 Self::fetch_runnable_ranges(&snapshot, Anchor::min()..Anchor::max())
8923 }
8924 })
8925 .await;
8926 let rows = Self::runnable_rows(project, display_snapshot, new_rows, cx.clone());
8927
8928 this.update(&mut cx, |this, _| {
8929 this.clear_tasks();
8930 for (key, value) in rows {
8931 this.insert_tasks(key, value);
8932 }
8933 })
8934 .ok();
8935 })
8936 }
8937 fn fetch_runnable_ranges(
8938 snapshot: &DisplaySnapshot,
8939 range: Range<Anchor>,
8940 ) -> Vec<language::RunnableRange> {
8941 snapshot.buffer_snapshot.runnable_ranges(range).collect()
8942 }
8943
8944 fn runnable_rows(
8945 project: Model<Project>,
8946 snapshot: DisplaySnapshot,
8947 runnable_ranges: Vec<RunnableRange>,
8948 mut cx: AsyncWindowContext,
8949 ) -> Vec<((BufferId, u32), RunnableTasks)> {
8950 runnable_ranges
8951 .into_iter()
8952 .filter_map(|mut runnable| {
8953 let tasks = cx
8954 .update(|cx| Self::templates_with_tags(&project, &mut runnable.runnable, cx))
8955 .ok()?;
8956 if tasks.is_empty() {
8957 return None;
8958 }
8959
8960 let point = runnable.run_range.start.to_point(&snapshot.buffer_snapshot);
8961
8962 let row = snapshot
8963 .buffer_snapshot
8964 .buffer_line_for_row(MultiBufferRow(point.row))?
8965 .1
8966 .start
8967 .row;
8968
8969 let context_range =
8970 BufferOffset(runnable.full_range.start)..BufferOffset(runnable.full_range.end);
8971 Some((
8972 (runnable.buffer_id, row),
8973 RunnableTasks {
8974 templates: tasks,
8975 offset: MultiBufferOffset(runnable.run_range.start),
8976 context_range,
8977 column: point.column,
8978 extra_variables: runnable.extra_captures,
8979 },
8980 ))
8981 })
8982 .collect()
8983 }
8984
8985 fn templates_with_tags(
8986 project: &Model<Project>,
8987 runnable: &mut Runnable,
8988 cx: &WindowContext<'_>,
8989 ) -> Vec<(TaskSourceKind, TaskTemplate)> {
8990 let (inventory, worktree_id, file) = project.read_with(cx, |project, cx| {
8991 let (worktree_id, file) = project
8992 .buffer_for_id(runnable.buffer, cx)
8993 .and_then(|buffer| buffer.read(cx).file())
8994 .map(|file| (file.worktree_id(cx), file.clone()))
8995 .unzip();
8996
8997 (project.task_inventory().clone(), worktree_id, file)
8998 });
8999
9000 let inventory = inventory.read(cx);
9001 let tags = mem::take(&mut runnable.tags);
9002 let mut tags: Vec<_> = tags
9003 .into_iter()
9004 .flat_map(|tag| {
9005 let tag = tag.0.clone();
9006 inventory
9007 .list_tasks(
9008 file.clone(),
9009 Some(runnable.language.clone()),
9010 worktree_id,
9011 cx,
9012 )
9013 .into_iter()
9014 .filter(move |(_, template)| {
9015 template.tags.iter().any(|source_tag| source_tag == &tag)
9016 })
9017 })
9018 .sorted_by_key(|(kind, _)| kind.to_owned())
9019 .collect();
9020 if let Some((leading_tag_source, _)) = tags.first() {
9021 // Strongest source wins; if we have worktree tag binding, prefer that to
9022 // global and language bindings;
9023 // if we have a global binding, prefer that to language binding.
9024 let first_mismatch = tags
9025 .iter()
9026 .position(|(tag_source, _)| tag_source != leading_tag_source);
9027 if let Some(index) = first_mismatch {
9028 tags.truncate(index);
9029 }
9030 }
9031
9032 tags
9033 }
9034
9035 pub fn move_to_enclosing_bracket(
9036 &mut self,
9037 _: &MoveToEnclosingBracket,
9038 cx: &mut ViewContext<Self>,
9039 ) {
9040 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9041 s.move_offsets_with(|snapshot, selection| {
9042 let Some(enclosing_bracket_ranges) =
9043 snapshot.enclosing_bracket_ranges(selection.start..selection.end)
9044 else {
9045 return;
9046 };
9047
9048 let mut best_length = usize::MAX;
9049 let mut best_inside = false;
9050 let mut best_in_bracket_range = false;
9051 let mut best_destination = None;
9052 for (open, close) in enclosing_bracket_ranges {
9053 let close = close.to_inclusive();
9054 let length = close.end() - open.start;
9055 let inside = selection.start >= open.end && selection.end <= *close.start();
9056 let in_bracket_range = open.to_inclusive().contains(&selection.head())
9057 || close.contains(&selection.head());
9058
9059 // If best is next to a bracket and current isn't, skip
9060 if !in_bracket_range && best_in_bracket_range {
9061 continue;
9062 }
9063
9064 // Prefer smaller lengths unless best is inside and current isn't
9065 if length > best_length && (best_inside || !inside) {
9066 continue;
9067 }
9068
9069 best_length = length;
9070 best_inside = inside;
9071 best_in_bracket_range = in_bracket_range;
9072 best_destination = Some(
9073 if close.contains(&selection.start) && close.contains(&selection.end) {
9074 if inside {
9075 open.end
9076 } else {
9077 open.start
9078 }
9079 } else if inside {
9080 *close.start()
9081 } else {
9082 *close.end()
9083 },
9084 );
9085 }
9086
9087 if let Some(destination) = best_destination {
9088 selection.collapse_to(destination, SelectionGoal::None);
9089 }
9090 })
9091 });
9092 }
9093
9094 pub fn undo_selection(&mut self, _: &UndoSelection, cx: &mut ViewContext<Self>) {
9095 self.end_selection(cx);
9096 self.selection_history.mode = SelectionHistoryMode::Undoing;
9097 if let Some(entry) = self.selection_history.undo_stack.pop_back() {
9098 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9099 self.select_next_state = entry.select_next_state;
9100 self.select_prev_state = entry.select_prev_state;
9101 self.add_selections_state = entry.add_selections_state;
9102 self.request_autoscroll(Autoscroll::newest(), cx);
9103 }
9104 self.selection_history.mode = SelectionHistoryMode::Normal;
9105 }
9106
9107 pub fn redo_selection(&mut self, _: &RedoSelection, cx: &mut ViewContext<Self>) {
9108 self.end_selection(cx);
9109 self.selection_history.mode = SelectionHistoryMode::Redoing;
9110 if let Some(entry) = self.selection_history.redo_stack.pop_back() {
9111 self.change_selections(None, cx, |s| s.select_anchors(entry.selections.to_vec()));
9112 self.select_next_state = entry.select_next_state;
9113 self.select_prev_state = entry.select_prev_state;
9114 self.add_selections_state = entry.add_selections_state;
9115 self.request_autoscroll(Autoscroll::newest(), cx);
9116 }
9117 self.selection_history.mode = SelectionHistoryMode::Normal;
9118 }
9119
9120 pub fn expand_excerpts(&mut self, action: &ExpandExcerpts, cx: &mut ViewContext<Self>) {
9121 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::UpAndDown, cx)
9122 }
9123
9124 pub fn expand_excerpts_down(
9125 &mut self,
9126 action: &ExpandExcerptsDown,
9127 cx: &mut ViewContext<Self>,
9128 ) {
9129 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Down, cx)
9130 }
9131
9132 pub fn expand_excerpts_up(&mut self, action: &ExpandExcerptsUp, cx: &mut ViewContext<Self>) {
9133 self.expand_excerpts_for_direction(action.lines, ExpandExcerptDirection::Up, cx)
9134 }
9135
9136 pub fn expand_excerpts_for_direction(
9137 &mut self,
9138 lines: u32,
9139 direction: ExpandExcerptDirection,
9140 cx: &mut ViewContext<Self>,
9141 ) {
9142 let selections = self.selections.disjoint_anchors();
9143
9144 let lines = if lines == 0 {
9145 EditorSettings::get_global(cx).expand_excerpt_lines
9146 } else {
9147 lines
9148 };
9149
9150 self.buffer.update(cx, |buffer, cx| {
9151 buffer.expand_excerpts(
9152 selections
9153 .iter()
9154 .map(|selection| selection.head().excerpt_id)
9155 .dedup(),
9156 lines,
9157 direction,
9158 cx,
9159 )
9160 })
9161 }
9162
9163 pub fn expand_excerpt(
9164 &mut self,
9165 excerpt: ExcerptId,
9166 direction: ExpandExcerptDirection,
9167 cx: &mut ViewContext<Self>,
9168 ) {
9169 let lines = EditorSettings::get_global(cx).expand_excerpt_lines;
9170 self.buffer.update(cx, |buffer, cx| {
9171 buffer.expand_excerpts([excerpt], lines, direction, cx)
9172 })
9173 }
9174
9175 fn go_to_diagnostic(&mut self, _: &GoToDiagnostic, cx: &mut ViewContext<Self>) {
9176 self.go_to_diagnostic_impl(Direction::Next, cx)
9177 }
9178
9179 fn go_to_prev_diagnostic(&mut self, _: &GoToPrevDiagnostic, cx: &mut ViewContext<Self>) {
9180 self.go_to_diagnostic_impl(Direction::Prev, cx)
9181 }
9182
9183 pub fn go_to_diagnostic_impl(&mut self, direction: Direction, cx: &mut ViewContext<Self>) {
9184 let buffer = self.buffer.read(cx).snapshot(cx);
9185 let selection = self.selections.newest::<usize>(cx);
9186
9187 // If there is an active Diagnostic Popover jump to its diagnostic instead.
9188 if direction == Direction::Next {
9189 if let Some(popover) = self.hover_state.diagnostic_popover.as_ref() {
9190 let (group_id, jump_to) = popover.activation_info();
9191 if self.activate_diagnostics(group_id, cx) {
9192 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9193 let mut new_selection = s.newest_anchor().clone();
9194 new_selection.collapse_to(jump_to, SelectionGoal::None);
9195 s.select_anchors(vec![new_selection.clone()]);
9196 });
9197 }
9198 return;
9199 }
9200 }
9201
9202 let mut active_primary_range = self.active_diagnostics.as_ref().map(|active_diagnostics| {
9203 active_diagnostics
9204 .primary_range
9205 .to_offset(&buffer)
9206 .to_inclusive()
9207 });
9208 let mut search_start = if let Some(active_primary_range) = active_primary_range.as_ref() {
9209 if active_primary_range.contains(&selection.head()) {
9210 *active_primary_range.start()
9211 } else {
9212 selection.head()
9213 }
9214 } else {
9215 selection.head()
9216 };
9217 let snapshot = self.snapshot(cx);
9218 loop {
9219 let diagnostics = if direction == Direction::Prev {
9220 buffer.diagnostics_in_range::<_, usize>(0..search_start, true)
9221 } else {
9222 buffer.diagnostics_in_range::<_, usize>(search_start..buffer.len(), false)
9223 }
9224 .filter(|diagnostic| !snapshot.intersects_fold(diagnostic.range.start));
9225 let group = diagnostics
9226 // relies on diagnostics_in_range to return diagnostics with the same starting range to
9227 // be sorted in a stable way
9228 // skip until we are at current active diagnostic, if it exists
9229 .skip_while(|entry| {
9230 (match direction {
9231 Direction::Prev => entry.range.start >= search_start,
9232 Direction::Next => entry.range.start <= search_start,
9233 }) && self
9234 .active_diagnostics
9235 .as_ref()
9236 .is_some_and(|a| a.group_id != entry.diagnostic.group_id)
9237 })
9238 .find_map(|entry| {
9239 if entry.diagnostic.is_primary
9240 && entry.diagnostic.severity <= DiagnosticSeverity::WARNING
9241 && !entry.range.is_empty()
9242 // if we match with the active diagnostic, skip it
9243 && Some(entry.diagnostic.group_id)
9244 != self.active_diagnostics.as_ref().map(|d| d.group_id)
9245 {
9246 Some((entry.range, entry.diagnostic.group_id))
9247 } else {
9248 None
9249 }
9250 });
9251
9252 if let Some((primary_range, group_id)) = group {
9253 if self.activate_diagnostics(group_id, cx) {
9254 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9255 s.select(vec![Selection {
9256 id: selection.id,
9257 start: primary_range.start,
9258 end: primary_range.start,
9259 reversed: false,
9260 goal: SelectionGoal::None,
9261 }]);
9262 });
9263 }
9264 break;
9265 } else {
9266 // Cycle around to the start of the buffer, potentially moving back to the start of
9267 // the currently active diagnostic.
9268 active_primary_range.take();
9269 if direction == Direction::Prev {
9270 if search_start == buffer.len() {
9271 break;
9272 } else {
9273 search_start = buffer.len();
9274 }
9275 } else if search_start == 0 {
9276 break;
9277 } else {
9278 search_start = 0;
9279 }
9280 }
9281 }
9282 }
9283
9284 fn go_to_hunk(&mut self, _: &GoToHunk, cx: &mut ViewContext<Self>) {
9285 let snapshot = self
9286 .display_map
9287 .update(cx, |display_map, cx| display_map.snapshot(cx));
9288 let selection = self.selections.newest::<Point>(cx);
9289
9290 if !self.seek_in_direction(
9291 &snapshot,
9292 selection.head(),
9293 false,
9294 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9295 MultiBufferRow(selection.head().row + 1)..MultiBufferRow::MAX,
9296 ),
9297 cx,
9298 ) {
9299 let wrapped_point = Point::zero();
9300 self.seek_in_direction(
9301 &snapshot,
9302 wrapped_point,
9303 true,
9304 snapshot.buffer_snapshot.git_diff_hunks_in_range(
9305 MultiBufferRow(wrapped_point.row + 1)..MultiBufferRow::MAX,
9306 ),
9307 cx,
9308 );
9309 }
9310 }
9311
9312 fn go_to_prev_hunk(&mut self, _: &GoToPrevHunk, cx: &mut ViewContext<Self>) {
9313 let snapshot = self
9314 .display_map
9315 .update(cx, |display_map, cx| display_map.snapshot(cx));
9316 let selection = self.selections.newest::<Point>(cx);
9317
9318 if !self.seek_in_direction(
9319 &snapshot,
9320 selection.head(),
9321 false,
9322 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9323 MultiBufferRow(0)..MultiBufferRow(selection.head().row),
9324 ),
9325 cx,
9326 ) {
9327 let wrapped_point = snapshot.buffer_snapshot.max_point();
9328 self.seek_in_direction(
9329 &snapshot,
9330 wrapped_point,
9331 true,
9332 snapshot.buffer_snapshot.git_diff_hunks_in_range_rev(
9333 MultiBufferRow(0)..MultiBufferRow(wrapped_point.row),
9334 ),
9335 cx,
9336 );
9337 }
9338 }
9339
9340 fn seek_in_direction(
9341 &mut self,
9342 snapshot: &DisplaySnapshot,
9343 initial_point: Point,
9344 is_wrapped: bool,
9345 hunks: impl Iterator<Item = MultiBufferDiffHunk>,
9346 cx: &mut ViewContext<Editor>,
9347 ) -> bool {
9348 let display_point = initial_point.to_display_point(snapshot);
9349 let mut hunks = hunks
9350 .map(|hunk| diff_hunk_to_display(&hunk, snapshot))
9351 .filter(|hunk| is_wrapped || !hunk.contains_display_row(display_point.row()))
9352 .dedup();
9353
9354 if let Some(hunk) = hunks.next() {
9355 self.change_selections(Some(Autoscroll::fit()), cx, |s| {
9356 let row = hunk.start_display_row();
9357 let point = DisplayPoint::new(row, 0);
9358 s.select_display_ranges([point..point]);
9359 });
9360
9361 true
9362 } else {
9363 false
9364 }
9365 }
9366
9367 pub fn go_to_definition(
9368 &mut self,
9369 _: &GoToDefinition,
9370 cx: &mut ViewContext<Self>,
9371 ) -> Task<Result<Navigated>> {
9372 let definition = self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, false, cx);
9373 cx.spawn(|editor, mut cx| async move {
9374 if definition.await? == Navigated::Yes {
9375 return Ok(Navigated::Yes);
9376 }
9377 match editor.update(&mut cx, |editor, cx| {
9378 editor.find_all_references(&FindAllReferences, cx)
9379 })? {
9380 Some(references) => references.await,
9381 None => Ok(Navigated::No),
9382 }
9383 })
9384 }
9385
9386 pub fn go_to_declaration(
9387 &mut self,
9388 _: &GoToDeclaration,
9389 cx: &mut ViewContext<Self>,
9390 ) -> Task<Result<Navigated>> {
9391 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, false, cx)
9392 }
9393
9394 pub fn go_to_declaration_split(
9395 &mut self,
9396 _: &GoToDeclaration,
9397 cx: &mut ViewContext<Self>,
9398 ) -> Task<Result<Navigated>> {
9399 self.go_to_definition_of_kind(GotoDefinitionKind::Declaration, true, cx)
9400 }
9401
9402 pub fn go_to_implementation(
9403 &mut self,
9404 _: &GoToImplementation,
9405 cx: &mut ViewContext<Self>,
9406 ) -> Task<Result<Navigated>> {
9407 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, false, cx)
9408 }
9409
9410 pub fn go_to_implementation_split(
9411 &mut self,
9412 _: &GoToImplementationSplit,
9413 cx: &mut ViewContext<Self>,
9414 ) -> Task<Result<Navigated>> {
9415 self.go_to_definition_of_kind(GotoDefinitionKind::Implementation, true, cx)
9416 }
9417
9418 pub fn go_to_type_definition(
9419 &mut self,
9420 _: &GoToTypeDefinition,
9421 cx: &mut ViewContext<Self>,
9422 ) -> Task<Result<Navigated>> {
9423 self.go_to_definition_of_kind(GotoDefinitionKind::Type, false, cx)
9424 }
9425
9426 pub fn go_to_definition_split(
9427 &mut self,
9428 _: &GoToDefinitionSplit,
9429 cx: &mut ViewContext<Self>,
9430 ) -> Task<Result<Navigated>> {
9431 self.go_to_definition_of_kind(GotoDefinitionKind::Symbol, true, cx)
9432 }
9433
9434 pub fn go_to_type_definition_split(
9435 &mut self,
9436 _: &GoToTypeDefinitionSplit,
9437 cx: &mut ViewContext<Self>,
9438 ) -> Task<Result<Navigated>> {
9439 self.go_to_definition_of_kind(GotoDefinitionKind::Type, true, cx)
9440 }
9441
9442 fn go_to_definition_of_kind(
9443 &mut self,
9444 kind: GotoDefinitionKind,
9445 split: bool,
9446 cx: &mut ViewContext<Self>,
9447 ) -> Task<Result<Navigated>> {
9448 let Some(workspace) = self.workspace() else {
9449 return Task::ready(Ok(Navigated::No));
9450 };
9451 let buffer = self.buffer.read(cx);
9452 let head = self.selections.newest::<usize>(cx).head();
9453 let (buffer, head) = if let Some(text_anchor) = buffer.text_anchor_for_position(head, cx) {
9454 text_anchor
9455 } else {
9456 return Task::ready(Ok(Navigated::No));
9457 };
9458
9459 let project = workspace.read(cx).project().clone();
9460 let definitions = project.update(cx, |project, cx| match kind {
9461 GotoDefinitionKind::Symbol => project.definition(&buffer, head, cx),
9462 GotoDefinitionKind::Declaration => project.declaration(&buffer, head, cx),
9463 GotoDefinitionKind::Type => project.type_definition(&buffer, head, cx),
9464 GotoDefinitionKind::Implementation => project.implementation(&buffer, head, cx),
9465 });
9466
9467 cx.spawn(|editor, mut cx| async move {
9468 let definitions = definitions.await?;
9469 let navigated = editor
9470 .update(&mut cx, |editor, cx| {
9471 editor.navigate_to_hover_links(
9472 Some(kind),
9473 definitions
9474 .into_iter()
9475 .filter(|location| {
9476 hover_links::exclude_link_to_position(&buffer, &head, location, cx)
9477 })
9478 .map(HoverLink::Text)
9479 .collect::<Vec<_>>(),
9480 split,
9481 cx,
9482 )
9483 })?
9484 .await?;
9485 anyhow::Ok(navigated)
9486 })
9487 }
9488
9489 pub fn open_url(&mut self, _: &OpenUrl, cx: &mut ViewContext<Self>) {
9490 let position = self.selections.newest_anchor().head();
9491 let Some((buffer, buffer_position)) =
9492 self.buffer.read(cx).text_anchor_for_position(position, cx)
9493 else {
9494 return;
9495 };
9496
9497 cx.spawn(|editor, mut cx| async move {
9498 if let Some((_, url)) = find_url(&buffer, buffer_position, cx.clone()) {
9499 editor.update(&mut cx, |_, cx| {
9500 cx.open_url(&url);
9501 })
9502 } else {
9503 Ok(())
9504 }
9505 })
9506 .detach();
9507 }
9508
9509 pub fn open_file(&mut self, _: &OpenFile, cx: &mut ViewContext<Self>) {
9510 let Some(workspace) = self.workspace() else {
9511 return;
9512 };
9513
9514 let position = self.selections.newest_anchor().head();
9515
9516 let Some((buffer, buffer_position)) =
9517 self.buffer.read(cx).text_anchor_for_position(position, cx)
9518 else {
9519 return;
9520 };
9521
9522 let Some(project) = self.project.clone() else {
9523 return;
9524 };
9525
9526 cx.spawn(|_, mut cx| async move {
9527 let result = find_file(&buffer, project, buffer_position, &mut cx).await;
9528
9529 if let Some((_, path)) = result {
9530 workspace
9531 .update(&mut cx, |workspace, cx| {
9532 workspace.open_resolved_path(path, cx)
9533 })?
9534 .await?;
9535 }
9536 anyhow::Ok(())
9537 })
9538 .detach();
9539 }
9540
9541 pub(crate) fn navigate_to_hover_links(
9542 &mut self,
9543 kind: Option<GotoDefinitionKind>,
9544 mut definitions: Vec<HoverLink>,
9545 split: bool,
9546 cx: &mut ViewContext<Editor>,
9547 ) -> Task<Result<Navigated>> {
9548 // If there is one definition, just open it directly
9549 if definitions.len() == 1 {
9550 let definition = definitions.pop().unwrap();
9551
9552 enum TargetTaskResult {
9553 Location(Option<Location>),
9554 AlreadyNavigated,
9555 }
9556
9557 let target_task = match definition {
9558 HoverLink::Text(link) => {
9559 Task::ready(anyhow::Ok(TargetTaskResult::Location(Some(link.target))))
9560 }
9561 HoverLink::InlayHint(lsp_location, server_id) => {
9562 let computation = self.compute_target_location(lsp_location, server_id, cx);
9563 cx.background_executor().spawn(async move {
9564 let location = computation.await?;
9565 Ok(TargetTaskResult::Location(location))
9566 })
9567 }
9568 HoverLink::Url(url) => {
9569 cx.open_url(&url);
9570 Task::ready(Ok(TargetTaskResult::AlreadyNavigated))
9571 }
9572 HoverLink::File(path) => {
9573 if let Some(workspace) = self.workspace() {
9574 cx.spawn(|_, mut cx| async move {
9575 workspace
9576 .update(&mut cx, |workspace, cx| {
9577 workspace.open_resolved_path(path, cx)
9578 })?
9579 .await
9580 .map(|_| TargetTaskResult::AlreadyNavigated)
9581 })
9582 } else {
9583 Task::ready(Ok(TargetTaskResult::Location(None)))
9584 }
9585 }
9586 };
9587 cx.spawn(|editor, mut cx| async move {
9588 let target = match target_task.await.context("target resolution task")? {
9589 TargetTaskResult::AlreadyNavigated => return Ok(Navigated::Yes),
9590 TargetTaskResult::Location(None) => return Ok(Navigated::No),
9591 TargetTaskResult::Location(Some(target)) => target,
9592 };
9593
9594 editor.update(&mut cx, |editor, cx| {
9595 let Some(workspace) = editor.workspace() else {
9596 return Navigated::No;
9597 };
9598 let pane = workspace.read(cx).active_pane().clone();
9599
9600 let range = target.range.to_offset(target.buffer.read(cx));
9601 let range = editor.range_for_match(&range);
9602
9603 if Some(&target.buffer) == editor.buffer.read(cx).as_singleton().as_ref() {
9604 let buffer = target.buffer.read(cx);
9605 let range = check_multiline_range(buffer, range);
9606 editor.change_selections(Some(Autoscroll::focused()), cx, |s| {
9607 s.select_ranges([range]);
9608 });
9609 } else {
9610 cx.window_context().defer(move |cx| {
9611 let target_editor: View<Self> =
9612 workspace.update(cx, |workspace, cx| {
9613 let pane = if split {
9614 workspace.adjacent_pane(cx)
9615 } else {
9616 workspace.active_pane().clone()
9617 };
9618
9619 workspace.open_project_item(
9620 pane,
9621 target.buffer.clone(),
9622 true,
9623 true,
9624 cx,
9625 )
9626 });
9627 target_editor.update(cx, |target_editor, cx| {
9628 // When selecting a definition in a different buffer, disable the nav history
9629 // to avoid creating a history entry at the previous cursor location.
9630 pane.update(cx, |pane, _| pane.disable_history());
9631 let buffer = target.buffer.read(cx);
9632 let range = check_multiline_range(buffer, range);
9633 target_editor.change_selections(
9634 Some(Autoscroll::focused()),
9635 cx,
9636 |s| {
9637 s.select_ranges([range]);
9638 },
9639 );
9640 pane.update(cx, |pane, _| pane.enable_history());
9641 });
9642 });
9643 }
9644 Navigated::Yes
9645 })
9646 })
9647 } else if !definitions.is_empty() {
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(workspace, locations, title, split, cx)
9701 })
9702 .ok();
9703
9704 anyhow::Ok(Navigated::from_bool(opened.is_some()))
9705 })
9706 } else {
9707 Task::ready(Ok(Navigated::No))
9708 }
9709 }
9710
9711 fn compute_target_location(
9712 &self,
9713 lsp_location: lsp::Location,
9714 server_id: LanguageServerId,
9715 cx: &mut ViewContext<Editor>,
9716 ) -> Task<anyhow::Result<Option<Location>>> {
9717 let Some(project) = self.project.clone() else {
9718 return Task::Ready(Some(Ok(None)));
9719 };
9720
9721 cx.spawn(move |editor, mut cx| async move {
9722 let location_task = editor.update(&mut cx, |editor, cx| {
9723 project.update(cx, |project, cx| {
9724 let language_server_name =
9725 editor.buffer.read(cx).as_singleton().and_then(|buffer| {
9726 project
9727 .language_server_for_buffer(buffer.read(cx), server_id, cx)
9728 .map(|(lsp_adapter, _)| lsp_adapter.name.clone())
9729 });
9730 language_server_name.map(|language_server_name| {
9731 project.open_local_buffer_via_lsp(
9732 lsp_location.uri.clone(),
9733 server_id,
9734 language_server_name,
9735 cx,
9736 )
9737 })
9738 })
9739 })?;
9740 let location = match location_task {
9741 Some(task) => Some({
9742 let target_buffer_handle = task.await.context("open local buffer")?;
9743 let range = target_buffer_handle.update(&mut cx, |target_buffer, _| {
9744 let target_start = target_buffer
9745 .clip_point_utf16(point_from_lsp(lsp_location.range.start), Bias::Left);
9746 let target_end = target_buffer
9747 .clip_point_utf16(point_from_lsp(lsp_location.range.end), Bias::Left);
9748 target_buffer.anchor_after(target_start)
9749 ..target_buffer.anchor_before(target_end)
9750 })?;
9751 Location {
9752 buffer: target_buffer_handle,
9753 range,
9754 }
9755 }),
9756 None => None,
9757 };
9758 Ok(location)
9759 })
9760 }
9761
9762 pub fn find_all_references(
9763 &mut self,
9764 _: &FindAllReferences,
9765 cx: &mut ViewContext<Self>,
9766 ) -> Option<Task<Result<Navigated>>> {
9767 let multi_buffer = self.buffer.read(cx);
9768 let selection = self.selections.newest::<usize>(cx);
9769 let head = selection.head();
9770
9771 let multi_buffer_snapshot = multi_buffer.snapshot(cx);
9772 let head_anchor = multi_buffer_snapshot.anchor_at(
9773 head,
9774 if head < selection.tail() {
9775 Bias::Right
9776 } else {
9777 Bias::Left
9778 },
9779 );
9780
9781 match self
9782 .find_all_references_task_sources
9783 .binary_search_by(|anchor| anchor.cmp(&head_anchor, &multi_buffer_snapshot))
9784 {
9785 Ok(_) => {
9786 log::info!(
9787 "Ignoring repeated FindAllReferences invocation with the position of already running task"
9788 );
9789 return None;
9790 }
9791 Err(i) => {
9792 self.find_all_references_task_sources.insert(i, head_anchor);
9793 }
9794 }
9795
9796 let (buffer, head) = multi_buffer.text_anchor_for_position(head, cx)?;
9797 let workspace = self.workspace()?;
9798 let project = workspace.read(cx).project().clone();
9799 let references = project.update(cx, |project, cx| project.references(&buffer, head, cx));
9800 Some(cx.spawn(|editor, mut cx| async move {
9801 let _cleanup = defer({
9802 let mut cx = cx.clone();
9803 move || {
9804 let _ = editor.update(&mut cx, |editor, _| {
9805 if let Ok(i) =
9806 editor
9807 .find_all_references_task_sources
9808 .binary_search_by(|anchor| {
9809 anchor.cmp(&head_anchor, &multi_buffer_snapshot)
9810 })
9811 {
9812 editor.find_all_references_task_sources.remove(i);
9813 }
9814 });
9815 }
9816 });
9817
9818 let locations = references.await?;
9819 if locations.is_empty() {
9820 return anyhow::Ok(Navigated::No);
9821 }
9822
9823 workspace.update(&mut cx, |workspace, cx| {
9824 let title = locations
9825 .first()
9826 .as_ref()
9827 .map(|location| {
9828 let buffer = location.buffer.read(cx);
9829 format!(
9830 "References to `{}`",
9831 buffer
9832 .text_for_range(location.range.clone())
9833 .collect::<String>()
9834 )
9835 })
9836 .unwrap();
9837 Self::open_locations_in_multibuffer(workspace, locations, title, false, cx);
9838 Navigated::Yes
9839 })
9840 }))
9841 }
9842
9843 /// Opens a multibuffer with the given project locations in it
9844 pub fn open_locations_in_multibuffer(
9845 workspace: &mut Workspace,
9846 mut locations: Vec<Location>,
9847 title: String,
9848 split: bool,
9849 cx: &mut ViewContext<Workspace>,
9850 ) {
9851 // If there are multiple definitions, open them in a multibuffer
9852 locations.sort_by_key(|location| location.buffer.read(cx).remote_id());
9853 let mut locations = locations.into_iter().peekable();
9854 let mut ranges_to_highlight = Vec::new();
9855 let capability = workspace.project().read(cx).capability();
9856
9857 let excerpt_buffer = cx.new_model(|cx| {
9858 let mut multibuffer = MultiBuffer::new(capability);
9859 while let Some(location) = locations.next() {
9860 let buffer = location.buffer.read(cx);
9861 let mut ranges_for_buffer = Vec::new();
9862 let range = location.range.to_offset(buffer);
9863 ranges_for_buffer.push(range.clone());
9864
9865 while let Some(next_location) = locations.peek() {
9866 if next_location.buffer == location.buffer {
9867 ranges_for_buffer.push(next_location.range.to_offset(buffer));
9868 locations.next();
9869 } else {
9870 break;
9871 }
9872 }
9873
9874 ranges_for_buffer.sort_by_key(|range| (range.start, Reverse(range.end)));
9875 ranges_to_highlight.extend(multibuffer.push_excerpts_with_context_lines(
9876 location.buffer.clone(),
9877 ranges_for_buffer,
9878 DEFAULT_MULTIBUFFER_CONTEXT,
9879 cx,
9880 ))
9881 }
9882
9883 multibuffer.with_title(title)
9884 });
9885
9886 let editor = cx.new_view(|cx| {
9887 Editor::for_multibuffer(excerpt_buffer, Some(workspace.project().clone()), true, cx)
9888 });
9889 editor.update(cx, |editor, cx| {
9890 if let Some(first_range) = ranges_to_highlight.first() {
9891 editor.change_selections(None, cx, |selections| {
9892 selections.clear_disjoint();
9893 selections.select_anchor_ranges(std::iter::once(first_range.clone()));
9894 });
9895 }
9896 editor.highlight_background::<Self>(
9897 &ranges_to_highlight,
9898 |theme| theme.editor_highlighted_line_background,
9899 cx,
9900 );
9901 });
9902
9903 let item = Box::new(editor);
9904 let item_id = item.item_id();
9905
9906 if split {
9907 workspace.split_item(SplitDirection::Right, item.clone(), cx);
9908 } else {
9909 let destination_index = workspace.active_pane().update(cx, |pane, cx| {
9910 if PreviewTabsSettings::get_global(cx).enable_preview_from_code_navigation {
9911 pane.close_current_preview_item(cx)
9912 } else {
9913 None
9914 }
9915 });
9916 workspace.add_item_to_active_pane(item.clone(), destination_index, true, cx);
9917 }
9918 workspace.active_pane().update(cx, |pane, cx| {
9919 pane.set_preview_item_id(Some(item_id), cx);
9920 });
9921 }
9922
9923 pub fn rename(&mut self, _: &Rename, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
9924 use language::ToOffset as _;
9925
9926 let project = self.project.clone()?;
9927 let selection = self.selections.newest_anchor().clone();
9928 let (cursor_buffer, cursor_buffer_position) = self
9929 .buffer
9930 .read(cx)
9931 .text_anchor_for_position(selection.head(), cx)?;
9932 let (tail_buffer, cursor_buffer_position_end) = self
9933 .buffer
9934 .read(cx)
9935 .text_anchor_for_position(selection.tail(), cx)?;
9936 if tail_buffer != cursor_buffer {
9937 return None;
9938 }
9939
9940 let snapshot = cursor_buffer.read(cx).snapshot();
9941 let cursor_buffer_offset = cursor_buffer_position.to_offset(&snapshot);
9942 let cursor_buffer_offset_end = cursor_buffer_position_end.to_offset(&snapshot);
9943 let prepare_rename = project.update(cx, |project, cx| {
9944 project.prepare_rename(cursor_buffer.clone(), cursor_buffer_offset, cx)
9945 });
9946 drop(snapshot);
9947
9948 Some(cx.spawn(|this, mut cx| async move {
9949 let rename_range = if let Some(range) = prepare_rename.await? {
9950 Some(range)
9951 } else {
9952 this.update(&mut cx, |this, cx| {
9953 let buffer = this.buffer.read(cx).snapshot(cx);
9954 let mut buffer_highlights = this
9955 .document_highlights_for_position(selection.head(), &buffer)
9956 .filter(|highlight| {
9957 highlight.start.excerpt_id == selection.head().excerpt_id
9958 && highlight.end.excerpt_id == selection.head().excerpt_id
9959 });
9960 buffer_highlights
9961 .next()
9962 .map(|highlight| highlight.start.text_anchor..highlight.end.text_anchor)
9963 })?
9964 };
9965 if let Some(rename_range) = rename_range {
9966 this.update(&mut cx, |this, cx| {
9967 let snapshot = cursor_buffer.read(cx).snapshot();
9968 let rename_buffer_range = rename_range.to_offset(&snapshot);
9969 let cursor_offset_in_rename_range =
9970 cursor_buffer_offset.saturating_sub(rename_buffer_range.start);
9971 let cursor_offset_in_rename_range_end =
9972 cursor_buffer_offset_end.saturating_sub(rename_buffer_range.start);
9973
9974 this.take_rename(false, cx);
9975 let buffer = this.buffer.read(cx).read(cx);
9976 let cursor_offset = selection.head().to_offset(&buffer);
9977 let rename_start = cursor_offset.saturating_sub(cursor_offset_in_rename_range);
9978 let rename_end = rename_start + rename_buffer_range.len();
9979 let range = buffer.anchor_before(rename_start)..buffer.anchor_after(rename_end);
9980 let mut old_highlight_id = None;
9981 let old_name: Arc<str> = buffer
9982 .chunks(rename_start..rename_end, true)
9983 .map(|chunk| {
9984 if old_highlight_id.is_none() {
9985 old_highlight_id = chunk.syntax_highlight_id;
9986 }
9987 chunk.text
9988 })
9989 .collect::<String>()
9990 .into();
9991
9992 drop(buffer);
9993
9994 // Position the selection in the rename editor so that it matches the current selection.
9995 this.show_local_selections = false;
9996 let rename_editor = cx.new_view(|cx| {
9997 let mut editor = Editor::single_line(cx);
9998 editor.buffer.update(cx, |buffer, cx| {
9999 buffer.edit([(0..0, old_name.clone())], None, cx)
10000 });
10001 let rename_selection_range = match cursor_offset_in_rename_range
10002 .cmp(&cursor_offset_in_rename_range_end)
10003 {
10004 Ordering::Equal => {
10005 editor.select_all(&SelectAll, cx);
10006 return editor;
10007 }
10008 Ordering::Less => {
10009 cursor_offset_in_rename_range..cursor_offset_in_rename_range_end
10010 }
10011 Ordering::Greater => {
10012 cursor_offset_in_rename_range_end..cursor_offset_in_rename_range
10013 }
10014 };
10015 if rename_selection_range.end > old_name.len() {
10016 editor.select_all(&SelectAll, cx);
10017 } else {
10018 editor.change_selections(Some(Autoscroll::fit()), cx, |s| {
10019 s.select_ranges([rename_selection_range]);
10020 });
10021 }
10022 editor
10023 });
10024 cx.subscribe(&rename_editor, |_, _, e: &EditorEvent, cx| {
10025 if e == &EditorEvent::Focused {
10026 cx.emit(EditorEvent::FocusedIn)
10027 }
10028 })
10029 .detach();
10030
10031 let write_highlights =
10032 this.clear_background_highlights::<DocumentHighlightWrite>(cx);
10033 let read_highlights =
10034 this.clear_background_highlights::<DocumentHighlightRead>(cx);
10035 let ranges = write_highlights
10036 .iter()
10037 .flat_map(|(_, ranges)| ranges.iter())
10038 .chain(read_highlights.iter().flat_map(|(_, ranges)| ranges.iter()))
10039 .cloned()
10040 .collect();
10041
10042 this.highlight_text::<Rename>(
10043 ranges,
10044 HighlightStyle {
10045 fade_out: Some(0.6),
10046 ..Default::default()
10047 },
10048 cx,
10049 );
10050 let rename_focus_handle = rename_editor.focus_handle(cx);
10051 cx.focus(&rename_focus_handle);
10052 let block_id = this.insert_blocks(
10053 [BlockProperties {
10054 style: BlockStyle::Flex,
10055 position: range.start,
10056 height: 1,
10057 render: Box::new({
10058 let rename_editor = rename_editor.clone();
10059 move |cx: &mut BlockContext| {
10060 let mut text_style = cx.editor_style.text.clone();
10061 if let Some(highlight_style) = old_highlight_id
10062 .and_then(|h| h.style(&cx.editor_style.syntax))
10063 {
10064 text_style = text_style.highlight(highlight_style);
10065 }
10066 div()
10067 .pl(cx.anchor_x)
10068 .child(EditorElement::new(
10069 &rename_editor,
10070 EditorStyle {
10071 background: cx.theme().system().transparent,
10072 local_player: cx.editor_style.local_player,
10073 text: text_style,
10074 scrollbar_width: cx.editor_style.scrollbar_width,
10075 syntax: cx.editor_style.syntax.clone(),
10076 status: cx.editor_style.status.clone(),
10077 inlay_hints_style: HighlightStyle {
10078 font_weight: Some(FontWeight::BOLD),
10079 ..make_inlay_hints_style(cx)
10080 },
10081 suggestions_style: HighlightStyle {
10082 color: Some(cx.theme().status().predictive),
10083 ..HighlightStyle::default()
10084 },
10085 ..EditorStyle::default()
10086 },
10087 ))
10088 .into_any_element()
10089 }
10090 }),
10091 disposition: BlockDisposition::Below,
10092 priority: 0,
10093 }],
10094 Some(Autoscroll::fit()),
10095 cx,
10096 )[0];
10097 this.pending_rename = Some(RenameState {
10098 range,
10099 old_name,
10100 editor: rename_editor,
10101 block_id,
10102 });
10103 })?;
10104 }
10105
10106 Ok(())
10107 }))
10108 }
10109
10110 pub fn confirm_rename(
10111 &mut self,
10112 _: &ConfirmRename,
10113 cx: &mut ViewContext<Self>,
10114 ) -> Option<Task<Result<()>>> {
10115 let rename = self.take_rename(false, cx)?;
10116 let workspace = self.workspace()?;
10117 let (start_buffer, start) = self
10118 .buffer
10119 .read(cx)
10120 .text_anchor_for_position(rename.range.start, cx)?;
10121 let (end_buffer, end) = self
10122 .buffer
10123 .read(cx)
10124 .text_anchor_for_position(rename.range.end, cx)?;
10125 if start_buffer != end_buffer {
10126 return None;
10127 }
10128
10129 let buffer = start_buffer;
10130 let range = start..end;
10131 let old_name = rename.old_name;
10132 let new_name = rename.editor.read(cx).text(cx);
10133
10134 let rename = workspace
10135 .read(cx)
10136 .project()
10137 .clone()
10138 .update(cx, |project, cx| {
10139 project.perform_rename(buffer.clone(), range.start, new_name.clone(), true, cx)
10140 });
10141 let workspace = workspace.downgrade();
10142
10143 Some(cx.spawn(|editor, mut cx| async move {
10144 let project_transaction = rename.await?;
10145 Self::open_project_transaction(
10146 &editor,
10147 workspace,
10148 project_transaction,
10149 format!("Rename: {} → {}", old_name, new_name),
10150 cx.clone(),
10151 )
10152 .await?;
10153
10154 editor.update(&mut cx, |editor, cx| {
10155 editor.refresh_document_highlights(cx);
10156 })?;
10157 Ok(())
10158 }))
10159 }
10160
10161 fn take_rename(
10162 &mut self,
10163 moving_cursor: bool,
10164 cx: &mut ViewContext<Self>,
10165 ) -> Option<RenameState> {
10166 let rename = self.pending_rename.take()?;
10167 if rename.editor.focus_handle(cx).is_focused(cx) {
10168 cx.focus(&self.focus_handle);
10169 }
10170
10171 self.remove_blocks(
10172 [rename.block_id].into_iter().collect(),
10173 Some(Autoscroll::fit()),
10174 cx,
10175 );
10176 self.clear_highlights::<Rename>(cx);
10177 self.show_local_selections = true;
10178
10179 if moving_cursor {
10180 let rename_editor = rename.editor.read(cx);
10181 let cursor_in_rename_editor = rename_editor.selections.newest::<usize>(cx).head();
10182
10183 // Update the selection to match the position of the selection inside
10184 // the rename editor.
10185 let snapshot = self.buffer.read(cx).read(cx);
10186 let rename_range = rename.range.to_offset(&snapshot);
10187 let cursor_in_editor = snapshot
10188 .clip_offset(rename_range.start + cursor_in_rename_editor, Bias::Left)
10189 .min(rename_range.end);
10190 drop(snapshot);
10191
10192 self.change_selections(None, cx, |s| {
10193 s.select_ranges(vec![cursor_in_editor..cursor_in_editor])
10194 });
10195 } else {
10196 self.refresh_document_highlights(cx);
10197 }
10198
10199 Some(rename)
10200 }
10201
10202 pub fn pending_rename(&self) -> Option<&RenameState> {
10203 self.pending_rename.as_ref()
10204 }
10205
10206 fn format(&mut self, _: &Format, cx: &mut ViewContext<Self>) -> Option<Task<Result<()>>> {
10207 let project = match &self.project {
10208 Some(project) => project.clone(),
10209 None => return None,
10210 };
10211
10212 Some(self.perform_format(project, FormatTrigger::Manual, cx))
10213 }
10214
10215 fn perform_format(
10216 &mut self,
10217 project: Model<Project>,
10218 trigger: FormatTrigger,
10219 cx: &mut ViewContext<Self>,
10220 ) -> Task<Result<()>> {
10221 let buffer = self.buffer().clone();
10222 let mut buffers = buffer.read(cx).all_buffers();
10223 if trigger == FormatTrigger::Save {
10224 buffers.retain(|buffer| buffer.read(cx).is_dirty());
10225 }
10226
10227 let mut timeout = cx.background_executor().timer(FORMAT_TIMEOUT).fuse();
10228 let format = project.update(cx, |project, cx| project.format(buffers, true, trigger, cx));
10229
10230 cx.spawn(|_, mut cx| async move {
10231 let transaction = futures::select_biased! {
10232 () = timeout => {
10233 log::warn!("timed out waiting for formatting");
10234 None
10235 }
10236 transaction = format.log_err().fuse() => transaction,
10237 };
10238
10239 buffer
10240 .update(&mut cx, |buffer, cx| {
10241 if let Some(transaction) = transaction {
10242 if !buffer.is_singleton() {
10243 buffer.push_transaction(&transaction.0, cx);
10244 }
10245 }
10246
10247 cx.notify();
10248 })
10249 .ok();
10250
10251 Ok(())
10252 })
10253 }
10254
10255 fn restart_language_server(&mut self, _: &RestartLanguageServer, cx: &mut ViewContext<Self>) {
10256 if let Some(project) = self.project.clone() {
10257 self.buffer.update(cx, |multi_buffer, cx| {
10258 project.update(cx, |project, cx| {
10259 project.restart_language_servers_for_buffers(multi_buffer.all_buffers(), cx);
10260 });
10261 })
10262 }
10263 }
10264
10265 fn cancel_language_server_work(
10266 &mut self,
10267 _: &CancelLanguageServerWork,
10268 cx: &mut ViewContext<Self>,
10269 ) {
10270 if let Some(project) = self.project.clone() {
10271 self.buffer.update(cx, |multi_buffer, cx| {
10272 project.update(cx, |project, cx| {
10273 project.cancel_language_server_work_for_buffers(multi_buffer.all_buffers(), cx);
10274 });
10275 })
10276 }
10277 }
10278
10279 fn show_character_palette(&mut self, _: &ShowCharacterPalette, cx: &mut ViewContext<Self>) {
10280 cx.show_character_palette();
10281 }
10282
10283 fn refresh_active_diagnostics(&mut self, cx: &mut ViewContext<Editor>) {
10284 if let Some(active_diagnostics) = self.active_diagnostics.as_mut() {
10285 let buffer = self.buffer.read(cx).snapshot(cx);
10286 let primary_range_start = active_diagnostics.primary_range.start.to_offset(&buffer);
10287 let is_valid = buffer
10288 .diagnostics_in_range::<_, usize>(active_diagnostics.primary_range.clone(), false)
10289 .any(|entry| {
10290 entry.diagnostic.is_primary
10291 && !entry.range.is_empty()
10292 && entry.range.start == primary_range_start
10293 && entry.diagnostic.message == active_diagnostics.primary_message
10294 });
10295
10296 if is_valid != active_diagnostics.is_valid {
10297 active_diagnostics.is_valid = is_valid;
10298 let mut new_styles = HashMap::default();
10299 for (block_id, diagnostic) in &active_diagnostics.blocks {
10300 new_styles.insert(
10301 *block_id,
10302 diagnostic_block_renderer(diagnostic.clone(), None, true, is_valid),
10303 );
10304 }
10305 self.display_map.update(cx, |display_map, _cx| {
10306 display_map.replace_blocks(new_styles)
10307 });
10308 }
10309 }
10310 }
10311
10312 fn activate_diagnostics(&mut self, group_id: usize, cx: &mut ViewContext<Self>) -> bool {
10313 self.dismiss_diagnostics(cx);
10314 let snapshot = self.snapshot(cx);
10315 self.active_diagnostics = self.display_map.update(cx, |display_map, cx| {
10316 let buffer = self.buffer.read(cx).snapshot(cx);
10317
10318 let mut primary_range = None;
10319 let mut primary_message = None;
10320 let mut group_end = Point::zero();
10321 let diagnostic_group = buffer
10322 .diagnostic_group::<MultiBufferPoint>(group_id)
10323 .filter_map(|entry| {
10324 if snapshot.is_line_folded(MultiBufferRow(entry.range.start.row))
10325 && (entry.range.start.row == entry.range.end.row
10326 || snapshot.is_line_folded(MultiBufferRow(entry.range.end.row)))
10327 {
10328 return None;
10329 }
10330 if entry.range.end > group_end {
10331 group_end = entry.range.end;
10332 }
10333 if entry.diagnostic.is_primary {
10334 primary_range = Some(entry.range.clone());
10335 primary_message = Some(entry.diagnostic.message.clone());
10336 }
10337 Some(entry)
10338 })
10339 .collect::<Vec<_>>();
10340 let primary_range = primary_range?;
10341 let primary_message = primary_message?;
10342 let primary_range =
10343 buffer.anchor_after(primary_range.start)..buffer.anchor_before(primary_range.end);
10344
10345 let blocks = display_map
10346 .insert_blocks(
10347 diagnostic_group.iter().map(|entry| {
10348 let diagnostic = entry.diagnostic.clone();
10349 let message_height = diagnostic.message.matches('\n').count() as u32 + 1;
10350 BlockProperties {
10351 style: BlockStyle::Fixed,
10352 position: buffer.anchor_after(entry.range.start),
10353 height: message_height,
10354 render: diagnostic_block_renderer(diagnostic, None, true, true),
10355 disposition: BlockDisposition::Below,
10356 priority: 0,
10357 }
10358 }),
10359 cx,
10360 )
10361 .into_iter()
10362 .zip(diagnostic_group.into_iter().map(|entry| entry.diagnostic))
10363 .collect();
10364
10365 Some(ActiveDiagnosticGroup {
10366 primary_range,
10367 primary_message,
10368 group_id,
10369 blocks,
10370 is_valid: true,
10371 })
10372 });
10373 self.active_diagnostics.is_some()
10374 }
10375
10376 fn dismiss_diagnostics(&mut self, cx: &mut ViewContext<Self>) {
10377 if let Some(active_diagnostic_group) = self.active_diagnostics.take() {
10378 self.display_map.update(cx, |display_map, cx| {
10379 display_map.remove_blocks(active_diagnostic_group.blocks.into_keys().collect(), cx);
10380 });
10381 cx.notify();
10382 }
10383 }
10384
10385 pub fn set_selections_from_remote(
10386 &mut self,
10387 selections: Vec<Selection<Anchor>>,
10388 pending_selection: Option<Selection<Anchor>>,
10389 cx: &mut ViewContext<Self>,
10390 ) {
10391 let old_cursor_position = self.selections.newest_anchor().head();
10392 self.selections.change_with(cx, |s| {
10393 s.select_anchors(selections);
10394 if let Some(pending_selection) = pending_selection {
10395 s.set_pending(pending_selection, SelectMode::Character);
10396 } else {
10397 s.clear_pending();
10398 }
10399 });
10400 self.selections_did_change(false, &old_cursor_position, true, cx);
10401 }
10402
10403 fn push_to_selection_history(&mut self) {
10404 self.selection_history.push(SelectionHistoryEntry {
10405 selections: self.selections.disjoint_anchors(),
10406 select_next_state: self.select_next_state.clone(),
10407 select_prev_state: self.select_prev_state.clone(),
10408 add_selections_state: self.add_selections_state.clone(),
10409 });
10410 }
10411
10412 pub fn transact(
10413 &mut self,
10414 cx: &mut ViewContext<Self>,
10415 update: impl FnOnce(&mut Self, &mut ViewContext<Self>),
10416 ) -> Option<TransactionId> {
10417 self.start_transaction_at(Instant::now(), cx);
10418 update(self, cx);
10419 self.end_transaction_at(Instant::now(), cx)
10420 }
10421
10422 fn start_transaction_at(&mut self, now: Instant, cx: &mut ViewContext<Self>) {
10423 self.end_selection(cx);
10424 if let Some(tx_id) = self
10425 .buffer
10426 .update(cx, |buffer, cx| buffer.start_transaction_at(now, cx))
10427 {
10428 self.selection_history
10429 .insert_transaction(tx_id, self.selections.disjoint_anchors());
10430 cx.emit(EditorEvent::TransactionBegun {
10431 transaction_id: tx_id,
10432 })
10433 }
10434 }
10435
10436 fn end_transaction_at(
10437 &mut self,
10438 now: Instant,
10439 cx: &mut ViewContext<Self>,
10440 ) -> Option<TransactionId> {
10441 if let Some(transaction_id) = self
10442 .buffer
10443 .update(cx, |buffer, cx| buffer.end_transaction_at(now, cx))
10444 {
10445 if let Some((_, end_selections)) =
10446 self.selection_history.transaction_mut(transaction_id)
10447 {
10448 *end_selections = Some(self.selections.disjoint_anchors());
10449 } else {
10450 log::error!("unexpectedly ended a transaction that wasn't started by this editor");
10451 }
10452
10453 cx.emit(EditorEvent::Edited { transaction_id });
10454 Some(transaction_id)
10455 } else {
10456 None
10457 }
10458 }
10459
10460 pub fn fold(&mut self, _: &actions::Fold, cx: &mut ViewContext<Self>) {
10461 let mut fold_ranges = Vec::new();
10462
10463 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10464
10465 let selections = self.selections.all_adjusted(cx);
10466 for selection in selections {
10467 let range = selection.range().sorted();
10468 let buffer_start_row = range.start.row;
10469
10470 for row in (0..=range.end.row).rev() {
10471 if let Some((foldable_range, fold_text)) =
10472 display_map.foldable_range(MultiBufferRow(row))
10473 {
10474 if foldable_range.end.row >= buffer_start_row {
10475 fold_ranges.push((foldable_range, fold_text));
10476 if row <= range.start.row {
10477 break;
10478 }
10479 }
10480 }
10481 }
10482 }
10483
10484 self.fold_ranges(fold_ranges, true, cx);
10485 }
10486
10487 pub fn fold_at(&mut self, fold_at: &FoldAt, cx: &mut ViewContext<Self>) {
10488 let buffer_row = fold_at.buffer_row;
10489 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10490
10491 if let Some((fold_range, placeholder)) = display_map.foldable_range(buffer_row) {
10492 let autoscroll = self
10493 .selections
10494 .all::<Point>(cx)
10495 .iter()
10496 .any(|selection| fold_range.overlaps(&selection.range()));
10497
10498 self.fold_ranges([(fold_range, placeholder)], autoscroll, cx);
10499 }
10500 }
10501
10502 pub fn unfold_lines(&mut self, _: &UnfoldLines, cx: &mut ViewContext<Self>) {
10503 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10504 let buffer = &display_map.buffer_snapshot;
10505 let selections = self.selections.all::<Point>(cx);
10506 let ranges = selections
10507 .iter()
10508 .map(|s| {
10509 let range = s.display_range(&display_map).sorted();
10510 let mut start = range.start.to_point(&display_map);
10511 let mut end = range.end.to_point(&display_map);
10512 start.column = 0;
10513 end.column = buffer.line_len(MultiBufferRow(end.row));
10514 start..end
10515 })
10516 .collect::<Vec<_>>();
10517
10518 self.unfold_ranges(ranges, true, true, cx);
10519 }
10520
10521 pub fn unfold_at(&mut self, unfold_at: &UnfoldAt, cx: &mut ViewContext<Self>) {
10522 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10523
10524 let intersection_range = Point::new(unfold_at.buffer_row.0, 0)
10525 ..Point::new(
10526 unfold_at.buffer_row.0,
10527 display_map.buffer_snapshot.line_len(unfold_at.buffer_row),
10528 );
10529
10530 let autoscroll = self
10531 .selections
10532 .all::<Point>(cx)
10533 .iter()
10534 .any(|selection| selection.range().overlaps(&intersection_range));
10535
10536 self.unfold_ranges(std::iter::once(intersection_range), true, autoscroll, cx)
10537 }
10538
10539 pub fn fold_selected_ranges(&mut self, _: &FoldSelectedRanges, cx: &mut ViewContext<Self>) {
10540 let selections = self.selections.all::<Point>(cx);
10541 let display_map = self.display_map.update(cx, |map, cx| map.snapshot(cx));
10542 let line_mode = self.selections.line_mode;
10543 let ranges = selections.into_iter().map(|s| {
10544 if line_mode {
10545 let start = Point::new(s.start.row, 0);
10546 let end = Point::new(
10547 s.end.row,
10548 display_map
10549 .buffer_snapshot
10550 .line_len(MultiBufferRow(s.end.row)),
10551 );
10552 (start..end, display_map.fold_placeholder.clone())
10553 } else {
10554 (s.start..s.end, display_map.fold_placeholder.clone())
10555 }
10556 });
10557 self.fold_ranges(ranges, true, cx);
10558 }
10559
10560 pub fn fold_ranges<T: ToOffset + Clone>(
10561 &mut self,
10562 ranges: impl IntoIterator<Item = (Range<T>, FoldPlaceholder)>,
10563 auto_scroll: bool,
10564 cx: &mut ViewContext<Self>,
10565 ) {
10566 let mut fold_ranges = Vec::new();
10567 let mut buffers_affected = HashMap::default();
10568 let multi_buffer = self.buffer().read(cx);
10569 for (fold_range, fold_text) in ranges {
10570 if let Some((_, buffer, _)) =
10571 multi_buffer.excerpt_containing(fold_range.start.clone(), cx)
10572 {
10573 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10574 };
10575 fold_ranges.push((fold_range, fold_text));
10576 }
10577
10578 let mut ranges = fold_ranges.into_iter().peekable();
10579 if ranges.peek().is_some() {
10580 self.display_map.update(cx, |map, cx| map.fold(ranges, cx));
10581
10582 if auto_scroll {
10583 self.request_autoscroll(Autoscroll::fit(), cx);
10584 }
10585
10586 for buffer in buffers_affected.into_values() {
10587 self.sync_expanded_diff_hunks(buffer, cx);
10588 }
10589
10590 cx.notify();
10591
10592 if let Some(active_diagnostics) = self.active_diagnostics.take() {
10593 // Clear diagnostics block when folding a range that contains it.
10594 let snapshot = self.snapshot(cx);
10595 if snapshot.intersects_fold(active_diagnostics.primary_range.start) {
10596 drop(snapshot);
10597 self.active_diagnostics = Some(active_diagnostics);
10598 self.dismiss_diagnostics(cx);
10599 } else {
10600 self.active_diagnostics = Some(active_diagnostics);
10601 }
10602 }
10603
10604 self.scrollbar_marker_state.dirty = true;
10605 }
10606 }
10607
10608 pub fn unfold_ranges<T: ToOffset + Clone>(
10609 &mut self,
10610 ranges: impl IntoIterator<Item = Range<T>>,
10611 inclusive: bool,
10612 auto_scroll: bool,
10613 cx: &mut ViewContext<Self>,
10614 ) {
10615 let mut unfold_ranges = Vec::new();
10616 let mut buffers_affected = HashMap::default();
10617 let multi_buffer = self.buffer().read(cx);
10618 for range in ranges {
10619 if let Some((_, buffer, _)) = multi_buffer.excerpt_containing(range.start.clone(), cx) {
10620 buffers_affected.insert(buffer.read(cx).remote_id(), buffer);
10621 };
10622 unfold_ranges.push(range);
10623 }
10624
10625 let mut ranges = unfold_ranges.into_iter().peekable();
10626 if ranges.peek().is_some() {
10627 self.display_map
10628 .update(cx, |map, cx| map.unfold(ranges, inclusive, cx));
10629 if auto_scroll {
10630 self.request_autoscroll(Autoscroll::fit(), cx);
10631 }
10632
10633 for buffer in buffers_affected.into_values() {
10634 self.sync_expanded_diff_hunks(buffer, cx);
10635 }
10636
10637 cx.notify();
10638 self.scrollbar_marker_state.dirty = true;
10639 self.active_indent_guides_state.dirty = true;
10640 }
10641 }
10642
10643 pub fn default_fold_placeholder(&self, cx: &AppContext) -> FoldPlaceholder {
10644 self.display_map.read(cx).fold_placeholder.clone()
10645 }
10646
10647 pub fn set_gutter_hovered(&mut self, hovered: bool, cx: &mut ViewContext<Self>) {
10648 if hovered != self.gutter_hovered {
10649 self.gutter_hovered = hovered;
10650 cx.notify();
10651 }
10652 }
10653
10654 pub fn insert_blocks(
10655 &mut self,
10656 blocks: impl IntoIterator<Item = BlockProperties<Anchor>>,
10657 autoscroll: Option<Autoscroll>,
10658 cx: &mut ViewContext<Self>,
10659 ) -> Vec<CustomBlockId> {
10660 let blocks = self
10661 .display_map
10662 .update(cx, |display_map, cx| display_map.insert_blocks(blocks, cx));
10663 if let Some(autoscroll) = autoscroll {
10664 self.request_autoscroll(autoscroll, cx);
10665 }
10666 cx.notify();
10667 blocks
10668 }
10669
10670 pub fn resize_blocks(
10671 &mut self,
10672 heights: HashMap<CustomBlockId, u32>,
10673 autoscroll: Option<Autoscroll>,
10674 cx: &mut ViewContext<Self>,
10675 ) {
10676 self.display_map
10677 .update(cx, |display_map, cx| display_map.resize_blocks(heights, cx));
10678 if let Some(autoscroll) = autoscroll {
10679 self.request_autoscroll(autoscroll, cx);
10680 }
10681 cx.notify();
10682 }
10683
10684 pub fn replace_blocks(
10685 &mut self,
10686 renderers: HashMap<CustomBlockId, RenderBlock>,
10687 autoscroll: Option<Autoscroll>,
10688 cx: &mut ViewContext<Self>,
10689 ) {
10690 self.display_map
10691 .update(cx, |display_map, _cx| display_map.replace_blocks(renderers));
10692 if let Some(autoscroll) = autoscroll {
10693 self.request_autoscroll(autoscroll, cx);
10694 }
10695 cx.notify();
10696 }
10697
10698 pub fn remove_blocks(
10699 &mut self,
10700 block_ids: HashSet<CustomBlockId>,
10701 autoscroll: Option<Autoscroll>,
10702 cx: &mut ViewContext<Self>,
10703 ) {
10704 self.display_map.update(cx, |display_map, cx| {
10705 display_map.remove_blocks(block_ids, cx)
10706 });
10707 if let Some(autoscroll) = autoscroll {
10708 self.request_autoscroll(autoscroll, cx);
10709 }
10710 cx.notify();
10711 }
10712
10713 pub fn row_for_block(
10714 &self,
10715 block_id: CustomBlockId,
10716 cx: &mut ViewContext<Self>,
10717 ) -> Option<DisplayRow> {
10718 self.display_map
10719 .update(cx, |map, cx| map.row_for_block(block_id, cx))
10720 }
10721
10722 pub(crate) fn set_focused_block(&mut self, focused_block: FocusedBlock) {
10723 self.focused_block = Some(focused_block);
10724 }
10725
10726 pub(crate) fn take_focused_block(&mut self) -> Option<FocusedBlock> {
10727 self.focused_block.take()
10728 }
10729
10730 pub fn insert_creases(
10731 &mut self,
10732 creases: impl IntoIterator<Item = Crease>,
10733 cx: &mut ViewContext<Self>,
10734 ) -> Vec<CreaseId> {
10735 self.display_map
10736 .update(cx, |map, cx| map.insert_creases(creases, cx))
10737 }
10738
10739 pub fn remove_creases(
10740 &mut self,
10741 ids: impl IntoIterator<Item = CreaseId>,
10742 cx: &mut ViewContext<Self>,
10743 ) {
10744 self.display_map
10745 .update(cx, |map, cx| map.remove_creases(ids, cx));
10746 }
10747
10748 pub fn longest_row(&self, cx: &mut AppContext) -> DisplayRow {
10749 self.display_map
10750 .update(cx, |map, cx| map.snapshot(cx))
10751 .longest_row()
10752 }
10753
10754 pub fn max_point(&self, cx: &mut AppContext) -> DisplayPoint {
10755 self.display_map
10756 .update(cx, |map, cx| map.snapshot(cx))
10757 .max_point()
10758 }
10759
10760 pub fn text(&self, cx: &AppContext) -> String {
10761 self.buffer.read(cx).read(cx).text()
10762 }
10763
10764 pub fn text_option(&self, cx: &AppContext) -> Option<String> {
10765 let text = self.text(cx);
10766 let text = text.trim();
10767
10768 if text.is_empty() {
10769 return None;
10770 }
10771
10772 Some(text.to_string())
10773 }
10774
10775 pub fn set_text(&mut self, text: impl Into<Arc<str>>, cx: &mut ViewContext<Self>) {
10776 self.transact(cx, |this, cx| {
10777 this.buffer
10778 .read(cx)
10779 .as_singleton()
10780 .expect("you can only call set_text on editors for singleton buffers")
10781 .update(cx, |buffer, cx| buffer.set_text(text, cx));
10782 });
10783 }
10784
10785 pub fn display_text(&self, cx: &mut AppContext) -> String {
10786 self.display_map
10787 .update(cx, |map, cx| map.snapshot(cx))
10788 .text()
10789 }
10790
10791 pub fn wrap_guides(&self, cx: &AppContext) -> SmallVec<[(usize, bool); 2]> {
10792 let mut wrap_guides = smallvec::smallvec![];
10793
10794 if self.show_wrap_guides == Some(false) {
10795 return wrap_guides;
10796 }
10797
10798 let settings = self.buffer.read(cx).settings_at(0, cx);
10799 if settings.show_wrap_guides {
10800 if let SoftWrap::Column(soft_wrap) = self.soft_wrap_mode(cx) {
10801 wrap_guides.push((soft_wrap as usize, true));
10802 } else if let SoftWrap::Bounded(soft_wrap) = self.soft_wrap_mode(cx) {
10803 wrap_guides.push((soft_wrap as usize, true));
10804 }
10805 wrap_guides.extend(settings.wrap_guides.iter().map(|guide| (*guide, false)))
10806 }
10807
10808 wrap_guides
10809 }
10810
10811 pub fn soft_wrap_mode(&self, cx: &AppContext) -> SoftWrap {
10812 let settings = self.buffer.read(cx).settings_at(0, cx);
10813 let mode = self.soft_wrap_mode_override.unwrap_or(settings.soft_wrap);
10814 match mode {
10815 language_settings::SoftWrap::None => SoftWrap::None,
10816 language_settings::SoftWrap::PreferLine => SoftWrap::PreferLine,
10817 language_settings::SoftWrap::EditorWidth => SoftWrap::EditorWidth,
10818 language_settings::SoftWrap::PreferredLineLength => {
10819 SoftWrap::Column(settings.preferred_line_length)
10820 }
10821 language_settings::SoftWrap::Bounded => {
10822 SoftWrap::Bounded(settings.preferred_line_length)
10823 }
10824 }
10825 }
10826
10827 pub fn set_soft_wrap_mode(
10828 &mut self,
10829 mode: language_settings::SoftWrap,
10830 cx: &mut ViewContext<Self>,
10831 ) {
10832 self.soft_wrap_mode_override = Some(mode);
10833 cx.notify();
10834 }
10835
10836 pub fn set_style(&mut self, style: EditorStyle, cx: &mut ViewContext<Self>) {
10837 let rem_size = cx.rem_size();
10838 self.display_map.update(cx, |map, cx| {
10839 map.set_font(
10840 style.text.font(),
10841 style.text.font_size.to_pixels(rem_size),
10842 cx,
10843 )
10844 });
10845 self.style = Some(style);
10846 }
10847
10848 pub fn style(&self) -> Option<&EditorStyle> {
10849 self.style.as_ref()
10850 }
10851
10852 // Called by the element. This method is not designed to be called outside of the editor
10853 // element's layout code because it does not notify when rewrapping is computed synchronously.
10854 pub(crate) fn set_wrap_width(&self, width: Option<Pixels>, cx: &mut AppContext) -> bool {
10855 self.display_map
10856 .update(cx, |map, cx| map.set_wrap_width(width, cx))
10857 }
10858
10859 pub fn toggle_soft_wrap(&mut self, _: &ToggleSoftWrap, cx: &mut ViewContext<Self>) {
10860 if self.soft_wrap_mode_override.is_some() {
10861 self.soft_wrap_mode_override.take();
10862 } else {
10863 let soft_wrap = match self.soft_wrap_mode(cx) {
10864 SoftWrap::None | SoftWrap::PreferLine => language_settings::SoftWrap::EditorWidth,
10865 SoftWrap::EditorWidth | SoftWrap::Column(_) | SoftWrap::Bounded(_) => {
10866 language_settings::SoftWrap::PreferLine
10867 }
10868 };
10869 self.soft_wrap_mode_override = Some(soft_wrap);
10870 }
10871 cx.notify();
10872 }
10873
10874 pub fn toggle_tab_bar(&mut self, _: &ToggleTabBar, cx: &mut ViewContext<Self>) {
10875 let Some(workspace) = self.workspace() else {
10876 return;
10877 };
10878 let fs = workspace.read(cx).app_state().fs.clone();
10879 let current_show = TabBarSettings::get_global(cx).show;
10880 update_settings_file::<TabBarSettings>(fs, cx, move |setting, _| {
10881 setting.show = Some(!current_show);
10882 });
10883 }
10884
10885 pub fn toggle_indent_guides(&mut self, _: &ToggleIndentGuides, cx: &mut ViewContext<Self>) {
10886 let currently_enabled = self.should_show_indent_guides().unwrap_or_else(|| {
10887 self.buffer
10888 .read(cx)
10889 .settings_at(0, cx)
10890 .indent_guides
10891 .enabled
10892 });
10893 self.show_indent_guides = Some(!currently_enabled);
10894 cx.notify();
10895 }
10896
10897 fn should_show_indent_guides(&self) -> Option<bool> {
10898 self.show_indent_guides
10899 }
10900
10901 pub fn toggle_line_numbers(&mut self, _: &ToggleLineNumbers, cx: &mut ViewContext<Self>) {
10902 let mut editor_settings = EditorSettings::get_global(cx).clone();
10903 editor_settings.gutter.line_numbers = !editor_settings.gutter.line_numbers;
10904 EditorSettings::override_global(editor_settings, cx);
10905 }
10906
10907 pub fn should_use_relative_line_numbers(&self, cx: &WindowContext) -> bool {
10908 self.use_relative_line_numbers
10909 .unwrap_or(EditorSettings::get_global(cx).relative_line_numbers)
10910 }
10911
10912 pub fn toggle_relative_line_numbers(
10913 &mut self,
10914 _: &ToggleRelativeLineNumbers,
10915 cx: &mut ViewContext<Self>,
10916 ) {
10917 let is_relative = self.should_use_relative_line_numbers(cx);
10918 self.set_relative_line_number(Some(!is_relative), cx)
10919 }
10920
10921 pub fn set_relative_line_number(
10922 &mut self,
10923 is_relative: Option<bool>,
10924 cx: &mut ViewContext<Self>,
10925 ) {
10926 self.use_relative_line_numbers = is_relative;
10927 cx.notify();
10928 }
10929
10930 pub fn set_show_gutter(&mut self, show_gutter: bool, cx: &mut ViewContext<Self>) {
10931 self.show_gutter = show_gutter;
10932 cx.notify();
10933 }
10934
10935 pub fn set_show_line_numbers(&mut self, show_line_numbers: bool, cx: &mut ViewContext<Self>) {
10936 self.show_line_numbers = Some(show_line_numbers);
10937 cx.notify();
10938 }
10939
10940 pub fn set_show_git_diff_gutter(
10941 &mut self,
10942 show_git_diff_gutter: bool,
10943 cx: &mut ViewContext<Self>,
10944 ) {
10945 self.show_git_diff_gutter = Some(show_git_diff_gutter);
10946 cx.notify();
10947 }
10948
10949 pub fn set_show_code_actions(&mut self, show_code_actions: bool, cx: &mut ViewContext<Self>) {
10950 self.show_code_actions = Some(show_code_actions);
10951 cx.notify();
10952 }
10953
10954 pub fn set_show_runnables(&mut self, show_runnables: bool, cx: &mut ViewContext<Self>) {
10955 self.show_runnables = Some(show_runnables);
10956 cx.notify();
10957 }
10958
10959 pub fn set_masked(&mut self, masked: bool, cx: &mut ViewContext<Self>) {
10960 if self.display_map.read(cx).masked != masked {
10961 self.display_map.update(cx, |map, _| map.masked = masked);
10962 }
10963 cx.notify()
10964 }
10965
10966 pub fn set_show_wrap_guides(&mut self, show_wrap_guides: bool, cx: &mut ViewContext<Self>) {
10967 self.show_wrap_guides = Some(show_wrap_guides);
10968 cx.notify();
10969 }
10970
10971 pub fn set_show_indent_guides(&mut self, show_indent_guides: bool, cx: &mut ViewContext<Self>) {
10972 self.show_indent_guides = Some(show_indent_guides);
10973 cx.notify();
10974 }
10975
10976 pub fn working_directory(&self, cx: &WindowContext) -> Option<PathBuf> {
10977 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10978 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10979 if let Some(dir) = file.abs_path(cx).parent() {
10980 return Some(dir.to_owned());
10981 }
10982 }
10983
10984 if let Some(project_path) = buffer.read(cx).project_path(cx) {
10985 return Some(project_path.path.to_path_buf());
10986 }
10987 }
10988
10989 None
10990 }
10991
10992 pub fn reveal_in_finder(&mut self, _: &RevealInFileManager, cx: &mut ViewContext<Self>) {
10993 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
10994 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
10995 cx.reveal_path(&file.abs_path(cx));
10996 }
10997 }
10998 }
10999
11000 pub fn copy_path(&mut self, _: &CopyPath, cx: &mut ViewContext<Self>) {
11001 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11002 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11003 if let Some(path) = file.abs_path(cx).to_str() {
11004 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11005 }
11006 }
11007 }
11008 }
11009
11010 pub fn copy_relative_path(&mut self, _: &CopyRelativePath, cx: &mut ViewContext<Self>) {
11011 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11012 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11013 if let Some(path) = file.path().to_str() {
11014 cx.write_to_clipboard(ClipboardItem::new_string(path.to_string()));
11015 }
11016 }
11017 }
11018 }
11019
11020 pub fn toggle_git_blame(&mut self, _: &ToggleGitBlame, cx: &mut ViewContext<Self>) {
11021 self.show_git_blame_gutter = !self.show_git_blame_gutter;
11022
11023 if self.show_git_blame_gutter && !self.has_blame_entries(cx) {
11024 self.start_git_blame(true, cx);
11025 }
11026
11027 cx.notify();
11028 }
11029
11030 pub fn toggle_git_blame_inline(
11031 &mut self,
11032 _: &ToggleGitBlameInline,
11033 cx: &mut ViewContext<Self>,
11034 ) {
11035 self.toggle_git_blame_inline_internal(true, cx);
11036 cx.notify();
11037 }
11038
11039 pub fn git_blame_inline_enabled(&self) -> bool {
11040 self.git_blame_inline_enabled
11041 }
11042
11043 pub fn toggle_selection_menu(&mut self, _: &ToggleSelectionMenu, cx: &mut ViewContext<Self>) {
11044 self.show_selection_menu = self
11045 .show_selection_menu
11046 .map(|show_selections_menu| !show_selections_menu)
11047 .or_else(|| Some(!EditorSettings::get_global(cx).toolbar.selections_menu));
11048
11049 cx.notify();
11050 }
11051
11052 pub fn selection_menu_enabled(&self, cx: &AppContext) -> bool {
11053 self.show_selection_menu
11054 .unwrap_or_else(|| EditorSettings::get_global(cx).toolbar.selections_menu)
11055 }
11056
11057 fn start_git_blame(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11058 if let Some(project) = self.project.as_ref() {
11059 let Some(buffer) = self.buffer().read(cx).as_singleton() else {
11060 return;
11061 };
11062
11063 if buffer.read(cx).file().is_none() {
11064 return;
11065 }
11066
11067 let focused = self.focus_handle(cx).contains_focused(cx);
11068
11069 let project = project.clone();
11070 let blame =
11071 cx.new_model(|cx| GitBlame::new(buffer, project, user_triggered, focused, cx));
11072 self.blame_subscription = Some(cx.observe(&blame, |_, _, cx| cx.notify()));
11073 self.blame = Some(blame);
11074 }
11075 }
11076
11077 fn toggle_git_blame_inline_internal(
11078 &mut self,
11079 user_triggered: bool,
11080 cx: &mut ViewContext<Self>,
11081 ) {
11082 if self.git_blame_inline_enabled {
11083 self.git_blame_inline_enabled = false;
11084 self.show_git_blame_inline = false;
11085 self.show_git_blame_inline_delay_task.take();
11086 } else {
11087 self.git_blame_inline_enabled = true;
11088 self.start_git_blame_inline(user_triggered, cx);
11089 }
11090
11091 cx.notify();
11092 }
11093
11094 fn start_git_blame_inline(&mut self, user_triggered: bool, cx: &mut ViewContext<Self>) {
11095 self.start_git_blame(user_triggered, cx);
11096
11097 if ProjectSettings::get_global(cx)
11098 .git
11099 .inline_blame_delay()
11100 .is_some()
11101 {
11102 self.start_inline_blame_timer(cx);
11103 } else {
11104 self.show_git_blame_inline = true
11105 }
11106 }
11107
11108 pub fn blame(&self) -> Option<&Model<GitBlame>> {
11109 self.blame.as_ref()
11110 }
11111
11112 pub fn render_git_blame_gutter(&mut self, cx: &mut WindowContext) -> bool {
11113 self.show_git_blame_gutter && self.has_blame_entries(cx)
11114 }
11115
11116 pub fn render_git_blame_inline(&mut self, cx: &mut WindowContext) -> bool {
11117 self.show_git_blame_inline
11118 && self.focus_handle.is_focused(cx)
11119 && !self.newest_selection_head_on_empty_line(cx)
11120 && self.has_blame_entries(cx)
11121 }
11122
11123 fn has_blame_entries(&self, cx: &mut WindowContext) -> bool {
11124 self.blame()
11125 .map_or(false, |blame| blame.read(cx).has_generated_entries())
11126 }
11127
11128 fn newest_selection_head_on_empty_line(&mut self, cx: &mut WindowContext) -> bool {
11129 let cursor_anchor = self.selections.newest_anchor().head();
11130
11131 let snapshot = self.buffer.read(cx).snapshot(cx);
11132 let buffer_row = MultiBufferRow(cursor_anchor.to_point(&snapshot).row);
11133
11134 snapshot.line_len(buffer_row) == 0
11135 }
11136
11137 fn get_permalink_to_line(&mut self, cx: &mut ViewContext<Self>) -> Result<url::Url> {
11138 let (path, selection, repo) = maybe!({
11139 let project_handle = self.project.as_ref()?.clone();
11140 let project = project_handle.read(cx);
11141
11142 let selection = self.selections.newest::<Point>(cx);
11143 let selection_range = selection.range();
11144
11145 let (buffer, selection) = if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11146 (buffer, selection_range.start.row..selection_range.end.row)
11147 } else {
11148 let buffer_ranges = self
11149 .buffer()
11150 .read(cx)
11151 .range_to_buffer_ranges(selection_range, cx);
11152
11153 let (buffer, range, _) = if selection.reversed {
11154 buffer_ranges.first()
11155 } else {
11156 buffer_ranges.last()
11157 }?;
11158
11159 let snapshot = buffer.read(cx).snapshot();
11160 let selection = text::ToPoint::to_point(&range.start, &snapshot).row
11161 ..text::ToPoint::to_point(&range.end, &snapshot).row;
11162 (buffer.clone(), selection)
11163 };
11164
11165 let path = buffer
11166 .read(cx)
11167 .file()?
11168 .as_local()?
11169 .path()
11170 .to_str()?
11171 .to_string();
11172 let repo = project.get_repo(&buffer.read(cx).project_path(cx)?, cx)?;
11173 Some((path, selection, repo))
11174 })
11175 .ok_or_else(|| anyhow!("unable to open git repository"))?;
11176
11177 const REMOTE_NAME: &str = "origin";
11178 let origin_url = repo
11179 .remote_url(REMOTE_NAME)
11180 .ok_or_else(|| anyhow!("remote \"{REMOTE_NAME}\" not found"))?;
11181 let sha = repo
11182 .head_sha()
11183 .ok_or_else(|| anyhow!("failed to read HEAD SHA"))?;
11184
11185 let (provider, remote) =
11186 parse_git_remote_url(GitHostingProviderRegistry::default_global(cx), &origin_url)
11187 .ok_or_else(|| anyhow!("failed to parse Git remote URL"))?;
11188
11189 Ok(provider.build_permalink(
11190 remote,
11191 BuildPermalinkParams {
11192 sha: &sha,
11193 path: &path,
11194 selection: Some(selection),
11195 },
11196 ))
11197 }
11198
11199 pub fn copy_permalink_to_line(&mut self, _: &CopyPermalinkToLine, cx: &mut ViewContext<Self>) {
11200 let permalink = self.get_permalink_to_line(cx);
11201
11202 match permalink {
11203 Ok(permalink) => {
11204 cx.write_to_clipboard(ClipboardItem::new_string(permalink.to_string()));
11205 }
11206 Err(err) => {
11207 let message = format!("Failed to copy permalink: {err}");
11208
11209 Err::<(), anyhow::Error>(err).log_err();
11210
11211 if let Some(workspace) = self.workspace() {
11212 workspace.update(cx, |workspace, cx| {
11213 struct CopyPermalinkToLine;
11214
11215 workspace.show_toast(
11216 Toast::new(NotificationId::unique::<CopyPermalinkToLine>(), message),
11217 cx,
11218 )
11219 })
11220 }
11221 }
11222 }
11223 }
11224
11225 pub fn copy_file_location(&mut self, _: &CopyFileLocation, cx: &mut ViewContext<Self>) {
11226 if let Some(buffer) = self.buffer().read(cx).as_singleton() {
11227 if let Some(file) = buffer.read(cx).file().and_then(|f| f.as_local()) {
11228 if let Some(path) = file.path().to_str() {
11229 let selection = self.selections.newest::<Point>(cx).start.row + 1;
11230 cx.write_to_clipboard(ClipboardItem::new_string(format!("{path}:{selection}")));
11231 }
11232 }
11233 }
11234 }
11235
11236 pub fn open_permalink_to_line(&mut self, _: &OpenPermalinkToLine, cx: &mut ViewContext<Self>) {
11237 let permalink = self.get_permalink_to_line(cx);
11238
11239 match permalink {
11240 Ok(permalink) => {
11241 cx.open_url(permalink.as_ref());
11242 }
11243 Err(err) => {
11244 let message = format!("Failed to open permalink: {err}");
11245
11246 Err::<(), anyhow::Error>(err).log_err();
11247
11248 if let Some(workspace) = self.workspace() {
11249 workspace.update(cx, |workspace, cx| {
11250 struct OpenPermalinkToLine;
11251
11252 workspace.show_toast(
11253 Toast::new(NotificationId::unique::<OpenPermalinkToLine>(), message),
11254 cx,
11255 )
11256 })
11257 }
11258 }
11259 }
11260 }
11261
11262 /// Adds or removes (on `None` color) a highlight for the rows corresponding to the anchor range given.
11263 /// On matching anchor range, replaces the old highlight; does not clear the other existing highlights.
11264 /// If multiple anchor ranges will produce highlights for the same row, the last range added will be used.
11265 pub fn highlight_rows<T: 'static>(
11266 &mut self,
11267 rows: RangeInclusive<Anchor>,
11268 color: Option<Hsla>,
11269 should_autoscroll: bool,
11270 cx: &mut ViewContext<Self>,
11271 ) {
11272 let snapshot = self.buffer().read(cx).snapshot(cx);
11273 let row_highlights = self.highlighted_rows.entry(TypeId::of::<T>()).or_default();
11274 let existing_highlight_index = row_highlights.binary_search_by(|highlight| {
11275 highlight
11276 .range
11277 .start()
11278 .cmp(rows.start(), &snapshot)
11279 .then(highlight.range.end().cmp(rows.end(), &snapshot))
11280 });
11281 match (color, existing_highlight_index) {
11282 (Some(_), Ok(ix)) | (_, Err(ix)) => row_highlights.insert(
11283 ix,
11284 RowHighlight {
11285 index: post_inc(&mut self.highlight_order),
11286 range: rows,
11287 should_autoscroll,
11288 color,
11289 },
11290 ),
11291 (None, Ok(i)) => {
11292 row_highlights.remove(i);
11293 }
11294 }
11295 }
11296
11297 /// Clear all anchor ranges for a certain highlight context type, so no corresponding rows will be highlighted.
11298 pub fn clear_row_highlights<T: 'static>(&mut self) {
11299 self.highlighted_rows.remove(&TypeId::of::<T>());
11300 }
11301
11302 /// For a highlight given context type, gets all anchor ranges that will be used for row highlighting.
11303 pub fn highlighted_rows<T: 'static>(
11304 &self,
11305 ) -> Option<impl Iterator<Item = (&RangeInclusive<Anchor>, Option<&Hsla>)>> {
11306 Some(
11307 self.highlighted_rows
11308 .get(&TypeId::of::<T>())?
11309 .iter()
11310 .map(|highlight| (&highlight.range, highlight.color.as_ref())),
11311 )
11312 }
11313
11314 /// Merges all anchor ranges for all context types ever set, picking the last highlight added in case of a row conflict.
11315 /// Rerturns a map of display rows that are highlighted and their corresponding highlight color.
11316 /// Allows to ignore certain kinds of highlights.
11317 pub fn highlighted_display_rows(
11318 &mut self,
11319 cx: &mut WindowContext,
11320 ) -> BTreeMap<DisplayRow, Hsla> {
11321 let snapshot = self.snapshot(cx);
11322 let mut used_highlight_orders = HashMap::default();
11323 self.highlighted_rows
11324 .iter()
11325 .flat_map(|(_, highlighted_rows)| highlighted_rows.iter())
11326 .fold(
11327 BTreeMap::<DisplayRow, Hsla>::new(),
11328 |mut unique_rows, highlight| {
11329 let start_row = highlight.range.start().to_display_point(&snapshot).row();
11330 let end_row = highlight.range.end().to_display_point(&snapshot).row();
11331 for row in start_row.0..=end_row.0 {
11332 let used_index =
11333 used_highlight_orders.entry(row).or_insert(highlight.index);
11334 if highlight.index >= *used_index {
11335 *used_index = highlight.index;
11336 match highlight.color {
11337 Some(hsla) => unique_rows.insert(DisplayRow(row), hsla),
11338 None => unique_rows.remove(&DisplayRow(row)),
11339 };
11340 }
11341 }
11342 unique_rows
11343 },
11344 )
11345 }
11346
11347 pub fn highlighted_display_row_for_autoscroll(
11348 &self,
11349 snapshot: &DisplaySnapshot,
11350 ) -> Option<DisplayRow> {
11351 self.highlighted_rows
11352 .values()
11353 .flat_map(|highlighted_rows| highlighted_rows.iter())
11354 .filter_map(|highlight| {
11355 if highlight.color.is_none() || !highlight.should_autoscroll {
11356 return None;
11357 }
11358 Some(highlight.range.start().to_display_point(snapshot).row())
11359 })
11360 .min()
11361 }
11362
11363 pub fn set_search_within_ranges(
11364 &mut self,
11365 ranges: &[Range<Anchor>],
11366 cx: &mut ViewContext<Self>,
11367 ) {
11368 self.highlight_background::<SearchWithinRange>(
11369 ranges,
11370 |colors| colors.editor_document_highlight_read_background,
11371 cx,
11372 )
11373 }
11374
11375 pub fn set_breadcrumb_header(&mut self, new_header: String) {
11376 self.breadcrumb_header = Some(new_header);
11377 }
11378
11379 pub fn clear_search_within_ranges(&mut self, cx: &mut ViewContext<Self>) {
11380 self.clear_background_highlights::<SearchWithinRange>(cx);
11381 }
11382
11383 pub fn highlight_background<T: 'static>(
11384 &mut self,
11385 ranges: &[Range<Anchor>],
11386 color_fetcher: fn(&ThemeColors) -> Hsla,
11387 cx: &mut ViewContext<Self>,
11388 ) {
11389 self.background_highlights
11390 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11391 self.scrollbar_marker_state.dirty = true;
11392 cx.notify();
11393 }
11394
11395 pub fn clear_background_highlights<T: 'static>(
11396 &mut self,
11397 cx: &mut ViewContext<Self>,
11398 ) -> Option<BackgroundHighlight> {
11399 let text_highlights = self.background_highlights.remove(&TypeId::of::<T>())?;
11400 if !text_highlights.1.is_empty() {
11401 self.scrollbar_marker_state.dirty = true;
11402 cx.notify();
11403 }
11404 Some(text_highlights)
11405 }
11406
11407 pub fn highlight_gutter<T: 'static>(
11408 &mut self,
11409 ranges: &[Range<Anchor>],
11410 color_fetcher: fn(&AppContext) -> Hsla,
11411 cx: &mut ViewContext<Self>,
11412 ) {
11413 self.gutter_highlights
11414 .insert(TypeId::of::<T>(), (color_fetcher, Arc::from(ranges)));
11415 cx.notify();
11416 }
11417
11418 pub fn clear_gutter_highlights<T: 'static>(
11419 &mut self,
11420 cx: &mut ViewContext<Self>,
11421 ) -> Option<GutterHighlight> {
11422 cx.notify();
11423 self.gutter_highlights.remove(&TypeId::of::<T>())
11424 }
11425
11426 #[cfg(feature = "test-support")]
11427 pub fn all_text_background_highlights(
11428 &mut self,
11429 cx: &mut ViewContext<Self>,
11430 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11431 let snapshot = self.snapshot(cx);
11432 let buffer = &snapshot.buffer_snapshot;
11433 let start = buffer.anchor_before(0);
11434 let end = buffer.anchor_after(buffer.len());
11435 let theme = cx.theme().colors();
11436 self.background_highlights_in_range(start..end, &snapshot, theme)
11437 }
11438
11439 #[cfg(feature = "test-support")]
11440 pub fn search_background_highlights(
11441 &mut self,
11442 cx: &mut ViewContext<Self>,
11443 ) -> Vec<Range<Point>> {
11444 let snapshot = self.buffer().read(cx).snapshot(cx);
11445
11446 let highlights = self
11447 .background_highlights
11448 .get(&TypeId::of::<items::BufferSearchHighlights>());
11449
11450 if let Some((_color, ranges)) = highlights {
11451 ranges
11452 .iter()
11453 .map(|range| range.start.to_point(&snapshot)..range.end.to_point(&snapshot))
11454 .collect_vec()
11455 } else {
11456 vec![]
11457 }
11458 }
11459
11460 fn document_highlights_for_position<'a>(
11461 &'a self,
11462 position: Anchor,
11463 buffer: &'a MultiBufferSnapshot,
11464 ) -> impl 'a + Iterator<Item = &Range<Anchor>> {
11465 let read_highlights = self
11466 .background_highlights
11467 .get(&TypeId::of::<DocumentHighlightRead>())
11468 .map(|h| &h.1);
11469 let write_highlights = self
11470 .background_highlights
11471 .get(&TypeId::of::<DocumentHighlightWrite>())
11472 .map(|h| &h.1);
11473 let left_position = position.bias_left(buffer);
11474 let right_position = position.bias_right(buffer);
11475 read_highlights
11476 .into_iter()
11477 .chain(write_highlights)
11478 .flat_map(move |ranges| {
11479 let start_ix = match ranges.binary_search_by(|probe| {
11480 let cmp = probe.end.cmp(&left_position, buffer);
11481 if cmp.is_ge() {
11482 Ordering::Greater
11483 } else {
11484 Ordering::Less
11485 }
11486 }) {
11487 Ok(i) | Err(i) => i,
11488 };
11489
11490 ranges[start_ix..]
11491 .iter()
11492 .take_while(move |range| range.start.cmp(&right_position, buffer).is_le())
11493 })
11494 }
11495
11496 pub fn has_background_highlights<T: 'static>(&self) -> bool {
11497 self.background_highlights
11498 .get(&TypeId::of::<T>())
11499 .map_or(false, |(_, highlights)| !highlights.is_empty())
11500 }
11501
11502 pub fn background_highlights_in_range(
11503 &self,
11504 search_range: Range<Anchor>,
11505 display_snapshot: &DisplaySnapshot,
11506 theme: &ThemeColors,
11507 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11508 let mut results = Vec::new();
11509 for (color_fetcher, ranges) in self.background_highlights.values() {
11510 let color = color_fetcher(theme);
11511 let start_ix = match ranges.binary_search_by(|probe| {
11512 let cmp = probe
11513 .end
11514 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11515 if cmp.is_gt() {
11516 Ordering::Greater
11517 } else {
11518 Ordering::Less
11519 }
11520 }) {
11521 Ok(i) | Err(i) => i,
11522 };
11523 for range in &ranges[start_ix..] {
11524 if range
11525 .start
11526 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11527 .is_ge()
11528 {
11529 break;
11530 }
11531
11532 let start = range.start.to_display_point(display_snapshot);
11533 let end = range.end.to_display_point(display_snapshot);
11534 results.push((start..end, color))
11535 }
11536 }
11537 results
11538 }
11539
11540 pub fn background_highlight_row_ranges<T: 'static>(
11541 &self,
11542 search_range: Range<Anchor>,
11543 display_snapshot: &DisplaySnapshot,
11544 count: usize,
11545 ) -> Vec<RangeInclusive<DisplayPoint>> {
11546 let mut results = Vec::new();
11547 let Some((_, ranges)) = self.background_highlights.get(&TypeId::of::<T>()) else {
11548 return vec![];
11549 };
11550
11551 let start_ix = match ranges.binary_search_by(|probe| {
11552 let cmp = probe
11553 .end
11554 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11555 if cmp.is_gt() {
11556 Ordering::Greater
11557 } else {
11558 Ordering::Less
11559 }
11560 }) {
11561 Ok(i) | Err(i) => i,
11562 };
11563 let mut push_region = |start: Option<Point>, end: Option<Point>| {
11564 if let (Some(start_display), Some(end_display)) = (start, end) {
11565 results.push(
11566 start_display.to_display_point(display_snapshot)
11567 ..=end_display.to_display_point(display_snapshot),
11568 );
11569 }
11570 };
11571 let mut start_row: Option<Point> = None;
11572 let mut end_row: Option<Point> = None;
11573 if ranges.len() > count {
11574 return Vec::new();
11575 }
11576 for range in &ranges[start_ix..] {
11577 if range
11578 .start
11579 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11580 .is_ge()
11581 {
11582 break;
11583 }
11584 let end = range.end.to_point(&display_snapshot.buffer_snapshot);
11585 if let Some(current_row) = &end_row {
11586 if end.row == current_row.row {
11587 continue;
11588 }
11589 }
11590 let start = range.start.to_point(&display_snapshot.buffer_snapshot);
11591 if start_row.is_none() {
11592 assert_eq!(end_row, None);
11593 start_row = Some(start);
11594 end_row = Some(end);
11595 continue;
11596 }
11597 if let Some(current_end) = end_row.as_mut() {
11598 if start.row > current_end.row + 1 {
11599 push_region(start_row, end_row);
11600 start_row = Some(start);
11601 end_row = Some(end);
11602 } else {
11603 // Merge two hunks.
11604 *current_end = end;
11605 }
11606 } else {
11607 unreachable!();
11608 }
11609 }
11610 // We might still have a hunk that was not rendered (if there was a search hit on the last line)
11611 push_region(start_row, end_row);
11612 results
11613 }
11614
11615 pub fn gutter_highlights_in_range(
11616 &self,
11617 search_range: Range<Anchor>,
11618 display_snapshot: &DisplaySnapshot,
11619 cx: &AppContext,
11620 ) -> Vec<(Range<DisplayPoint>, Hsla)> {
11621 let mut results = Vec::new();
11622 for (color_fetcher, ranges) in self.gutter_highlights.values() {
11623 let color = color_fetcher(cx);
11624 let start_ix = match ranges.binary_search_by(|probe| {
11625 let cmp = probe
11626 .end
11627 .cmp(&search_range.start, &display_snapshot.buffer_snapshot);
11628 if cmp.is_gt() {
11629 Ordering::Greater
11630 } else {
11631 Ordering::Less
11632 }
11633 }) {
11634 Ok(i) | Err(i) => i,
11635 };
11636 for range in &ranges[start_ix..] {
11637 if range
11638 .start
11639 .cmp(&search_range.end, &display_snapshot.buffer_snapshot)
11640 .is_ge()
11641 {
11642 break;
11643 }
11644
11645 let start = range.start.to_display_point(display_snapshot);
11646 let end = range.end.to_display_point(display_snapshot);
11647 results.push((start..end, color))
11648 }
11649 }
11650 results
11651 }
11652
11653 /// Get the text ranges corresponding to the redaction query
11654 pub fn redacted_ranges(
11655 &self,
11656 search_range: Range<Anchor>,
11657 display_snapshot: &DisplaySnapshot,
11658 cx: &WindowContext,
11659 ) -> Vec<Range<DisplayPoint>> {
11660 display_snapshot
11661 .buffer_snapshot
11662 .redacted_ranges(search_range, |file| {
11663 if let Some(file) = file {
11664 file.is_private()
11665 && EditorSettings::get(
11666 Some(SettingsLocation {
11667 worktree_id: file.worktree_id(cx),
11668 path: file.path().as_ref(),
11669 }),
11670 cx,
11671 )
11672 .redact_private_values
11673 } else {
11674 false
11675 }
11676 })
11677 .map(|range| {
11678 range.start.to_display_point(display_snapshot)
11679 ..range.end.to_display_point(display_snapshot)
11680 })
11681 .collect()
11682 }
11683
11684 pub fn highlight_text<T: 'static>(
11685 &mut self,
11686 ranges: Vec<Range<Anchor>>,
11687 style: HighlightStyle,
11688 cx: &mut ViewContext<Self>,
11689 ) {
11690 self.display_map.update(cx, |map, _| {
11691 map.highlight_text(TypeId::of::<T>(), ranges, style)
11692 });
11693 cx.notify();
11694 }
11695
11696 pub(crate) fn highlight_inlays<T: 'static>(
11697 &mut self,
11698 highlights: Vec<InlayHighlight>,
11699 style: HighlightStyle,
11700 cx: &mut ViewContext<Self>,
11701 ) {
11702 self.display_map.update(cx, |map, _| {
11703 map.highlight_inlays(TypeId::of::<T>(), highlights, style)
11704 });
11705 cx.notify();
11706 }
11707
11708 pub fn text_highlights<'a, T: 'static>(
11709 &'a self,
11710 cx: &'a AppContext,
11711 ) -> Option<(HighlightStyle, &'a [Range<Anchor>])> {
11712 self.display_map.read(cx).text_highlights(TypeId::of::<T>())
11713 }
11714
11715 pub fn clear_highlights<T: 'static>(&mut self, cx: &mut ViewContext<Self>) {
11716 let cleared = self
11717 .display_map
11718 .update(cx, |map, _| map.clear_highlights(TypeId::of::<T>()));
11719 if cleared {
11720 cx.notify();
11721 }
11722 }
11723
11724 pub fn show_local_cursors(&self, cx: &WindowContext) -> bool {
11725 (self.read_only(cx) || self.blink_manager.read(cx).visible())
11726 && self.focus_handle.is_focused(cx)
11727 }
11728
11729 pub fn set_show_cursor_when_unfocused(&mut self, is_enabled: bool, cx: &mut ViewContext<Self>) {
11730 self.show_cursor_when_unfocused = is_enabled;
11731 cx.notify();
11732 }
11733
11734 fn on_buffer_changed(&mut self, _: Model<MultiBuffer>, cx: &mut ViewContext<Self>) {
11735 cx.notify();
11736 }
11737
11738 fn on_buffer_event(
11739 &mut self,
11740 multibuffer: Model<MultiBuffer>,
11741 event: &multi_buffer::Event,
11742 cx: &mut ViewContext<Self>,
11743 ) {
11744 match event {
11745 multi_buffer::Event::Edited {
11746 singleton_buffer_edited,
11747 } => {
11748 self.scrollbar_marker_state.dirty = true;
11749 self.active_indent_guides_state.dirty = true;
11750 self.refresh_active_diagnostics(cx);
11751 self.refresh_code_actions(cx);
11752 if self.has_active_inline_completion(cx) {
11753 self.update_visible_inline_completion(cx);
11754 }
11755 cx.emit(EditorEvent::BufferEdited);
11756 cx.emit(SearchEvent::MatchesInvalidated);
11757 if *singleton_buffer_edited {
11758 if let Some(project) = &self.project {
11759 let project = project.read(cx);
11760 #[allow(clippy::mutable_key_type)]
11761 let languages_affected = multibuffer
11762 .read(cx)
11763 .all_buffers()
11764 .into_iter()
11765 .filter_map(|buffer| {
11766 let buffer = buffer.read(cx);
11767 let language = buffer.language()?;
11768 if project.is_local_or_ssh()
11769 && project.language_servers_for_buffer(buffer, cx).count() == 0
11770 {
11771 None
11772 } else {
11773 Some(language)
11774 }
11775 })
11776 .cloned()
11777 .collect::<HashSet<_>>();
11778 if !languages_affected.is_empty() {
11779 self.refresh_inlay_hints(
11780 InlayHintRefreshReason::BufferEdited(languages_affected),
11781 cx,
11782 );
11783 }
11784 }
11785 }
11786
11787 let Some(project) = &self.project else { return };
11788 let telemetry = project.read(cx).client().telemetry().clone();
11789 refresh_linked_ranges(self, cx);
11790 telemetry.log_edit_event("editor");
11791 }
11792 multi_buffer::Event::ExcerptsAdded {
11793 buffer,
11794 predecessor,
11795 excerpts,
11796 } => {
11797 self.tasks_update_task = Some(self.refresh_runnables(cx));
11798 cx.emit(EditorEvent::ExcerptsAdded {
11799 buffer: buffer.clone(),
11800 predecessor: *predecessor,
11801 excerpts: excerpts.clone(),
11802 });
11803 self.refresh_inlay_hints(InlayHintRefreshReason::NewLinesShown, cx);
11804 }
11805 multi_buffer::Event::ExcerptsRemoved { ids } => {
11806 self.refresh_inlay_hints(InlayHintRefreshReason::ExcerptsRemoved(ids.clone()), cx);
11807 cx.emit(EditorEvent::ExcerptsRemoved { ids: ids.clone() })
11808 }
11809 multi_buffer::Event::ExcerptsEdited { ids } => {
11810 cx.emit(EditorEvent::ExcerptsEdited { ids: ids.clone() })
11811 }
11812 multi_buffer::Event::ExcerptsExpanded { ids } => {
11813 cx.emit(EditorEvent::ExcerptsExpanded { ids: ids.clone() })
11814 }
11815 multi_buffer::Event::Reparsed(buffer_id) => {
11816 self.tasks_update_task = Some(self.refresh_runnables(cx));
11817
11818 cx.emit(EditorEvent::Reparsed(*buffer_id));
11819 }
11820 multi_buffer::Event::LanguageChanged(buffer_id) => {
11821 linked_editing_ranges::refresh_linked_ranges(self, cx);
11822 cx.emit(EditorEvent::Reparsed(*buffer_id));
11823 cx.notify();
11824 }
11825 multi_buffer::Event::DirtyChanged => cx.emit(EditorEvent::DirtyChanged),
11826 multi_buffer::Event::Saved => cx.emit(EditorEvent::Saved),
11827 multi_buffer::Event::FileHandleChanged | multi_buffer::Event::Reloaded => {
11828 cx.emit(EditorEvent::TitleChanged)
11829 }
11830 multi_buffer::Event::DiffBaseChanged => {
11831 self.scrollbar_marker_state.dirty = true;
11832 cx.emit(EditorEvent::DiffBaseChanged);
11833 cx.notify();
11834 }
11835 multi_buffer::Event::DiffUpdated { buffer } => {
11836 self.sync_expanded_diff_hunks(buffer.clone(), cx);
11837 cx.notify();
11838 }
11839 multi_buffer::Event::Closed => cx.emit(EditorEvent::Closed),
11840 multi_buffer::Event::DiagnosticsUpdated => {
11841 self.refresh_active_diagnostics(cx);
11842 self.scrollbar_marker_state.dirty = true;
11843 cx.notify();
11844 }
11845 _ => {}
11846 };
11847 }
11848
11849 fn on_display_map_changed(&mut self, _: Model<DisplayMap>, cx: &mut ViewContext<Self>) {
11850 cx.notify();
11851 }
11852
11853 fn settings_changed(&mut self, cx: &mut ViewContext<Self>) {
11854 self.tasks_update_task = Some(self.refresh_runnables(cx));
11855 self.refresh_inline_completion(true, false, cx);
11856 self.refresh_inlay_hints(
11857 InlayHintRefreshReason::SettingsChange(inlay_hint_settings(
11858 self.selections.newest_anchor().head(),
11859 &self.buffer.read(cx).snapshot(cx),
11860 cx,
11861 )),
11862 cx,
11863 );
11864 let editor_settings = EditorSettings::get_global(cx);
11865 if let Some(cursor_shape) = editor_settings.cursor_shape {
11866 self.cursor_shape = cursor_shape;
11867 }
11868 self.scroll_manager.vertical_scroll_margin = editor_settings.vertical_scroll_margin;
11869 self.show_breadcrumbs = editor_settings.toolbar.breadcrumbs;
11870
11871 let project_settings = ProjectSettings::get_global(cx);
11872 self.serialize_dirty_buffers = project_settings.session.restore_unsaved_buffers;
11873
11874 if self.mode == EditorMode::Full {
11875 let inline_blame_enabled = project_settings.git.inline_blame_enabled();
11876 if self.git_blame_inline_enabled != inline_blame_enabled {
11877 self.toggle_git_blame_inline_internal(false, cx);
11878 }
11879 }
11880
11881 cx.notify();
11882 }
11883
11884 pub fn set_searchable(&mut self, searchable: bool) {
11885 self.searchable = searchable;
11886 }
11887
11888 pub fn searchable(&self) -> bool {
11889 self.searchable
11890 }
11891
11892 fn open_proposed_changes_editor(
11893 &mut self,
11894 _: &OpenProposedChangesEditor,
11895 cx: &mut ViewContext<Self>,
11896 ) {
11897 let Some(workspace) = self.workspace() else {
11898 cx.propagate();
11899 return;
11900 };
11901
11902 let buffer = self.buffer.read(cx);
11903 let mut new_selections_by_buffer = HashMap::default();
11904 for selection in self.selections.all::<usize>(cx) {
11905 for (buffer, mut range, _) in
11906 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11907 {
11908 if selection.reversed {
11909 mem::swap(&mut range.start, &mut range.end);
11910 }
11911 let mut range = range.to_point(buffer.read(cx));
11912 range.start.column = 0;
11913 range.end.column = buffer.read(cx).line_len(range.end.row);
11914 new_selections_by_buffer
11915 .entry(buffer)
11916 .or_insert(Vec::new())
11917 .push(range)
11918 }
11919 }
11920
11921 let proposed_changes_buffers = new_selections_by_buffer
11922 .into_iter()
11923 .map(|(buffer, ranges)| ProposedChangesBuffer { buffer, ranges })
11924 .collect::<Vec<_>>();
11925 let proposed_changes_editor = cx.new_view(|cx| {
11926 ProposedChangesEditor::new(proposed_changes_buffers, self.project.clone(), cx)
11927 });
11928
11929 cx.window_context().defer(move |cx| {
11930 workspace.update(cx, |workspace, cx| {
11931 workspace.active_pane().update(cx, |pane, cx| {
11932 pane.add_item(Box::new(proposed_changes_editor), true, true, None, cx);
11933 });
11934 });
11935 });
11936 }
11937
11938 fn open_excerpts_in_split(&mut self, _: &OpenExcerptsSplit, cx: &mut ViewContext<Self>) {
11939 self.open_excerpts_common(true, cx)
11940 }
11941
11942 fn open_excerpts(&mut self, _: &OpenExcerpts, cx: &mut ViewContext<Self>) {
11943 self.open_excerpts_common(false, cx)
11944 }
11945
11946 fn open_excerpts_common(&mut self, split: bool, cx: &mut ViewContext<Self>) {
11947 let buffer = self.buffer.read(cx);
11948 if buffer.is_singleton() {
11949 cx.propagate();
11950 return;
11951 }
11952
11953 let Some(workspace) = self.workspace() else {
11954 cx.propagate();
11955 return;
11956 };
11957
11958 let mut new_selections_by_buffer = HashMap::default();
11959 for selection in self.selections.all::<usize>(cx) {
11960 for (buffer, mut range, _) in
11961 buffer.range_to_buffer_ranges(selection.start..selection.end, cx)
11962 {
11963 if selection.reversed {
11964 mem::swap(&mut range.start, &mut range.end);
11965 }
11966 new_selections_by_buffer
11967 .entry(buffer)
11968 .or_insert(Vec::new())
11969 .push(range)
11970 }
11971 }
11972
11973 // We defer the pane interaction because we ourselves are a workspace item
11974 // and activating a new item causes the pane to call a method on us reentrantly,
11975 // which panics if we're on the stack.
11976 cx.window_context().defer(move |cx| {
11977 workspace.update(cx, |workspace, cx| {
11978 let pane = if split {
11979 workspace.adjacent_pane(cx)
11980 } else {
11981 workspace.active_pane().clone()
11982 };
11983
11984 for (buffer, ranges) in new_selections_by_buffer {
11985 let editor =
11986 workspace.open_project_item::<Self>(pane.clone(), buffer, true, true, cx);
11987 editor.update(cx, |editor, cx| {
11988 editor.change_selections(Some(Autoscroll::newest()), cx, |s| {
11989 s.select_ranges(ranges);
11990 });
11991 });
11992 }
11993 })
11994 });
11995 }
11996
11997 fn jump(
11998 &mut self,
11999 path: ProjectPath,
12000 position: Point,
12001 anchor: language::Anchor,
12002 offset_from_top: u32,
12003 cx: &mut ViewContext<Self>,
12004 ) {
12005 let workspace = self.workspace();
12006 cx.spawn(|_, mut cx| async move {
12007 let workspace = workspace.ok_or_else(|| anyhow!("cannot jump without workspace"))?;
12008 let editor = workspace.update(&mut cx, |workspace, cx| {
12009 // Reset the preview item id before opening the new item
12010 workspace.active_pane().update(cx, |pane, cx| {
12011 pane.set_preview_item_id(None, cx);
12012 });
12013 workspace.open_path_preview(path, None, true, true, cx)
12014 })?;
12015 let editor = editor
12016 .await?
12017 .downcast::<Editor>()
12018 .ok_or_else(|| anyhow!("opened item was not an editor"))?
12019 .downgrade();
12020 editor.update(&mut cx, |editor, cx| {
12021 let buffer = editor
12022 .buffer()
12023 .read(cx)
12024 .as_singleton()
12025 .ok_or_else(|| anyhow!("cannot jump in a multi-buffer"))?;
12026 let buffer = buffer.read(cx);
12027 let cursor = if buffer.can_resolve(&anchor) {
12028 language::ToPoint::to_point(&anchor, buffer)
12029 } else {
12030 buffer.clip_point(position, Bias::Left)
12031 };
12032
12033 let nav_history = editor.nav_history.take();
12034 editor.change_selections(
12035 Some(Autoscroll::top_relative(offset_from_top as usize)),
12036 cx,
12037 |s| {
12038 s.select_ranges([cursor..cursor]);
12039 },
12040 );
12041 editor.nav_history = nav_history;
12042
12043 anyhow::Ok(())
12044 })??;
12045
12046 anyhow::Ok(())
12047 })
12048 .detach_and_log_err(cx);
12049 }
12050
12051 fn marked_text_ranges(&self, cx: &AppContext) -> Option<Vec<Range<OffsetUtf16>>> {
12052 let snapshot = self.buffer.read(cx).read(cx);
12053 let (_, ranges) = self.text_highlights::<InputComposition>(cx)?;
12054 Some(
12055 ranges
12056 .iter()
12057 .map(move |range| {
12058 range.start.to_offset_utf16(&snapshot)..range.end.to_offset_utf16(&snapshot)
12059 })
12060 .collect(),
12061 )
12062 }
12063
12064 fn selection_replacement_ranges(
12065 &self,
12066 range: Range<OffsetUtf16>,
12067 cx: &AppContext,
12068 ) -> Vec<Range<OffsetUtf16>> {
12069 let selections = self.selections.all::<OffsetUtf16>(cx);
12070 let newest_selection = selections
12071 .iter()
12072 .max_by_key(|selection| selection.id)
12073 .unwrap();
12074 let start_delta = range.start.0 as isize - newest_selection.start.0 as isize;
12075 let end_delta = range.end.0 as isize - newest_selection.end.0 as isize;
12076 let snapshot = self.buffer.read(cx).read(cx);
12077 selections
12078 .into_iter()
12079 .map(|mut selection| {
12080 selection.start.0 =
12081 (selection.start.0 as isize).saturating_add(start_delta) as usize;
12082 selection.end.0 = (selection.end.0 as isize).saturating_add(end_delta) as usize;
12083 snapshot.clip_offset_utf16(selection.start, Bias::Left)
12084 ..snapshot.clip_offset_utf16(selection.end, Bias::Right)
12085 })
12086 .collect()
12087 }
12088
12089 fn report_editor_event(
12090 &self,
12091 operation: &'static str,
12092 file_extension: Option<String>,
12093 cx: &AppContext,
12094 ) {
12095 if cfg!(any(test, feature = "test-support")) {
12096 return;
12097 }
12098
12099 let Some(project) = &self.project else { return };
12100
12101 // If None, we are in a file without an extension
12102 let file = self
12103 .buffer
12104 .read(cx)
12105 .as_singleton()
12106 .and_then(|b| b.read(cx).file());
12107 let file_extension = file_extension.or(file
12108 .as_ref()
12109 .and_then(|file| Path::new(file.file_name(cx)).extension())
12110 .and_then(|e| e.to_str())
12111 .map(|a| a.to_string()));
12112
12113 let vim_mode = cx
12114 .global::<SettingsStore>()
12115 .raw_user_settings()
12116 .get("vim_mode")
12117 == Some(&serde_json::Value::Bool(true));
12118
12119 let copilot_enabled = all_language_settings(file, cx).inline_completions.provider
12120 == language::language_settings::InlineCompletionProvider::Copilot;
12121 let copilot_enabled_for_language = self
12122 .buffer
12123 .read(cx)
12124 .settings_at(0, cx)
12125 .show_inline_completions;
12126
12127 let telemetry = project.read(cx).client().telemetry().clone();
12128 telemetry.report_editor_event(
12129 file_extension,
12130 vim_mode,
12131 operation,
12132 copilot_enabled,
12133 copilot_enabled_for_language,
12134 )
12135 }
12136
12137 /// Copy the highlighted chunks to the clipboard as JSON. The format is an array of lines,
12138 /// with each line being an array of {text, highlight} objects.
12139 fn copy_highlight_json(&mut self, _: &CopyHighlightJson, cx: &mut ViewContext<Self>) {
12140 let Some(buffer) = self.buffer.read(cx).as_singleton() else {
12141 return;
12142 };
12143
12144 #[derive(Serialize)]
12145 struct Chunk<'a> {
12146 text: String,
12147 highlight: Option<&'a str>,
12148 }
12149
12150 let snapshot = buffer.read(cx).snapshot();
12151 let range = self
12152 .selected_text_range(false, cx)
12153 .and_then(|selection| {
12154 if selection.range.is_empty() {
12155 None
12156 } else {
12157 Some(selection.range)
12158 }
12159 })
12160 .unwrap_or_else(|| 0..snapshot.len());
12161
12162 let chunks = snapshot.chunks(range, true);
12163 let mut lines = Vec::new();
12164 let mut line: VecDeque<Chunk> = VecDeque::new();
12165
12166 let Some(style) = self.style.as_ref() else {
12167 return;
12168 };
12169
12170 for chunk in chunks {
12171 let highlight = chunk
12172 .syntax_highlight_id
12173 .and_then(|id| id.name(&style.syntax));
12174 let mut chunk_lines = chunk.text.split('\n').peekable();
12175 while let Some(text) = chunk_lines.next() {
12176 let mut merged_with_last_token = false;
12177 if let Some(last_token) = line.back_mut() {
12178 if last_token.highlight == highlight {
12179 last_token.text.push_str(text);
12180 merged_with_last_token = true;
12181 }
12182 }
12183
12184 if !merged_with_last_token {
12185 line.push_back(Chunk {
12186 text: text.into(),
12187 highlight,
12188 });
12189 }
12190
12191 if chunk_lines.peek().is_some() {
12192 if line.len() > 1 && line.front().unwrap().text.is_empty() {
12193 line.pop_front();
12194 }
12195 if line.len() > 1 && line.back().unwrap().text.is_empty() {
12196 line.pop_back();
12197 }
12198
12199 lines.push(mem::take(&mut line));
12200 }
12201 }
12202 }
12203
12204 let Some(lines) = serde_json::to_string_pretty(&lines).log_err() else {
12205 return;
12206 };
12207 cx.write_to_clipboard(ClipboardItem::new_string(lines));
12208 }
12209
12210 pub fn inlay_hint_cache(&self) -> &InlayHintCache {
12211 &self.inlay_hint_cache
12212 }
12213
12214 pub fn replay_insert_event(
12215 &mut self,
12216 text: &str,
12217 relative_utf16_range: Option<Range<isize>>,
12218 cx: &mut ViewContext<Self>,
12219 ) {
12220 if !self.input_enabled {
12221 cx.emit(EditorEvent::InputIgnored { text: text.into() });
12222 return;
12223 }
12224 if let Some(relative_utf16_range) = relative_utf16_range {
12225 let selections = self.selections.all::<OffsetUtf16>(cx);
12226 self.change_selections(None, cx, |s| {
12227 let new_ranges = selections.into_iter().map(|range| {
12228 let start = OffsetUtf16(
12229 range
12230 .head()
12231 .0
12232 .saturating_add_signed(relative_utf16_range.start),
12233 );
12234 let end = OffsetUtf16(
12235 range
12236 .head()
12237 .0
12238 .saturating_add_signed(relative_utf16_range.end),
12239 );
12240 start..end
12241 });
12242 s.select_ranges(new_ranges);
12243 });
12244 }
12245
12246 self.handle_input(text, cx);
12247 }
12248
12249 pub fn supports_inlay_hints(&self, cx: &AppContext) -> bool {
12250 let Some(project) = self.project.as_ref() else {
12251 return false;
12252 };
12253 let project = project.read(cx);
12254
12255 let mut supports = false;
12256 self.buffer().read(cx).for_each_buffer(|buffer| {
12257 if !supports {
12258 supports = project
12259 .language_servers_for_buffer(buffer.read(cx), cx)
12260 .any(
12261 |(_, server)| match server.capabilities().inlay_hint_provider {
12262 Some(lsp::OneOf::Left(enabled)) => enabled,
12263 Some(lsp::OneOf::Right(_)) => true,
12264 None => false,
12265 },
12266 )
12267 }
12268 });
12269 supports
12270 }
12271
12272 pub fn focus(&self, cx: &mut WindowContext) {
12273 cx.focus(&self.focus_handle)
12274 }
12275
12276 pub fn is_focused(&self, cx: &WindowContext) -> bool {
12277 self.focus_handle.is_focused(cx)
12278 }
12279
12280 fn handle_focus(&mut self, cx: &mut ViewContext<Self>) {
12281 cx.emit(EditorEvent::Focused);
12282
12283 if let Some(descendant) = self
12284 .last_focused_descendant
12285 .take()
12286 .and_then(|descendant| descendant.upgrade())
12287 {
12288 cx.focus(&descendant);
12289 } else {
12290 if let Some(blame) = self.blame.as_ref() {
12291 blame.update(cx, GitBlame::focus)
12292 }
12293
12294 self.blink_manager.update(cx, BlinkManager::enable);
12295 self.show_cursor_names(cx);
12296 self.buffer.update(cx, |buffer, cx| {
12297 buffer.finalize_last_transaction(cx);
12298 if self.leader_peer_id.is_none() {
12299 buffer.set_active_selections(
12300 &self.selections.disjoint_anchors(),
12301 self.selections.line_mode,
12302 self.cursor_shape,
12303 cx,
12304 );
12305 }
12306 });
12307 }
12308 }
12309
12310 fn handle_focus_in(&mut self, cx: &mut ViewContext<Self>) {
12311 cx.emit(EditorEvent::FocusedIn)
12312 }
12313
12314 fn handle_focus_out(&mut self, event: FocusOutEvent, _cx: &mut ViewContext<Self>) {
12315 if event.blurred != self.focus_handle {
12316 self.last_focused_descendant = Some(event.blurred);
12317 }
12318 }
12319
12320 pub fn handle_blur(&mut self, cx: &mut ViewContext<Self>) {
12321 self.blink_manager.update(cx, BlinkManager::disable);
12322 self.buffer
12323 .update(cx, |buffer, cx| buffer.remove_active_selections(cx));
12324
12325 if let Some(blame) = self.blame.as_ref() {
12326 blame.update(cx, GitBlame::blur)
12327 }
12328 if !self.hover_state.focused(cx) {
12329 hide_hover(self, cx);
12330 }
12331
12332 self.hide_context_menu(cx);
12333 cx.emit(EditorEvent::Blurred);
12334 cx.notify();
12335 }
12336
12337 pub fn register_action<A: Action>(
12338 &mut self,
12339 listener: impl Fn(&A, &mut WindowContext) + 'static,
12340 ) -> Subscription {
12341 let id = self.next_editor_action_id.post_inc();
12342 let listener = Arc::new(listener);
12343 self.editor_actions.borrow_mut().insert(
12344 id,
12345 Box::new(move |cx| {
12346 let cx = cx.window_context();
12347 let listener = listener.clone();
12348 cx.on_action(TypeId::of::<A>(), move |action, phase, cx| {
12349 let action = action.downcast_ref().unwrap();
12350 if phase == DispatchPhase::Bubble {
12351 listener(action, cx)
12352 }
12353 })
12354 }),
12355 );
12356
12357 let editor_actions = self.editor_actions.clone();
12358 Subscription::new(move || {
12359 editor_actions.borrow_mut().remove(&id);
12360 })
12361 }
12362
12363 pub fn file_header_size(&self) -> u32 {
12364 self.file_header_size
12365 }
12366
12367 pub fn revert(
12368 &mut self,
12369 revert_changes: HashMap<BufferId, Vec<(Range<text::Anchor>, Rope)>>,
12370 cx: &mut ViewContext<Self>,
12371 ) {
12372 self.buffer().update(cx, |multi_buffer, cx| {
12373 for (buffer_id, changes) in revert_changes {
12374 if let Some(buffer) = multi_buffer.buffer(buffer_id) {
12375 buffer.update(cx, |buffer, cx| {
12376 buffer.edit(
12377 changes.into_iter().map(|(range, text)| {
12378 (range, text.to_string().map(Arc::<str>::from))
12379 }),
12380 None,
12381 cx,
12382 );
12383 });
12384 }
12385 }
12386 });
12387 self.change_selections(None, cx, |selections| selections.refresh());
12388 }
12389
12390 pub fn to_pixel_point(
12391 &mut self,
12392 source: multi_buffer::Anchor,
12393 editor_snapshot: &EditorSnapshot,
12394 cx: &mut ViewContext<Self>,
12395 ) -> Option<gpui::Point<Pixels>> {
12396 let source_point = source.to_display_point(editor_snapshot);
12397 self.display_to_pixel_point(source_point, editor_snapshot, cx)
12398 }
12399
12400 pub fn display_to_pixel_point(
12401 &mut self,
12402 source: DisplayPoint,
12403 editor_snapshot: &EditorSnapshot,
12404 cx: &mut ViewContext<Self>,
12405 ) -> Option<gpui::Point<Pixels>> {
12406 let line_height = self.style()?.text.line_height_in_pixels(cx.rem_size());
12407 let text_layout_details = self.text_layout_details(cx);
12408 let scroll_top = text_layout_details
12409 .scroll_anchor
12410 .scroll_position(editor_snapshot)
12411 .y;
12412
12413 if source.row().as_f32() < scroll_top.floor() {
12414 return None;
12415 }
12416 let source_x = editor_snapshot.x_for_display_point(source, &text_layout_details);
12417 let source_y = line_height * (source.row().as_f32() - scroll_top);
12418 Some(gpui::Point::new(source_x, source_y))
12419 }
12420
12421 fn gutter_bounds(&self) -> Option<Bounds<Pixels>> {
12422 let bounds = self.last_bounds?;
12423 Some(element::gutter_bounds(bounds, self.gutter_dimensions))
12424 }
12425
12426 pub fn has_active_completions_menu(&self) -> bool {
12427 self.context_menu.read().as_ref().map_or(false, |menu| {
12428 menu.visible() && matches!(menu, ContextMenu::Completions(_))
12429 })
12430 }
12431
12432 pub fn register_addon<T: Addon>(&mut self, instance: T) {
12433 self.addons
12434 .insert(std::any::TypeId::of::<T>(), Box::new(instance));
12435 }
12436
12437 pub fn unregister_addon<T: Addon>(&mut self) {
12438 self.addons.remove(&std::any::TypeId::of::<T>());
12439 }
12440
12441 pub fn addon<T: Addon>(&self) -> Option<&T> {
12442 let type_id = std::any::TypeId::of::<T>();
12443 self.addons
12444 .get(&type_id)
12445 .and_then(|item| item.to_any().downcast_ref::<T>())
12446 }
12447}
12448
12449fn hunks_for_selections(
12450 multi_buffer_snapshot: &MultiBufferSnapshot,
12451 selections: &[Selection<Anchor>],
12452) -> Vec<MultiBufferDiffHunk> {
12453 let buffer_rows_for_selections = selections.iter().map(|selection| {
12454 let head = selection.head();
12455 let tail = selection.tail();
12456 let start = MultiBufferRow(tail.to_point(multi_buffer_snapshot).row);
12457 let end = MultiBufferRow(head.to_point(multi_buffer_snapshot).row);
12458 if start > end {
12459 end..start
12460 } else {
12461 start..end
12462 }
12463 });
12464
12465 hunks_for_rows(buffer_rows_for_selections, multi_buffer_snapshot)
12466}
12467
12468pub fn hunks_for_rows(
12469 rows: impl Iterator<Item = Range<MultiBufferRow>>,
12470 multi_buffer_snapshot: &MultiBufferSnapshot,
12471) -> Vec<MultiBufferDiffHunk> {
12472 let mut hunks = Vec::new();
12473 let mut processed_buffer_rows: HashMap<BufferId, HashSet<Range<text::Anchor>>> =
12474 HashMap::default();
12475 for selected_multi_buffer_rows in rows {
12476 let query_rows =
12477 selected_multi_buffer_rows.start..selected_multi_buffer_rows.end.next_row();
12478 for hunk in multi_buffer_snapshot.git_diff_hunks_in_range(query_rows.clone()) {
12479 // Deleted hunk is an empty row range, no caret can be placed there and Zed allows to revert it
12480 // when the caret is just above or just below the deleted hunk.
12481 let allow_adjacent = hunk_status(&hunk) == DiffHunkStatus::Removed;
12482 let related_to_selection = if allow_adjacent {
12483 hunk.row_range.overlaps(&query_rows)
12484 || hunk.row_range.start == query_rows.end
12485 || hunk.row_range.end == query_rows.start
12486 } else {
12487 // `selected_multi_buffer_rows` are inclusive (e.g. [2..2] means 2nd row is selected)
12488 // `hunk.row_range` is exclusive (e.g. [2..3] means 2nd row is selected)
12489 hunk.row_range.overlaps(&selected_multi_buffer_rows)
12490 || selected_multi_buffer_rows.end == hunk.row_range.start
12491 };
12492 if related_to_selection {
12493 if !processed_buffer_rows
12494 .entry(hunk.buffer_id)
12495 .or_default()
12496 .insert(hunk.buffer_range.start..hunk.buffer_range.end)
12497 {
12498 continue;
12499 }
12500 hunks.push(hunk);
12501 }
12502 }
12503 }
12504
12505 hunks
12506}
12507
12508pub trait CollaborationHub {
12509 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator>;
12510 fn user_participant_indices<'a>(
12511 &self,
12512 cx: &'a AppContext,
12513 ) -> &'a HashMap<u64, ParticipantIndex>;
12514 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString>;
12515}
12516
12517impl CollaborationHub for Model<Project> {
12518 fn collaborators<'a>(&self, cx: &'a AppContext) -> &'a HashMap<PeerId, Collaborator> {
12519 self.read(cx).collaborators()
12520 }
12521
12522 fn user_participant_indices<'a>(
12523 &self,
12524 cx: &'a AppContext,
12525 ) -> &'a HashMap<u64, ParticipantIndex> {
12526 self.read(cx).user_store().read(cx).participant_indices()
12527 }
12528
12529 fn user_names(&self, cx: &AppContext) -> HashMap<u64, SharedString> {
12530 let this = self.read(cx);
12531 let user_ids = this.collaborators().values().map(|c| c.user_id);
12532 this.user_store().read_with(cx, |user_store, cx| {
12533 user_store.participant_names(user_ids, cx)
12534 })
12535 }
12536}
12537
12538pub trait CompletionProvider {
12539 fn completions(
12540 &self,
12541 buffer: &Model<Buffer>,
12542 buffer_position: text::Anchor,
12543 trigger: CompletionContext,
12544 cx: &mut ViewContext<Editor>,
12545 ) -> Task<Result<Vec<Completion>>>;
12546
12547 fn resolve_completions(
12548 &self,
12549 buffer: Model<Buffer>,
12550 completion_indices: Vec<usize>,
12551 completions: Arc<RwLock<Box<[Completion]>>>,
12552 cx: &mut ViewContext<Editor>,
12553 ) -> Task<Result<bool>>;
12554
12555 fn apply_additional_edits_for_completion(
12556 &self,
12557 buffer: Model<Buffer>,
12558 completion: Completion,
12559 push_to_history: bool,
12560 cx: &mut ViewContext<Editor>,
12561 ) -> Task<Result<Option<language::Transaction>>>;
12562
12563 fn is_completion_trigger(
12564 &self,
12565 buffer: &Model<Buffer>,
12566 position: language::Anchor,
12567 text: &str,
12568 trigger_in_words: bool,
12569 cx: &mut ViewContext<Editor>,
12570 ) -> bool;
12571
12572 fn sort_completions(&self) -> bool {
12573 true
12574 }
12575}
12576
12577fn snippet_completions(
12578 project: &Project,
12579 buffer: &Model<Buffer>,
12580 buffer_position: text::Anchor,
12581 cx: &mut AppContext,
12582) -> Vec<Completion> {
12583 let language = buffer.read(cx).language_at(buffer_position);
12584 let language_name = language.as_ref().map(|language| language.lsp_id());
12585 let snippet_store = project.snippets().read(cx);
12586 let snippets = snippet_store.snippets_for(language_name, cx);
12587
12588 if snippets.is_empty() {
12589 return vec![];
12590 }
12591 let snapshot = buffer.read(cx).text_snapshot();
12592 let chunks = snapshot.reversed_chunks_in_range(text::Anchor::MIN..buffer_position);
12593
12594 let mut lines = chunks.lines();
12595 let Some(line_at) = lines.next().filter(|line| !line.is_empty()) else {
12596 return vec![];
12597 };
12598
12599 let scope = language.map(|language| language.default_scope());
12600 let classifier = CharClassifier::new(scope).for_completion(true);
12601 let mut last_word = line_at
12602 .chars()
12603 .rev()
12604 .take_while(|c| classifier.is_word(*c))
12605 .collect::<String>();
12606 last_word = last_word.chars().rev().collect();
12607 let as_offset = text::ToOffset::to_offset(&buffer_position, &snapshot);
12608 let to_lsp = |point: &text::Anchor| {
12609 let end = text::ToPointUtf16::to_point_utf16(point, &snapshot);
12610 point_to_lsp(end)
12611 };
12612 let lsp_end = to_lsp(&buffer_position);
12613 snippets
12614 .into_iter()
12615 .filter_map(|snippet| {
12616 let matching_prefix = snippet
12617 .prefix
12618 .iter()
12619 .find(|prefix| prefix.starts_with(&last_word))?;
12620 let start = as_offset - last_word.len();
12621 let start = snapshot.anchor_before(start);
12622 let range = start..buffer_position;
12623 let lsp_start = to_lsp(&start);
12624 let lsp_range = lsp::Range {
12625 start: lsp_start,
12626 end: lsp_end,
12627 };
12628 Some(Completion {
12629 old_range: range,
12630 new_text: snippet.body.clone(),
12631 label: CodeLabel {
12632 text: matching_prefix.clone(),
12633 runs: vec![],
12634 filter_range: 0..matching_prefix.len(),
12635 },
12636 server_id: LanguageServerId(usize::MAX),
12637 documentation: snippet.description.clone().map(Documentation::SingleLine),
12638 lsp_completion: lsp::CompletionItem {
12639 label: snippet.prefix.first().unwrap().clone(),
12640 kind: Some(CompletionItemKind::SNIPPET),
12641 label_details: snippet.description.as_ref().map(|description| {
12642 lsp::CompletionItemLabelDetails {
12643 detail: Some(description.clone()),
12644 description: None,
12645 }
12646 }),
12647 insert_text_format: Some(InsertTextFormat::SNIPPET),
12648 text_edit: Some(lsp::CompletionTextEdit::InsertAndReplace(
12649 lsp::InsertReplaceEdit {
12650 new_text: snippet.body.clone(),
12651 insert: lsp_range,
12652 replace: lsp_range,
12653 },
12654 )),
12655 filter_text: Some(snippet.body.clone()),
12656 sort_text: Some(char::MAX.to_string()),
12657 ..Default::default()
12658 },
12659 confirm: None,
12660 })
12661 })
12662 .collect()
12663}
12664
12665impl CompletionProvider for Model<Project> {
12666 fn completions(
12667 &self,
12668 buffer: &Model<Buffer>,
12669 buffer_position: text::Anchor,
12670 options: CompletionContext,
12671 cx: &mut ViewContext<Editor>,
12672 ) -> Task<Result<Vec<Completion>>> {
12673 self.update(cx, |project, cx| {
12674 let snippets = snippet_completions(project, buffer, buffer_position, cx);
12675 let project_completions = project.completions(buffer, buffer_position, options, cx);
12676 cx.background_executor().spawn(async move {
12677 let mut completions = project_completions.await?;
12678 //let snippets = snippets.into_iter().;
12679 completions.extend(snippets);
12680 Ok(completions)
12681 })
12682 })
12683 }
12684
12685 fn resolve_completions(
12686 &self,
12687 buffer: Model<Buffer>,
12688 completion_indices: Vec<usize>,
12689 completions: Arc<RwLock<Box<[Completion]>>>,
12690 cx: &mut ViewContext<Editor>,
12691 ) -> Task<Result<bool>> {
12692 self.update(cx, |project, cx| {
12693 project.resolve_completions(buffer, completion_indices, completions, cx)
12694 })
12695 }
12696
12697 fn apply_additional_edits_for_completion(
12698 &self,
12699 buffer: Model<Buffer>,
12700 completion: Completion,
12701 push_to_history: bool,
12702 cx: &mut ViewContext<Editor>,
12703 ) -> Task<Result<Option<language::Transaction>>> {
12704 self.update(cx, |project, cx| {
12705 project.apply_additional_edits_for_completion(buffer, completion, push_to_history, cx)
12706 })
12707 }
12708
12709 fn is_completion_trigger(
12710 &self,
12711 buffer: &Model<Buffer>,
12712 position: language::Anchor,
12713 text: &str,
12714 trigger_in_words: bool,
12715 cx: &mut ViewContext<Editor>,
12716 ) -> bool {
12717 if !EditorSettings::get_global(cx).show_completions_on_input {
12718 return false;
12719 }
12720
12721 let mut chars = text.chars();
12722 let char = if let Some(char) = chars.next() {
12723 char
12724 } else {
12725 return false;
12726 };
12727 if chars.next().is_some() {
12728 return false;
12729 }
12730
12731 let buffer = buffer.read(cx);
12732 let classifier = buffer
12733 .snapshot()
12734 .char_classifier_at(position)
12735 .for_completion(true);
12736 if trigger_in_words && classifier.is_word(char) {
12737 return true;
12738 }
12739
12740 buffer
12741 .completion_triggers()
12742 .iter()
12743 .any(|string| string == text)
12744 }
12745}
12746
12747fn inlay_hint_settings(
12748 location: Anchor,
12749 snapshot: &MultiBufferSnapshot,
12750 cx: &mut ViewContext<'_, Editor>,
12751) -> InlayHintSettings {
12752 let file = snapshot.file_at(location);
12753 let language = snapshot.language_at(location);
12754 let settings = all_language_settings(file, cx);
12755 settings
12756 .language(language.map(|l| l.name()).as_ref())
12757 .inlay_hints
12758}
12759
12760fn consume_contiguous_rows(
12761 contiguous_row_selections: &mut Vec<Selection<Point>>,
12762 selection: &Selection<Point>,
12763 display_map: &DisplaySnapshot,
12764 selections: &mut std::iter::Peekable<std::slice::Iter<Selection<Point>>>,
12765) -> (MultiBufferRow, MultiBufferRow) {
12766 contiguous_row_selections.push(selection.clone());
12767 let start_row = MultiBufferRow(selection.start.row);
12768 let mut end_row = ending_row(selection, display_map);
12769
12770 while let Some(next_selection) = selections.peek() {
12771 if next_selection.start.row <= end_row.0 {
12772 end_row = ending_row(next_selection, display_map);
12773 contiguous_row_selections.push(selections.next().unwrap().clone());
12774 } else {
12775 break;
12776 }
12777 }
12778 (start_row, end_row)
12779}
12780
12781fn ending_row(next_selection: &Selection<Point>, display_map: &DisplaySnapshot) -> MultiBufferRow {
12782 if next_selection.end.column > 0 || next_selection.is_empty() {
12783 MultiBufferRow(display_map.next_line_boundary(next_selection.end).0.row + 1)
12784 } else {
12785 MultiBufferRow(next_selection.end.row)
12786 }
12787}
12788
12789impl EditorSnapshot {
12790 pub fn remote_selections_in_range<'a>(
12791 &'a self,
12792 range: &'a Range<Anchor>,
12793 collaboration_hub: &dyn CollaborationHub,
12794 cx: &'a AppContext,
12795 ) -> impl 'a + Iterator<Item = RemoteSelection> {
12796 let participant_names = collaboration_hub.user_names(cx);
12797 let participant_indices = collaboration_hub.user_participant_indices(cx);
12798 let collaborators_by_peer_id = collaboration_hub.collaborators(cx);
12799 let collaborators_by_replica_id = collaborators_by_peer_id
12800 .iter()
12801 .map(|(_, collaborator)| (collaborator.replica_id, collaborator))
12802 .collect::<HashMap<_, _>>();
12803 self.buffer_snapshot
12804 .selections_in_range(range, false)
12805 .filter_map(move |(replica_id, line_mode, cursor_shape, selection)| {
12806 let collaborator = collaborators_by_replica_id.get(&replica_id)?;
12807 let participant_index = participant_indices.get(&collaborator.user_id).copied();
12808 let user_name = participant_names.get(&collaborator.user_id).cloned();
12809 Some(RemoteSelection {
12810 replica_id,
12811 selection,
12812 cursor_shape,
12813 line_mode,
12814 participant_index,
12815 peer_id: collaborator.peer_id,
12816 user_name,
12817 })
12818 })
12819 }
12820
12821 pub fn language_at<T: ToOffset>(&self, position: T) -> Option<&Arc<Language>> {
12822 self.display_snapshot.buffer_snapshot.language_at(position)
12823 }
12824
12825 pub fn is_focused(&self) -> bool {
12826 self.is_focused
12827 }
12828
12829 pub fn placeholder_text(&self) -> Option<&Arc<str>> {
12830 self.placeholder_text.as_ref()
12831 }
12832
12833 pub fn scroll_position(&self) -> gpui::Point<f32> {
12834 self.scroll_anchor.scroll_position(&self.display_snapshot)
12835 }
12836
12837 fn gutter_dimensions(
12838 &self,
12839 font_id: FontId,
12840 font_size: Pixels,
12841 em_width: Pixels,
12842 max_line_number_width: Pixels,
12843 cx: &AppContext,
12844 ) -> GutterDimensions {
12845 if !self.show_gutter {
12846 return GutterDimensions::default();
12847 }
12848 let descent = cx.text_system().descent(font_id, font_size);
12849
12850 let show_git_gutter = self.show_git_diff_gutter.unwrap_or_else(|| {
12851 matches!(
12852 ProjectSettings::get_global(cx).git.git_gutter,
12853 Some(GitGutterSetting::TrackedFiles)
12854 )
12855 });
12856 let gutter_settings = EditorSettings::get_global(cx).gutter;
12857 let show_line_numbers = self
12858 .show_line_numbers
12859 .unwrap_or(gutter_settings.line_numbers);
12860 let line_gutter_width = if show_line_numbers {
12861 // Avoid flicker-like gutter resizes when the line number gains another digit and only resize the gutter on files with N*10^5 lines.
12862 let min_width_for_number_on_gutter = em_width * 4.0;
12863 max_line_number_width.max(min_width_for_number_on_gutter)
12864 } else {
12865 0.0.into()
12866 };
12867
12868 let show_code_actions = self
12869 .show_code_actions
12870 .unwrap_or(gutter_settings.code_actions);
12871
12872 let show_runnables = self.show_runnables.unwrap_or(gutter_settings.runnables);
12873
12874 let git_blame_entries_width = self
12875 .render_git_blame_gutter
12876 .then_some(em_width * GIT_BLAME_GUTTER_WIDTH_CHARS);
12877
12878 let mut left_padding = git_blame_entries_width.unwrap_or(Pixels::ZERO);
12879 left_padding += if show_code_actions || show_runnables {
12880 em_width * 3.0
12881 } else if show_git_gutter && show_line_numbers {
12882 em_width * 2.0
12883 } else if show_git_gutter || show_line_numbers {
12884 em_width
12885 } else {
12886 px(0.)
12887 };
12888
12889 let right_padding = if gutter_settings.folds && show_line_numbers {
12890 em_width * 4.0
12891 } else if gutter_settings.folds {
12892 em_width * 3.0
12893 } else if show_line_numbers {
12894 em_width
12895 } else {
12896 px(0.)
12897 };
12898
12899 GutterDimensions {
12900 left_padding,
12901 right_padding,
12902 width: line_gutter_width + left_padding + right_padding,
12903 margin: -descent,
12904 git_blame_entries_width,
12905 }
12906 }
12907
12908 pub fn render_fold_toggle(
12909 &self,
12910 buffer_row: MultiBufferRow,
12911 row_contains_cursor: bool,
12912 editor: View<Editor>,
12913 cx: &mut WindowContext,
12914 ) -> Option<AnyElement> {
12915 let folded = self.is_line_folded(buffer_row);
12916
12917 if let Some(crease) = self
12918 .crease_snapshot
12919 .query_row(buffer_row, &self.buffer_snapshot)
12920 {
12921 let toggle_callback = Arc::new(move |folded, cx: &mut WindowContext| {
12922 if folded {
12923 editor.update(cx, |editor, cx| {
12924 editor.fold_at(&crate::FoldAt { buffer_row }, cx)
12925 });
12926 } else {
12927 editor.update(cx, |editor, cx| {
12928 editor.unfold_at(&crate::UnfoldAt { buffer_row }, cx)
12929 });
12930 }
12931 });
12932
12933 Some((crease.render_toggle)(
12934 buffer_row,
12935 folded,
12936 toggle_callback,
12937 cx,
12938 ))
12939 } else if folded
12940 || (self.starts_indent(buffer_row) && (row_contains_cursor || self.gutter_hovered))
12941 {
12942 Some(
12943 Disclosure::new(("indent-fold-indicator", buffer_row.0), !folded)
12944 .selected(folded)
12945 .on_click(cx.listener_for(&editor, move |this, _e, cx| {
12946 if folded {
12947 this.unfold_at(&UnfoldAt { buffer_row }, cx);
12948 } else {
12949 this.fold_at(&FoldAt { buffer_row }, cx);
12950 }
12951 }))
12952 .into_any_element(),
12953 )
12954 } else {
12955 None
12956 }
12957 }
12958
12959 pub fn render_crease_trailer(
12960 &self,
12961 buffer_row: MultiBufferRow,
12962 cx: &mut WindowContext,
12963 ) -> Option<AnyElement> {
12964 let folded = self.is_line_folded(buffer_row);
12965 let crease = self
12966 .crease_snapshot
12967 .query_row(buffer_row, &self.buffer_snapshot)?;
12968 Some((crease.render_trailer)(buffer_row, folded, cx))
12969 }
12970}
12971
12972impl Deref for EditorSnapshot {
12973 type Target = DisplaySnapshot;
12974
12975 fn deref(&self) -> &Self::Target {
12976 &self.display_snapshot
12977 }
12978}
12979
12980#[derive(Clone, Debug, PartialEq, Eq)]
12981pub enum EditorEvent {
12982 InputIgnored {
12983 text: Arc<str>,
12984 },
12985 InputHandled {
12986 utf16_range_to_replace: Option<Range<isize>>,
12987 text: Arc<str>,
12988 },
12989 ExcerptsAdded {
12990 buffer: Model<Buffer>,
12991 predecessor: ExcerptId,
12992 excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
12993 },
12994 ExcerptsRemoved {
12995 ids: Vec<ExcerptId>,
12996 },
12997 ExcerptsEdited {
12998 ids: Vec<ExcerptId>,
12999 },
13000 ExcerptsExpanded {
13001 ids: Vec<ExcerptId>,
13002 },
13003 BufferEdited,
13004 Edited {
13005 transaction_id: clock::Lamport,
13006 },
13007 Reparsed(BufferId),
13008 Focused,
13009 FocusedIn,
13010 Blurred,
13011 DirtyChanged,
13012 Saved,
13013 TitleChanged,
13014 DiffBaseChanged,
13015 SelectionsChanged {
13016 local: bool,
13017 },
13018 ScrollPositionChanged {
13019 local: bool,
13020 autoscroll: bool,
13021 },
13022 Closed,
13023 TransactionUndone {
13024 transaction_id: clock::Lamport,
13025 },
13026 TransactionBegun {
13027 transaction_id: clock::Lamport,
13028 },
13029}
13030
13031impl EventEmitter<EditorEvent> for Editor {}
13032
13033impl FocusableView for Editor {
13034 fn focus_handle(&self, _cx: &AppContext) -> FocusHandle {
13035 self.focus_handle.clone()
13036 }
13037}
13038
13039impl Render for Editor {
13040 fn render<'a>(&mut self, cx: &mut ViewContext<'a, Self>) -> impl IntoElement {
13041 let settings = ThemeSettings::get_global(cx);
13042
13043 let text_style = match self.mode {
13044 EditorMode::SingleLine { .. } | EditorMode::AutoHeight { .. } => TextStyle {
13045 color: cx.theme().colors().editor_foreground,
13046 font_family: settings.ui_font.family.clone(),
13047 font_features: settings.ui_font.features.clone(),
13048 font_fallbacks: settings.ui_font.fallbacks.clone(),
13049 font_size: rems(0.875).into(),
13050 font_weight: settings.ui_font.weight,
13051 line_height: relative(settings.buffer_line_height.value()),
13052 ..Default::default()
13053 },
13054 EditorMode::Full => TextStyle {
13055 color: cx.theme().colors().editor_foreground,
13056 font_family: settings.buffer_font.family.clone(),
13057 font_features: settings.buffer_font.features.clone(),
13058 font_fallbacks: settings.buffer_font.fallbacks.clone(),
13059 font_size: settings.buffer_font_size(cx).into(),
13060 font_weight: settings.buffer_font.weight,
13061 line_height: relative(settings.buffer_line_height.value()),
13062 ..Default::default()
13063 },
13064 };
13065
13066 let background = match self.mode {
13067 EditorMode::SingleLine { .. } => cx.theme().system().transparent,
13068 EditorMode::AutoHeight { max_lines: _ } => cx.theme().system().transparent,
13069 EditorMode::Full => cx.theme().colors().editor_background,
13070 };
13071
13072 EditorElement::new(
13073 cx.view(),
13074 EditorStyle {
13075 background,
13076 local_player: cx.theme().players().local(),
13077 text: text_style,
13078 scrollbar_width: EditorElement::SCROLLBAR_WIDTH,
13079 syntax: cx.theme().syntax().clone(),
13080 status: cx.theme().status().clone(),
13081 inlay_hints_style: make_inlay_hints_style(cx),
13082 suggestions_style: HighlightStyle {
13083 color: Some(cx.theme().status().predictive),
13084 ..HighlightStyle::default()
13085 },
13086 unnecessary_code_fade: ThemeSettings::get_global(cx).unnecessary_code_fade,
13087 },
13088 )
13089 }
13090}
13091
13092impl ViewInputHandler for Editor {
13093 fn text_for_range(
13094 &mut self,
13095 range_utf16: Range<usize>,
13096 cx: &mut ViewContext<Self>,
13097 ) -> Option<String> {
13098 Some(
13099 self.buffer
13100 .read(cx)
13101 .read(cx)
13102 .text_for_range(OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end))
13103 .collect(),
13104 )
13105 }
13106
13107 fn selected_text_range(
13108 &mut self,
13109 ignore_disabled_input: bool,
13110 cx: &mut ViewContext<Self>,
13111 ) -> Option<UTF16Selection> {
13112 // Prevent the IME menu from appearing when holding down an alphabetic key
13113 // while input is disabled.
13114 if !ignore_disabled_input && !self.input_enabled {
13115 return None;
13116 }
13117
13118 let selection = self.selections.newest::<OffsetUtf16>(cx);
13119 let range = selection.range();
13120
13121 Some(UTF16Selection {
13122 range: range.start.0..range.end.0,
13123 reversed: selection.reversed,
13124 })
13125 }
13126
13127 fn marked_text_range(&self, cx: &mut ViewContext<Self>) -> Option<Range<usize>> {
13128 let snapshot = self.buffer.read(cx).read(cx);
13129 let range = self.text_highlights::<InputComposition>(cx)?.1.first()?;
13130 Some(range.start.to_offset_utf16(&snapshot).0..range.end.to_offset_utf16(&snapshot).0)
13131 }
13132
13133 fn unmark_text(&mut self, cx: &mut ViewContext<Self>) {
13134 self.clear_highlights::<InputComposition>(cx);
13135 self.ime_transaction.take();
13136 }
13137
13138 fn replace_text_in_range(
13139 &mut self,
13140 range_utf16: Option<Range<usize>>,
13141 text: &str,
13142 cx: &mut ViewContext<Self>,
13143 ) {
13144 if !self.input_enabled {
13145 cx.emit(EditorEvent::InputIgnored { text: text.into() });
13146 return;
13147 }
13148
13149 self.transact(cx, |this, cx| {
13150 let new_selected_ranges = if let Some(range_utf16) = range_utf16 {
13151 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13152 Some(this.selection_replacement_ranges(range_utf16, cx))
13153 } else {
13154 this.marked_text_ranges(cx)
13155 };
13156
13157 let range_to_replace = new_selected_ranges.as_ref().and_then(|ranges_to_replace| {
13158 let newest_selection_id = this.selections.newest_anchor().id;
13159 this.selections
13160 .all::<OffsetUtf16>(cx)
13161 .iter()
13162 .zip(ranges_to_replace.iter())
13163 .find_map(|(selection, range)| {
13164 if selection.id == newest_selection_id {
13165 Some(
13166 (range.start.0 as isize - selection.head().0 as isize)
13167 ..(range.end.0 as isize - selection.head().0 as isize),
13168 )
13169 } else {
13170 None
13171 }
13172 })
13173 });
13174
13175 cx.emit(EditorEvent::InputHandled {
13176 utf16_range_to_replace: range_to_replace,
13177 text: text.into(),
13178 });
13179
13180 if let Some(new_selected_ranges) = new_selected_ranges {
13181 this.change_selections(None, cx, |selections| {
13182 selections.select_ranges(new_selected_ranges)
13183 });
13184 this.backspace(&Default::default(), cx);
13185 }
13186
13187 this.handle_input(text, cx);
13188 });
13189
13190 if let Some(transaction) = self.ime_transaction {
13191 self.buffer.update(cx, |buffer, cx| {
13192 buffer.group_until_transaction(transaction, cx);
13193 });
13194 }
13195
13196 self.unmark_text(cx);
13197 }
13198
13199 fn replace_and_mark_text_in_range(
13200 &mut self,
13201 range_utf16: Option<Range<usize>>,
13202 text: &str,
13203 new_selected_range_utf16: Option<Range<usize>>,
13204 cx: &mut ViewContext<Self>,
13205 ) {
13206 if !self.input_enabled {
13207 return;
13208 }
13209
13210 let transaction = self.transact(cx, |this, cx| {
13211 let ranges_to_replace = if let Some(mut marked_ranges) = this.marked_text_ranges(cx) {
13212 let snapshot = this.buffer.read(cx).read(cx);
13213 if let Some(relative_range_utf16) = range_utf16.as_ref() {
13214 for marked_range in &mut marked_ranges {
13215 marked_range.end.0 = marked_range.start.0 + relative_range_utf16.end;
13216 marked_range.start.0 += relative_range_utf16.start;
13217 marked_range.start =
13218 snapshot.clip_offset_utf16(marked_range.start, Bias::Left);
13219 marked_range.end =
13220 snapshot.clip_offset_utf16(marked_range.end, Bias::Right);
13221 }
13222 }
13223 Some(marked_ranges)
13224 } else if let Some(range_utf16) = range_utf16 {
13225 let range_utf16 = OffsetUtf16(range_utf16.start)..OffsetUtf16(range_utf16.end);
13226 Some(this.selection_replacement_ranges(range_utf16, cx))
13227 } else {
13228 None
13229 };
13230
13231 let range_to_replace = ranges_to_replace.as_ref().and_then(|ranges_to_replace| {
13232 let newest_selection_id = this.selections.newest_anchor().id;
13233 this.selections
13234 .all::<OffsetUtf16>(cx)
13235 .iter()
13236 .zip(ranges_to_replace.iter())
13237 .find_map(|(selection, range)| {
13238 if selection.id == newest_selection_id {
13239 Some(
13240 (range.start.0 as isize - selection.head().0 as isize)
13241 ..(range.end.0 as isize - selection.head().0 as isize),
13242 )
13243 } else {
13244 None
13245 }
13246 })
13247 });
13248
13249 cx.emit(EditorEvent::InputHandled {
13250 utf16_range_to_replace: range_to_replace,
13251 text: text.into(),
13252 });
13253
13254 if let Some(ranges) = ranges_to_replace {
13255 this.change_selections(None, cx, |s| s.select_ranges(ranges));
13256 }
13257
13258 let marked_ranges = {
13259 let snapshot = this.buffer.read(cx).read(cx);
13260 this.selections
13261 .disjoint_anchors()
13262 .iter()
13263 .map(|selection| {
13264 selection.start.bias_left(&snapshot)..selection.end.bias_right(&snapshot)
13265 })
13266 .collect::<Vec<_>>()
13267 };
13268
13269 if text.is_empty() {
13270 this.unmark_text(cx);
13271 } else {
13272 this.highlight_text::<InputComposition>(
13273 marked_ranges.clone(),
13274 HighlightStyle {
13275 underline: Some(UnderlineStyle {
13276 thickness: px(1.),
13277 color: None,
13278 wavy: false,
13279 }),
13280 ..Default::default()
13281 },
13282 cx,
13283 );
13284 }
13285
13286 // Disable auto-closing when composing text (i.e. typing a `"` on a Brazilian keyboard)
13287 let use_autoclose = this.use_autoclose;
13288 let use_auto_surround = this.use_auto_surround;
13289 this.set_use_autoclose(false);
13290 this.set_use_auto_surround(false);
13291 this.handle_input(text, cx);
13292 this.set_use_autoclose(use_autoclose);
13293 this.set_use_auto_surround(use_auto_surround);
13294
13295 if let Some(new_selected_range) = new_selected_range_utf16 {
13296 let snapshot = this.buffer.read(cx).read(cx);
13297 let new_selected_ranges = marked_ranges
13298 .into_iter()
13299 .map(|marked_range| {
13300 let insertion_start = marked_range.start.to_offset_utf16(&snapshot).0;
13301 let new_start = OffsetUtf16(new_selected_range.start + insertion_start);
13302 let new_end = OffsetUtf16(new_selected_range.end + insertion_start);
13303 snapshot.clip_offset_utf16(new_start, Bias::Left)
13304 ..snapshot.clip_offset_utf16(new_end, Bias::Right)
13305 })
13306 .collect::<Vec<_>>();
13307
13308 drop(snapshot);
13309 this.change_selections(None, cx, |selections| {
13310 selections.select_ranges(new_selected_ranges)
13311 });
13312 }
13313 });
13314
13315 self.ime_transaction = self.ime_transaction.or(transaction);
13316 if let Some(transaction) = self.ime_transaction {
13317 self.buffer.update(cx, |buffer, cx| {
13318 buffer.group_until_transaction(transaction, cx);
13319 });
13320 }
13321
13322 if self.text_highlights::<InputComposition>(cx).is_none() {
13323 self.ime_transaction.take();
13324 }
13325 }
13326
13327 fn bounds_for_range(
13328 &mut self,
13329 range_utf16: Range<usize>,
13330 element_bounds: gpui::Bounds<Pixels>,
13331 cx: &mut ViewContext<Self>,
13332 ) -> Option<gpui::Bounds<Pixels>> {
13333 let text_layout_details = self.text_layout_details(cx);
13334 let style = &text_layout_details.editor_style;
13335 let font_id = cx.text_system().resolve_font(&style.text.font());
13336 let font_size = style.text.font_size.to_pixels(cx.rem_size());
13337 let line_height = style.text.line_height_in_pixels(cx.rem_size());
13338
13339 let em_width = cx
13340 .text_system()
13341 .typographic_bounds(font_id, font_size, 'm')
13342 .unwrap()
13343 .size
13344 .width;
13345
13346 let snapshot = self.snapshot(cx);
13347 let scroll_position = snapshot.scroll_position();
13348 let scroll_left = scroll_position.x * em_width;
13349
13350 let start = OffsetUtf16(range_utf16.start).to_display_point(&snapshot);
13351 let x = snapshot.x_for_display_point(start, &text_layout_details) - scroll_left
13352 + self.gutter_dimensions.width;
13353 let y = line_height * (start.row().as_f32() - scroll_position.y);
13354
13355 Some(Bounds {
13356 origin: element_bounds.origin + point(x, y),
13357 size: size(em_width, line_height),
13358 })
13359 }
13360}
13361
13362trait SelectionExt {
13363 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint>;
13364 fn spanned_rows(
13365 &self,
13366 include_end_if_at_line_start: bool,
13367 map: &DisplaySnapshot,
13368 ) -> Range<MultiBufferRow>;
13369}
13370
13371impl<T: ToPoint + ToOffset> SelectionExt for Selection<T> {
13372 fn display_range(&self, map: &DisplaySnapshot) -> Range<DisplayPoint> {
13373 let start = self
13374 .start
13375 .to_point(&map.buffer_snapshot)
13376 .to_display_point(map);
13377 let end = self
13378 .end
13379 .to_point(&map.buffer_snapshot)
13380 .to_display_point(map);
13381 if self.reversed {
13382 end..start
13383 } else {
13384 start..end
13385 }
13386 }
13387
13388 fn spanned_rows(
13389 &self,
13390 include_end_if_at_line_start: bool,
13391 map: &DisplaySnapshot,
13392 ) -> Range<MultiBufferRow> {
13393 let start = self.start.to_point(&map.buffer_snapshot);
13394 let mut end = self.end.to_point(&map.buffer_snapshot);
13395 if !include_end_if_at_line_start && start.row != end.row && end.column == 0 {
13396 end.row -= 1;
13397 }
13398
13399 let buffer_start = map.prev_line_boundary(start).0;
13400 let buffer_end = map.next_line_boundary(end).0;
13401 MultiBufferRow(buffer_start.row)..MultiBufferRow(buffer_end.row + 1)
13402 }
13403}
13404
13405impl<T: InvalidationRegion> InvalidationStack<T> {
13406 fn invalidate<S>(&mut self, selections: &[Selection<S>], buffer: &MultiBufferSnapshot)
13407 where
13408 S: Clone + ToOffset,
13409 {
13410 while let Some(region) = self.last() {
13411 let all_selections_inside_invalidation_ranges =
13412 if selections.len() == region.ranges().len() {
13413 selections
13414 .iter()
13415 .zip(region.ranges().iter().map(|r| r.to_offset(buffer)))
13416 .all(|(selection, invalidation_range)| {
13417 let head = selection.head().to_offset(buffer);
13418 invalidation_range.start <= head && invalidation_range.end >= head
13419 })
13420 } else {
13421 false
13422 };
13423
13424 if all_selections_inside_invalidation_ranges {
13425 break;
13426 } else {
13427 self.pop();
13428 }
13429 }
13430 }
13431}
13432
13433impl<T> Default for InvalidationStack<T> {
13434 fn default() -> Self {
13435 Self(Default::default())
13436 }
13437}
13438
13439impl<T> Deref for InvalidationStack<T> {
13440 type Target = Vec<T>;
13441
13442 fn deref(&self) -> &Self::Target {
13443 &self.0
13444 }
13445}
13446
13447impl<T> DerefMut for InvalidationStack<T> {
13448 fn deref_mut(&mut self) -> &mut Self::Target {
13449 &mut self.0
13450 }
13451}
13452
13453impl InvalidationRegion for SnippetState {
13454 fn ranges(&self) -> &[Range<Anchor>] {
13455 &self.ranges[self.active_index]
13456 }
13457}
13458
13459pub fn diagnostic_block_renderer(
13460 diagnostic: Diagnostic,
13461 max_message_rows: Option<u8>,
13462 allow_closing: bool,
13463 _is_valid: bool,
13464) -> RenderBlock {
13465 let (text_without_backticks, code_ranges) =
13466 highlight_diagnostic_message(&diagnostic, max_message_rows);
13467
13468 Box::new(move |cx: &mut BlockContext| {
13469 let group_id: SharedString = cx.block_id.to_string().into();
13470
13471 let mut text_style = cx.text_style().clone();
13472 text_style.color = diagnostic_style(diagnostic.severity, cx.theme().status());
13473 let theme_settings = ThemeSettings::get_global(cx);
13474 text_style.font_family = theme_settings.buffer_font.family.clone();
13475 text_style.font_style = theme_settings.buffer_font.style;
13476 text_style.font_features = theme_settings.buffer_font.features.clone();
13477 text_style.font_weight = theme_settings.buffer_font.weight;
13478
13479 let multi_line_diagnostic = diagnostic.message.contains('\n');
13480
13481 let buttons = |diagnostic: &Diagnostic, block_id: BlockId| {
13482 if multi_line_diagnostic {
13483 v_flex()
13484 } else {
13485 h_flex()
13486 }
13487 .when(allow_closing, |div| {
13488 div.children(diagnostic.is_primary.then(|| {
13489 IconButton::new(("close-block", EntityId::from(block_id)), IconName::XCircle)
13490 .icon_color(Color::Muted)
13491 .size(ButtonSize::Compact)
13492 .style(ButtonStyle::Transparent)
13493 .visible_on_hover(group_id.clone())
13494 .on_click(move |_click, cx| cx.dispatch_action(Box::new(Cancel)))
13495 .tooltip(|cx| Tooltip::for_action("Close Diagnostics", &Cancel, cx))
13496 }))
13497 })
13498 .child(
13499 IconButton::new(("copy-block", EntityId::from(block_id)), IconName::Copy)
13500 .icon_color(Color::Muted)
13501 .size(ButtonSize::Compact)
13502 .style(ButtonStyle::Transparent)
13503 .visible_on_hover(group_id.clone())
13504 .on_click({
13505 let message = diagnostic.message.clone();
13506 move |_click, cx| {
13507 cx.write_to_clipboard(ClipboardItem::new_string(message.clone()))
13508 }
13509 })
13510 .tooltip(|cx| Tooltip::text("Copy diagnostic message", cx)),
13511 )
13512 };
13513
13514 let icon_size = buttons(&diagnostic, cx.block_id)
13515 .into_any_element()
13516 .layout_as_root(AvailableSpace::min_size(), cx);
13517
13518 h_flex()
13519 .id(cx.block_id)
13520 .group(group_id.clone())
13521 .relative()
13522 .size_full()
13523 .pl(cx.gutter_dimensions.width)
13524 .w(cx.max_width + cx.gutter_dimensions.width)
13525 .child(
13526 div()
13527 .flex()
13528 .w(cx.anchor_x - cx.gutter_dimensions.width - icon_size.width)
13529 .flex_shrink(),
13530 )
13531 .child(buttons(&diagnostic, cx.block_id))
13532 .child(div().flex().flex_shrink_0().child(
13533 StyledText::new(text_without_backticks.clone()).with_highlights(
13534 &text_style,
13535 code_ranges.iter().map(|range| {
13536 (
13537 range.clone(),
13538 HighlightStyle {
13539 font_weight: Some(FontWeight::BOLD),
13540 ..Default::default()
13541 },
13542 )
13543 }),
13544 ),
13545 ))
13546 .into_any_element()
13547 })
13548}
13549
13550pub fn highlight_diagnostic_message(
13551 diagnostic: &Diagnostic,
13552 mut max_message_rows: Option<u8>,
13553) -> (SharedString, Vec<Range<usize>>) {
13554 let mut text_without_backticks = String::new();
13555 let mut code_ranges = Vec::new();
13556
13557 if let Some(source) = &diagnostic.source {
13558 text_without_backticks.push_str(source);
13559 code_ranges.push(0..source.len());
13560 text_without_backticks.push_str(": ");
13561 }
13562
13563 let mut prev_offset = 0;
13564 let mut in_code_block = false;
13565 let has_row_limit = max_message_rows.is_some();
13566 let mut newline_indices = diagnostic
13567 .message
13568 .match_indices('\n')
13569 .filter(|_| has_row_limit)
13570 .map(|(ix, _)| ix)
13571 .fuse()
13572 .peekable();
13573
13574 for (quote_ix, _) in diagnostic
13575 .message
13576 .match_indices('`')
13577 .chain([(diagnostic.message.len(), "")])
13578 {
13579 let mut first_newline_ix = None;
13580 let mut last_newline_ix = None;
13581 while let Some(newline_ix) = newline_indices.peek() {
13582 if *newline_ix < quote_ix {
13583 if first_newline_ix.is_none() {
13584 first_newline_ix = Some(*newline_ix);
13585 }
13586 last_newline_ix = Some(*newline_ix);
13587
13588 if let Some(rows_left) = &mut max_message_rows {
13589 if *rows_left == 0 {
13590 break;
13591 } else {
13592 *rows_left -= 1;
13593 }
13594 }
13595 let _ = newline_indices.next();
13596 } else {
13597 break;
13598 }
13599 }
13600 let prev_len = text_without_backticks.len();
13601 let new_text = &diagnostic.message[prev_offset..first_newline_ix.unwrap_or(quote_ix)];
13602 text_without_backticks.push_str(new_text);
13603 if in_code_block {
13604 code_ranges.push(prev_len..text_without_backticks.len());
13605 }
13606 prev_offset = last_newline_ix.unwrap_or(quote_ix) + 1;
13607 in_code_block = !in_code_block;
13608 if first_newline_ix.map_or(false, |newline_ix| newline_ix < quote_ix) {
13609 text_without_backticks.push_str("...");
13610 break;
13611 }
13612 }
13613
13614 (text_without_backticks.into(), code_ranges)
13615}
13616
13617fn diagnostic_style(severity: DiagnosticSeverity, colors: &StatusColors) -> Hsla {
13618 match severity {
13619 DiagnosticSeverity::ERROR => colors.error,
13620 DiagnosticSeverity::WARNING => colors.warning,
13621 DiagnosticSeverity::INFORMATION => colors.info,
13622 DiagnosticSeverity::HINT => colors.info,
13623 _ => colors.ignored,
13624 }
13625}
13626
13627pub fn styled_runs_for_code_label<'a>(
13628 label: &'a CodeLabel,
13629 syntax_theme: &'a theme::SyntaxTheme,
13630) -> impl 'a + Iterator<Item = (Range<usize>, HighlightStyle)> {
13631 let fade_out = HighlightStyle {
13632 fade_out: Some(0.35),
13633 ..Default::default()
13634 };
13635
13636 let mut prev_end = label.filter_range.end;
13637 label
13638 .runs
13639 .iter()
13640 .enumerate()
13641 .flat_map(move |(ix, (range, highlight_id))| {
13642 let style = if let Some(style) = highlight_id.style(syntax_theme) {
13643 style
13644 } else {
13645 return Default::default();
13646 };
13647 let mut muted_style = style;
13648 muted_style.highlight(fade_out);
13649
13650 let mut runs = SmallVec::<[(Range<usize>, HighlightStyle); 3]>::new();
13651 if range.start >= label.filter_range.end {
13652 if range.start > prev_end {
13653 runs.push((prev_end..range.start, fade_out));
13654 }
13655 runs.push((range.clone(), muted_style));
13656 } else if range.end <= label.filter_range.end {
13657 runs.push((range.clone(), style));
13658 } else {
13659 runs.push((range.start..label.filter_range.end, style));
13660 runs.push((label.filter_range.end..range.end, muted_style));
13661 }
13662 prev_end = cmp::max(prev_end, range.end);
13663
13664 if ix + 1 == label.runs.len() && label.text.len() > prev_end {
13665 runs.push((prev_end..label.text.len(), fade_out));
13666 }
13667
13668 runs
13669 })
13670}
13671
13672pub(crate) fn split_words(text: &str) -> impl std::iter::Iterator<Item = &str> + '_ {
13673 let mut prev_index = 0;
13674 let mut prev_codepoint: Option<char> = None;
13675 text.char_indices()
13676 .chain([(text.len(), '\0')])
13677 .filter_map(move |(index, codepoint)| {
13678 let prev_codepoint = prev_codepoint.replace(codepoint)?;
13679 let is_boundary = index == text.len()
13680 || !prev_codepoint.is_uppercase() && codepoint.is_uppercase()
13681 || !prev_codepoint.is_alphanumeric() && codepoint.is_alphanumeric();
13682 if is_boundary {
13683 let chunk = &text[prev_index..index];
13684 prev_index = index;
13685 Some(chunk)
13686 } else {
13687 None
13688 }
13689 })
13690}
13691
13692pub trait RangeToAnchorExt: Sized {
13693 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor>;
13694
13695 fn to_display_points(self, snapshot: &EditorSnapshot) -> Range<DisplayPoint> {
13696 let anchor_range = self.to_anchors(&snapshot.buffer_snapshot);
13697 anchor_range.start.to_display_point(snapshot)..anchor_range.end.to_display_point(snapshot)
13698 }
13699}
13700
13701impl<T: ToOffset> RangeToAnchorExt for Range<T> {
13702 fn to_anchors(self, snapshot: &MultiBufferSnapshot) -> Range<Anchor> {
13703 let start_offset = self.start.to_offset(snapshot);
13704 let end_offset = self.end.to_offset(snapshot);
13705 if start_offset == end_offset {
13706 snapshot.anchor_before(start_offset)..snapshot.anchor_before(end_offset)
13707 } else {
13708 snapshot.anchor_after(self.start)..snapshot.anchor_before(self.end)
13709 }
13710 }
13711}
13712
13713pub trait RowExt {
13714 fn as_f32(&self) -> f32;
13715
13716 fn next_row(&self) -> Self;
13717
13718 fn previous_row(&self) -> Self;
13719
13720 fn minus(&self, other: Self) -> u32;
13721}
13722
13723impl RowExt for DisplayRow {
13724 fn as_f32(&self) -> f32 {
13725 self.0 as f32
13726 }
13727
13728 fn next_row(&self) -> Self {
13729 Self(self.0 + 1)
13730 }
13731
13732 fn previous_row(&self) -> Self {
13733 Self(self.0.saturating_sub(1))
13734 }
13735
13736 fn minus(&self, other: Self) -> u32 {
13737 self.0 - other.0
13738 }
13739}
13740
13741impl RowExt for MultiBufferRow {
13742 fn as_f32(&self) -> f32 {
13743 self.0 as f32
13744 }
13745
13746 fn next_row(&self) -> Self {
13747 Self(self.0 + 1)
13748 }
13749
13750 fn previous_row(&self) -> Self {
13751 Self(self.0.saturating_sub(1))
13752 }
13753
13754 fn minus(&self, other: Self) -> u32 {
13755 self.0 - other.0
13756 }
13757}
13758
13759trait RowRangeExt {
13760 type Row;
13761
13762 fn len(&self) -> usize;
13763
13764 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = Self::Row>;
13765}
13766
13767impl RowRangeExt for Range<MultiBufferRow> {
13768 type Row = MultiBufferRow;
13769
13770 fn len(&self) -> usize {
13771 (self.end.0 - self.start.0) as usize
13772 }
13773
13774 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = MultiBufferRow> {
13775 (self.start.0..self.end.0).map(MultiBufferRow)
13776 }
13777}
13778
13779impl RowRangeExt for Range<DisplayRow> {
13780 type Row = DisplayRow;
13781
13782 fn len(&self) -> usize {
13783 (self.end.0 - self.start.0) as usize
13784 }
13785
13786 fn iter_rows(&self) -> impl DoubleEndedIterator<Item = DisplayRow> {
13787 (self.start.0..self.end.0).map(DisplayRow)
13788 }
13789}
13790
13791fn hunk_status(hunk: &MultiBufferDiffHunk) -> DiffHunkStatus {
13792 if hunk.diff_base_byte_range.is_empty() {
13793 DiffHunkStatus::Added
13794 } else if hunk.row_range.is_empty() {
13795 DiffHunkStatus::Removed
13796 } else {
13797 DiffHunkStatus::Modified
13798 }
13799}
13800
13801/// If select range has more than one line, we
13802/// just point the cursor to range.start.
13803fn check_multiline_range(buffer: &Buffer, range: Range<usize>) -> Range<usize> {
13804 if buffer.offset_to_point(range.start).row == buffer.offset_to_point(range.end).row {
13805 range
13806 } else {
13807 range.start..range.start
13808 }
13809}